Programs & Examples On #Heap corruption

What is the default scope of a method in Java?

If you are not giving any modifier to your method then as default it will be Default modifier which has scope within package.
for more info you can refer

Do Swift-based applications work on OS X 10.9/iOS 7 and lower?

It appears Swift applications don't run on OS X 10.7. I just created a simple GUI application (a view, a lable, a button) which runs fine on Mavericks. The base SDK is set to 10.9 and the deployment target to 10.7. I copied that application from the DerivedData folder over to my 10.7 virtual machine, and it crashs when starting, show this error:

Crashed Thread:  0

Exception Codes: 0x0000000000000002, 0x0000000000000000

Application Specific Information:
dyld: launch, loading dependent libraries

    Dyld Error Message:

  Library not loaded: /System/Library/Frameworks/CoreGraphics.framework/Versions/A/CoreGraphics
  Referenced from: /Users/USER/Desktop/
  Reason: image not found

Binary Images:
       0x109c65000 -        0x109c6afff +private.Swift-Test (1.0 - 1) <649695D0-58FD-3D02-9176-2D40D4E711F2> /Users/USER/Desktop/
       0x109c83000 -        0x109dbffff +libswift_stdlib_core.dylib (1.0 - 600. <10AAC369-9404-321D-A892-49F65856D7AF> /Users/USER/Desktop/

However this message is irritating, since there's certainly a CoreGraphics library in this VM. Other applications that make heavy use of CoreGraphics work just fine.

youtube: link to display HD video by default

via Is there a way to link someone to a YouTube Video in HD 1080p quality?

Yes there is:

options are:

default|none: vq=auto;
Code for auto: vq=auto;
Code for 2160p: vq=hd2160;
Code for 1440p: vq=hd1440;
Code for 1080p: vq=hd1080;
Code for 720p: vq=hd720;
Code for 480p: vq=large;
Code for 360p: vq=medium;
Code for 240p: vq=small;

As mentioned, you have to use the /embed/ or /v/ URL.

Note: Some copyrighted content doesn't support be played in this way

How to print variables in Perl

You should always include all relevant code when asking a question. In this case, the print statement that is the center of your question. The print statement is probably the most crucial piece of information. The second most crucial piece of information is the error, which you also did not include. Next time, include both of those.

print $ids should be a fairly hard statement to mess up, but it is possible. Possible reasons:

  1. $ids is undefined. Gives the warning undefined value in print
  2. $ids is out of scope. With use strict, gives fatal warning Global variable $ids needs explicit package name, and otherwise the undefined warning from above.
  3. You forgot a semi-colon at the end of the line.
  4. You tried to do print $ids $nIds, in which case perl thinks that $ids is supposed to be a filehandle, and you get an error such as print to unopened filehandle.


1: Should not happen. It might happen if you do something like this (assuming you are not using strict):

my $var;
while (<>) {
    $Var .= $_;
print $var;

Gives the warning for undefined value, because $Var and $var are two different variables.

2: Might happen, if you do something like this:

if ($something) {
    my $var = "something happened!";
print $var;

my declares the variable inside the current block. Outside the block, it is out of scope.

3: Simple enough, common mistake, easily fixed. Easier to spot with use warnings.

4: Also a common mistake. There are a number of ways to correctly print two variables in the same print statement:

print "$var1 $var2";  # concatenation inside a double quoted string
print $var1 . $var2;  # concatenation
print $var1, $var2;   # supplying print with a list of args

Lastly, some perl magic tips for you:

use strict;
use warnings;

# open with explicit direction '<', check the return value
# to make sure open succeeded. Using a lexical filehandle.
open my $fh, '<', 'file.txt' or die $!;

# read the whole file into an array and
# chomp all the lines at once
chomp(my @file = <$fh>);
close $fh;

my $ids  = join(' ', @file);
my $nIds = scalar @file;
print "Number of lines: $nIds\n";
print "Text:\n$ids\n";

Reading the whole file into an array is suitable for small files only, otherwise it uses a lot of memory. Usually, line-by-line is preferred.


  • print "@file" is equivalent to $ids = join(' ',@file); print $ids;
  • $#file will return the last index in @file. Since arrays usually start at 0, $#file + 1 is equivalent to scalar @file.

You can also do:

my $ids;
do {
    local $/;
    $ids = <$fh>;

By temporarily "turning off" $/, the input record separator, i.e. newline, you will make <$fh> return the entire file. What <$fh> really does is read until it finds $/, then return that string. Note that this will preserve the newlines in $ids.

Line-by-line solution:

open my $fh, '<', 'file.txt' or die $!; # btw, $! contains the most recent error
my $ids;
while (<$fh>) {
    $ids .= "$_ "; # concatenate with string
my $nIds = $.; # $. is Current line number for the last filehandle accessed.

Insert default value when parameter is null

Try an if statement ...

if @value is null 
    insert into t (value) values (default)
    insert into t (value) values (@value)

How to execute a .sql script from bash

You simply need to start mysql and feed it with the content of db.sql:

mysql -u user -p < db.sql

.mp4 file not playing in chrome

Encountering the same problem, I solved this by reconverting the file with default mp4 settings in iMovie.

How can I concatenate a string within a loop in JSTL/JSP?

You're using JSTL 2.0 right? You don't need to put <c:out/> around all variables. Have you tried something like this?

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
  <c:set var="myVar" value="${myVar}${currentItem}" />

Edit: Beaten by the above

Replace None with NaN in pandas dataframe

Here's another option:

df.replace(to_replace=[None], value=np.nan, inplace=True)

C#: Assign same value to multiple variables in single statement

This will do want you want:

int num1, num2;
num1 = num2 = 5;

'num2 = 5' assignment will return the assigned value.

This allows you to do crazy things like num1 = (num2 = 5) +3; which will assign 8 to num1, although I would not recommended doing it as not be very readable.

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

read string from .resx file in C#

Open .resx file and set "Access Modifier" to Public.

var <Variable Name> = Properties.Resources.<Resource Name>

UPDATE and REPLACE part of a string

you should use the below update query

UPDATE SET Value=REPLACE(Value,'123\','') WHERE Id IN(1, 2, 3, 4)

UPDATE SET Value=REPLACE(Value,'123\','') WHERE Id <= 4

Either of the above queries should work.

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

Scripts are raw java embedded in the page code, and if you declare variables in your scripts, then they become local variables embedded in the page.

In contrast, JSTL works entirely with scoped attributes, either at page, request or session scope. You need to rework your scriptlet to fish test out as an attribute:

<c:set var="test" value="test1"/>
  String resp = "abc";
  String test = pageContext.getAttribute("test");
  resp = resp + test;
  pageContext.setAttribute("resp", resp);
<c:out value="${resp}"/>

If you look at the docs for <c:set>, you'll see you can specify scope as page, request or session, and it defaults to page.

Better yet, don't use scriptlets at all: they make the baby jesus cry.

CUDA incompatible with my gcc version

On most distributions you have the possibility to install another gcc and g++ version beside a most recent compiler like gcc-4.7. In addition most build systems are aware of the CC and CXX environment variables, which let specify you other C and C++ compilers respectively. SO I suggest something like:

CC=gcc-4.4 CXX=g++-4.4 cmake path/to/your/CMakeLists.txt

For Makefiles there should be a similar way. I do not recommend setting custom symlinks within /usr/local unless you know what you are doing.

Reordering arrays

Change 2 to 1 as the first parameter in the splice call when removing the element:

var tmp = playlist.splice(1, 1);
playlist.splice(2, 0, tmp[0]);

sqlplus how to find details of the currently connected database session

I know this is an old question but I did try all the above answers but didnt work in my case. What ultimately helped me out is

SHOW PARAMETER instance_name

How to enable native resolution for apps on iPhone 6 and 6 Plus?

An error was encountered while running (Domain = LaunchServicesError, Code = 0)

Usually this indicates that installd returned an error during the install process (bad resources or similar).

Unfortunately, Xcode does not display the actual underlying error (feel free to file dupes of this known bug).

You should check ~/Library/Logs/CoreSimulator/CoreSimulator.log which will log the underlying error for you.

Java: get greatest common divisor

You can use this implementation of Binary GCD algorithm

public class BinaryGCD {

public static int gcd(int p, int q) {
    if (q == 0) return p;
    if (p == 0) return q;

    // p and q even
    if ((p & 1) == 0 && (q & 1) == 0) return gcd(p >> 1, q >> 1) << 1;

    // p is even, q is odd
    else if ((p & 1) == 0) return gcd(p >> 1, q);

    // p is odd, q is even
    else if ((q & 1) == 0) return gcd(p, q >> 1);

    // p and q odd, p >= q
    else if (p >= q) return gcd((p-q) >> 1, q);

    // p and q odd, p < q
    else return gcd(p, (q-p) >> 1);

public static void main(String[] args) {
    int p = Integer.parseInt(args[0]);
    int q = Integer.parseInt(args[1]);
    System.out.println("gcd(" + p + ", " + q + ") = " + gcd(p, q));



How to catch a click event on a button?

Taken from:

// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
    public void onClick(View v) {
      // do something when the button is clicked

protected void onCreate(Bundle savedValues) {
    // Capture our button from layout
    Button button = (Button)findViewById(;
    // Register the onClick listener with the implementation above

How do I remove the file suffix and path portion from a path string in Bash?

Using basename assumes that you know what the file extension is, doesn't it?

And I believe that the various regular expression suggestions don't cope with a filename containing more than one "."

The following seems to cope with double dots. Oh, and filenames that contain a "/" themselves (just for kicks)

To paraphrase Pascal, "Sorry this script is so long. I didn't have time to make it shorter"

  $fullname = $ARGV[0];
  ($path,$name) = $fullname =~ /^(.*[^\\]\/)*(.*)$/;
  ($basename,$extension) = $name =~ /^(.*)(\.[^.]*)$/;
  print $basename . "\n";

When should I use the Visitor Design Pattern?

The reason for your confusion is probably that the Visitor is a fatal misnomer. Many (prominent1!) programmers have stumbled over this problem. What it actually does is implement double dispatching in languages that don't support it natively (most of them don't).

1) My favourite example is Scott Meyers, acclaimed author of “Effective C++”, who called this one of his most important C++ aha! moments ever.

Run a Python script from another Python script, passing in arguments

This is inherently the wrong thing to do. If you are running a Python script from another Python script, you should communicate through Python instead of through the OS:

import script1

In an ideal world, you will be able to call a function inside script1 directly:

for i in range(whatever):

If necessary, you can hack sys.argv. There's a neat way of doing this using a context manager to ensure that you don't make any permanent changes.

import contextlib
def redirect_argv(num):
    sys._argv = sys.argv[:]
    sys.argv = sys._argv

with redirect_argv(1):

I think this is preferable to passing all your data to the OS and back; that's just silly.

Clear terminal in Python

Why hasn't anyone talked about just simply doing Ctrl+L in Windows or Cmd+L in Mac. Surely the simplest way of clearing screen.

Calling JMX MBean method from a shell script

Potentially its easiest to write this in Java


public class JmxInvoke {

    public static void main(String... args) throws Exception {
        JMXConnectorFactory.connect(new JMXServiceURL(args[0]))
            .getMBeanServerConnection().invoke(new ObjectName(args[1]), args[2], new Object[]{}, new String[]{});    


This would compile to a single .class and needs no dependencies in server or any complicated maven packaging.

call it with

java -cp . JmxInvoke [url] [beanName] [method]

How to update fields in a model without creating a new record in django?

If you get a model instance from the database, then calling the save method will always update that instance. For example:

t = TemperatureData.objects.get(id=1)
t.value = 999  # change field # this will update only

If your goal is prevent any INSERTs, then you can override the save method, test if the primary key exists and raise an exception. See the following for more detail:

Trigger event when user scroll to specific element - with jQuery

I think your best bet would be to leverage an existing library that does that very thing:

You can add listeners to your elements that will fire off when your element hits the top of the viewport:

$('#scroll-to').waypoint(function() {
 alert('you have scrolled to the h1!');

For an amazing demo of it in use:

Send Message in C#

It doesn't sound like a good idea to use send message. I think you should try to work around the problem that the DLLs can't reference each other...

Scroll to the top of the page using JavaScript?

Better solution with smooth animation:

// this changes the scrolling behavior to "smooth"
window.scrollTo({ top: 0, behavior: 'smooth' });


PostgreSQL create table if not exists

There is no CREATE TABLE IF NOT EXISTS... but you can write a simple procedure for that, something like:

CREATE OR REPLACE FUNCTION prc_create_sch_foo_table() RETURNS VOID AS $$

EXECUTE 'CREATE TABLE /* IF NOT EXISTS add for PostgreSQL 9.1+ */ (
                    id serial NOT NULL, 
                    demo_column varchar NOT NULL, 
                    demo_column2 varchar NOT NULL,
                    CONSTRAINT pk_sch_foo PRIMARY KEY (id));
                   CREATE INDEX /* IF NOT EXISTS add for PostgreSQL 9.5+ */ idx_sch_foo_demo_column ON;
                   CREATE INDEX /* IF NOT EXISTS add for PostgreSQL 9.5+ */ idx_sch_foo_demo_column2 ON;'
               WHERE NOT EXISTS(SELECT * FROM information_schema.tables 
                        WHERE table_schema = 'sch' 
                            AND table_name = 'foo');

         EXCEPTION WHEN null_value_not_allowed THEN
           WHEN duplicate_table THEN

END; $$ LANGUAGE plpgsql;

What is the difference between SOAP 1.1, SOAP 1.2, HTTP GET & HTTP POST methods for Android?

Differences in SOAP versions

Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.

The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.

The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.

In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.

SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.

There is not difine POST AND GET method for particular android....but all here is differance

GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.

What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.

POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.

Link to original IBM source

How to use executables from a package installed locally in node_modules?

The PATH solution has the issue that if $(npm bin) is placed in your .profile/.bashrc/etc it is evaluated once and is forever set to whichever directory the path was first evaluated in. If instead you modify the current path then every time you run the script your path will grow.

To get around these issues, I create a function and used that. It doesn't modify your environment and is simple to use:

function npm-exec {
   $(npm bin)/$@  

This can then be used like this without making any changes to your environment:

npm-exec r.js <args>

Streaming video from Android camera to server

I'm looking into this as well, and while I don't have a good solution for you I did manage to dig up SIPDroid's video code:

How to convert AAR to JAR

 The 'aar' bundle is the binary distribution of an Android Library Project. .aar file 
 consists a JAR file and some resource files. You can convert it
 as .jar file using this steps

1) Copy the .aar file in a separate folder and Rename the .aar file to .zip file using 
 any winrar or zip Extractor software.

2) Now you will get a .zip file. Right click on the .zip file and select "Extract files". 
 Will get a folder which contains "classes.jar, resource, manifest,,
 proguard(optional), libs(optional), assets(optional)".

3) Rename the classes.jar file as yourjarfilename.jar and use this in your project.

Note: If you want to get only .jar file from your .aar file use the above way. Suppose If you want to include the manifest.xml and resources with your .jar file means you can just right click on your .aar file and save it as .jar file directly instead of saving it as a .zip. To view the .jar file which you have extracted, download JD-GUI(Java Decompiler). Then drag and drop your .jar file into this JD_GUI, you can see the .class file in readable formats like a .java file.

enter image description here enter image description here

What do URLs represent?

There are two ways of looking at github content, the "raw" way and the "Web page" way. returns the raw content of files stored in github, so they can be downloaded simply to your computer. For example, if the page represents a ruby install script, then you will get a ruby install script that your ruby installation will understand.

If you instead download the file using the link, you will actually be downloading a web page with buttons and comments and which displays your wanted script in the middle -- it's what you want to give to your web browser to get a nice page to look at, but for the computer, it is not a script that can be executed or code that can be compiled, but a web page to be displayed. That web page has a button called Raw that sends you to the corresponding content on

To see the content of${repo}/${branch}/${path} in the usual github interface:

  1. you replace with plain
  2. AND you insert "blob" between the repo name and the branch name.

In this case, the branch name is "master" (which is a very common branch name), so you replace /master/ with /blob/master/, and so


This is the reverse of finding a file on Github and clicking the Raw link.

Set Label Text with JQuery

The checkbox is in a td, so need to get the parent first:

$("input:checkbox").on("change", function() {

Alternatively, find a label which has a for with the same id (perhaps more performant than reverse traversal) :

$("input:checkbox").on("change", function() {
    $("label[for='" + $(this).attr('id') + "']").text("TESTTTT");

Or, to be more succinct just

$("input:checkbox").on("change", function() {
    $("label[for='" + + "']").text("TESTTTT");

Using Server.MapPath in external C# Classes in ASP.NET

This one helped for me

//System.Web.HttpContext.Current.Server.MapPath //        
FileStream fileStream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/File.txt"),
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);

DataGridView changing cell background color

dataGridView1[row, col].Style.BackColor = System.Drawing.Color.Red;

How do I disable and re-enable a button in with javascript?

function checkusers()
   var shouldEnable = document.getElementById('checkbox').value == 0;
   document.getElementById('add_button').disabled = shouldEnable;

SQL Server SELECT into existing table

If the destination table does exist but you don't want to specify column names:


            SELECT ', table1.' +  AS [text()]
            FROM sys.columns SYSCOL1
            WHERE SYSCOL1.object_id = SYSCOL2.object_id and SYSCOL1.is_identity <> 1
            ORDER BY SYSCOL1.object_id
            FOR XML PATH ('')
        ), 2, 1000)
    sys.columns SYSCOL2
    SYSCOL2.object_id = object_id('dbo.TableOne') )

SET @SQL_INSERT =  'INSERT INTO dbo.TableTwo SELECT ' + @COLUMN_LIST + ' FROM dbo.TableOne table1 WHERE col3 LIKE ' + @search_key
EXEC sp_executesql @SQL_INSERT

Selecting option by text content with jQuery

Replace this:

var cat = $.jqURL.get('category');
var $dd = $('#cbCategory');
var $options = $('option', $dd);
$options.each(function() {
if ($(this).text() == cat)
    $(this).select(); // This is where my problem is

With this:


Calling val() on a select list will automatically select the option with that value, if any.

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

Yes, there is a maximum, but it's system dependent. Try it and see, doubling until you hit a limit then searching down. At least with Sun JRE 1.6 on linux you get interesting if not always informative error messages (peregrino is netbook running 32 bit ubuntu with 2G RAM and no swap):

peregrino:$ java -Xmx4096M -cp bin WheelPrimes 
Invalid maximum heap size: -Xmx4096M
The specified size exceeds the maximum representable size.
Could not create the Java virtual machine.

peregrino:$ java -Xmx4095M -cp bin WheelPrimes 
Error occurred during initialization of VM
Incompatible minimum and maximum heap sizes specified

peregrino:$ java -Xmx4092M -cp bin WheelPrimes 
Error occurred during initialization of VM
The size of the object heap + VM data exceeds the maximum representable size

peregrino:$ java -Xmx4000M -cp bin WheelPrimes 
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

(experiment reducing from 4000M until)

peregrino:$ java -Xmx2686M -cp bin WheelPrimes 
(normal execution)

Most are self explanatory, except -Xmx4095M which is rather odd (maybe a signed/unsigned comparison?), and that it claims to reserve 2686M on a 2GB machine with no swap. But it does hint that the maximum size is 4G not 2G for a 32 bit VM, if the OS allows you to address that much.

How to access cookies in AngularJS?

AngularJS provides ngCookies module and $cookieStore service to use Browser Cookies.

We need to add angular-cookies.min.js file to use cookie feature.

Here is some method of AngularJS Cookie.

  • get(key); // This method returns the value of given cookie key.

  • getObject(key); //This method returns the deserialized value of given cookie key.

  • getAll(); //This method returns a key value object with all the cookies.

  • put(key, value, [options]); //This method sets a value for given cookie key.

  • remove(key, [options]); //This method remove given cookie.



<!DOCTYPE html>
<html ng-app="myApp">
<script src="//"></script>
<script src="//"></script>
<body ng-controller="MyController">
{{cookiesUserName}} loves {{cookietechnology}}.


var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', ['$scope', '$cookies', '$cookieStore', '$window', function($scope, $cookies, $cookieStore, $window) {
$cookies.userName = 'Max Joe';
$scope.cookiesUserName = $cookies.userName;
$cookieStore.put('technology', 'Web');
$scope.cookietechnology = $cookieStore.get('technology'); }]);

I have Taken reference from

Swift: declare an empty dictionary

If you want to create a generic dictionary with any type

var dictionaryData = [AnyHashable:Any]()

How can I remove a key from a Python dictionary?

You can use exception handling if you want to be very verbose:

    del dict[key]

except KeyError: pass

This is slower, however, than the pop() method, if the key doesn't exist.

my_dict.pop('key', None)

It won't matter for a few keys, but if you're doing this repeatedly, then the latter method is a better bet.

The fastest approach is this:

if 'key' in dict: 
    del myDict['key']

But this method is dangerous because if 'key' is removed in between the two lines, a KeyError will be raised.

How to Concatenate Numbers and Strings to Format Numbers in T-SQL?

I was tried the below query it's works for me exactly

 with cte as(

   select ROW_NUMBER() over (order by repairid) as'RN', [RepairProductId] from [Ws_RepairList]
  update CTE set [RepairProductId]= ISNULL([RepairProductId]+convert(nvarchar(10),RN),0) from cte

Add single element to array in numpy

t = np.array([2, 3])
t = np.append(t, [4])

Catch paste input

I sort of fixed it by using the following code:

$("#editor").live('input paste',function(e){
    if( == 'editor') {
        $('<textarea></textarea>').attr('id', 'paste').appendTo('#editMode');
        setTimeout($(this).paste, 250);

Now I just need to store the caret location and append to that position then I'm all set... I think :)

One-line list comprehension: if-else variants

Just another solution, hope some one may like it :

Using: [False, True][Expression]

>>> map(lambda x: [x*100, x][x % 2 != 0], range(1,10))
[1, 200, 3, 400, 5, 600, 7, 800, 9]

Where does Console.WriteLine go in ASP.NET?

if you happened to use NLog in your project, you can add a Debugger target:

    <target name="debugger" xsi:type="Debugger"
            layout="${date:format=HH\:mm\:ss}|${pad:padding=5:inner=${level:uppercase=true}}|${message} "/>

and writes logs to this target for the levels you want:

    <logger name="*" minlevel="Trace" writeTo="debugger" />

now you have console output just like Jetty in "Output" window of VS, and make sure you are running in Debug Mode(F5).

How do I create a SQL table under a different schema?

Hit F4 and you'll get what you are looking for.

base_url() function not working in codeigniter

Load url helper in controller


Get index of a key/value pair in a C# dictionary based on the value

    You can find index by key/values in dictionary
Dictionary<string, string> myDictionary = new Dictionary<string, string>();
myDictionary.Add("a", "x");
myDictionary.Add("b", "y");
int i = Array.IndexOf(myDictionary.Keys.ToArray(), "a");
int j = Array.IndexOf(myDictionary.Values.ToArray(), "y");

using if else with eval in aspx page

<%# (string)Eval("gender") =="M" ? "Male" :"Female"%>

C# - Simplest way to remove first occurrence of a substring from another string

I definitely agree that this is perfect for an extension method, but I think it can be improved a bit.

public static string Remove(this string source, string remove,  int firstN)
        if(firstN <= 0 || string.IsNullOrEmpty(source) || string.IsNullOrEmpty(remove))
            return source;
        int index = source.IndexOf(remove);
        return index < 0 ? source : source.Remove(index, remove.Length).Remove(remove, --firstN);

This does a bit of recursion which is always fun.

Here is a simple unit test as well:

    public void RemoveTwiceTest()
        string source = "look up look up look it up";
        string remove = "look";
        int firstN = 2;
        string expected = " up  up look it up";
        string actual;
        actual = source.Remove(remove, firstN);
        Assert.AreEqual(expected, actual);


Hide all warnings in ipython

I hide the warnings in the pink boxes by running the following code in a cell:

from IPython.display import HTML
function code_toggle_err() {
 if (code_show_err){
 } else {
 code_show_err = !code_show_err
$( document ).ready(code_toggle_err);
To toggle on/off output_stderr, click <a href="javascript:code_toggle_err()">here</a>.''')

in angularjs how to access the element that triggered the event?

you can get easily like this first write event on element


and in your js file like below

$scope.myfunction= function (msg, $event) {
    var el =

I have used it as well.

Primary key or Unique index?

What is a unique index?

A unique index on a column is an index on that column that also enforces the constraint that you cannot have two equal values in that column in two different rows. Example:

CREATE TABLE table1 (foo int, bar int);
CREATE UNIQUE INDEX ux_table1_foo ON table1(foo);  -- Create unique index on foo.

INSERT INTO table1 (foo, bar) VALUES (1, 2); -- OK
INSERT INTO table1 (foo, bar) VALUES (2, 2); -- OK
INSERT INTO table1 (foo, bar) VALUES (3, 1); -- OK
INSERT INTO table1 (foo, bar) VALUES (1, 4); -- Fails!

Duplicate entry '1' for key 'ux_table1_foo'

The last insert fails because it violates the unique index on column foo when it tries to insert the value 1 into this column for a second time.

In MySQL a unique constraint allows multiple NULLs.

It is possible to make a unique index on mutiple columns.

Primary key versus unique index

Things that are the same:

  • A primary key implies a unique index.

Things that are different:

  • A primary key also implies NOT NULL, but a unique index can be nullable.
  • There can be only one primary key, but there can be multiple unique indexes.
  • If there is no clustered index defined then the primary key will be the clustered index.

How do you compare structs for equality in C?

Note you can use memcmp() on non static stuctures without worrying about padding, as long as you don't initialise all members (at once). This is defined by C90:

Using Python's ftplib to get a directory listing, portably

The reliable/standardized way to parse FTP directory listing is by using MLSD command, which by now should be supported by all recent/decent FTP servers.

import ftplib
f = ftplib.FTP()
ls = []
f.retrlines('MLSD', ls.append)
for entry in ls:
    print entry

The code above will print:

modify=20110723201710;perm=el;size=4096;type=dir;unique=807g4e5a5; tests
modify=20111206092323;perm=el;size=4096;type=dir;unique=807g1008e0; .xchat2
modify=20111022125631;perm=el;size=4096;type=dir;unique=807g10001a; .gconfd
modify=20110808185618;perm=el;size=4096;type=dir;unique=807g160f9a; .skychart

Starting from python 3.3, ftplib will provide a specific method to do this:

Invalidating JSON Web Tokens

Why not just use the jti claim (nonce) and store that in a list as a user record field (db dependant, but at very least a comma-separated list is fine)? No need for separate lookup, as others have pointed out presumably you want to get the user record anyway, and this way you can have multiple valid tokens for different client instances ("logout everywhere" can reset the list to empty)

Replacement for deprecated sizeWithFont: in iOS 7?

I created a category to handle this problem, here it is :

#import "NSString+StringSizeWithFont.h"

@implementation NSString (StringSizeWithFont)

- (CGSize) sizeWithMyFont:(UIFont *)fontToUse
    if ([self respondsToSelector:@selector(sizeWithAttributes:)])
        NSDictionary* attribs = @{NSFontAttributeName:fontToUse};
        return ([self sizeWithAttributes:attribs]);
    return ([self sizeWithFont:fontToUse]);

This way you only have to find/replace sizeWithFont: with sizeWithMyFont: and you're good to go.

MySQL - Select the last inserted row easiest way

In concurrency, the latest record may not be the record you just entered. It may better to get the latest record using the primary key.

If it is a auto increment field, use SELECT LAST_INSERT_ID(); to get the id you just created.

How to sort a list of lists by a specific index of the inner list?

array.sort(key = lambda x:x[1])

You can easily sort using this snippet, where 1 is the index of the element.

What does [object Object] mean?

[object Object] is the default string representation of a JavaScript Object. It is what you'll get if you run this code:

alert({}); // [object Object]

You can change the default representation by overriding the toString method like so:

var o = {toString: function(){ return "foo" }};
alert(o); // foo

How to get the process ID to kill a nohup process?

This works in Ubuntu

Type this to find out the PID

ps aux | grep java

All the running process regarding to java will be shown

In my case is

johnjoe      3315  9.1  4.0 1465240 335728 ?      Sl   09:42   3:19 java -jar batch.jar

Now kill it kill -9 3315

The zombie process finally stopped.

What is the difference between sscanf or atoi to convert a string to an integer?

If user enters 34abc and you pass them to atoi it will return 34. If you want to validate the value entered then you have to use isdigit on the entered string iteratively

How to allow access outside localhost

For the problem was Firewall. If you are on Windows, make sure node is allowed through enter image description here

Determine the type of an object?

type() is a better solution than isinstance(), particularly for booleans:

True and False are just keywords that mean 1 and 0 in python. Thus,

isinstance(True, int)


isinstance(False, int)

both return True. Both booleans are an instance of an integer. type(), however, is more clever:

type(True) == int

returns False.

Get current NSDate in timestamp format


I have a UILabel which shows TimeStamp over a Camera Preview.

    var timeStampTimer : NSTimer?
    var dateEnabled:  Bool?
    var timeEnabled: Bool?
   @IBOutlet weak var timeStampLabel: UILabel!

override func viewDidLoad() {
//Setting Initial Values to be false.
        dateEnabled =  false
        timeEnabled =  false

override func viewWillAppear(animated: Bool) {

        //Current Date and Time on Preview View
        timeStampLabel.text = timeStamp
        self.timeStampTimer = NSTimer.scheduledTimerWithTimeInterval(1.0,target: self, selector: Selector("updateCurrentDateAndTimeOnTimeStamperLabel"),userInfo: nil,repeats: true)

func updateCurrentDateAndTimeOnTimeStamperLabel()
//Every Second, it updates time.

        switch (dateEnabled, timeEnabled) {
        case (true?, true?):
            timeStampLabel.text =  NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .LongStyle, timeStyle: .MediumStyle)
        case (true?, false?):
            timeStampLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .LongStyle, timeStyle: .NoStyle)

        case (false?, true?):
            timeStampLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .MediumStyle)
        case (false?, false?):
            timeStampLabel.text =  NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .NoStyle)


I am setting up a setting Button to trigger a alertView.

@IBAction func settingsButton(sender : AnyObject) {

let cameraSettingsAlert = UIAlertController(title: NSLocalizedString("Please choose a course", comment: ""), message: NSLocalizedString("", comment: ""), preferredStyle: .ActionSheet)

let timeStampOnAction = UIAlertAction(title: NSLocalizedString("Time Stamp on Photo", comment: ""), style: .Default) { action in

    self.dateEnabled = true
    self.timeEnabled =  true

let timeStampOffAction = UIAlertAction(title: NSLocalizedString("TimeStamp Off", comment: ""), style: .Default) { action in

    self.dateEnabled = false
    self.timeEnabled =  false

let dateOnlyAction = UIAlertAction(title: NSLocalizedString("Date Only", comment: ""), style: .Default) { action in

    self.dateEnabled = true
    self.timeEnabled =  false

let timeOnlyAction = UIAlertAction(title: NSLocalizedString("Time Only", comment: ""), style: .Default) { action in

    self.dateEnabled = false
    self.timeEnabled =  true

let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel) { action in


self.presentViewController(cameraSettingsAlert, animated: true, completion: nil)


c# replace \" characters

Were you trying it like this:

string text = GetTextFromSomewhere();
text.Replace("\\", "");
text.Replace("\"", "");

? If so, that's the problem - Replace doesn't change the original string, it returns a new string with the replacement performed... so you'd want:

string text = GetTextFromSomewhere();
text = text.Replace("\\", "").Replace("\"", "");

Note that this will replace each backslash and each double-quote character; if you only wanted to replace the pair "backslash followed by double-quote" you'd just use:

string text = GetTextFromSomewhere();
text = text.Replace("\\\"", "");

(As mentioned in the comments, this is because strings are immutable in .NET - once you've got a string object somehow, that string will always have the same contents. You can assign a reference to a different string to a variable of course, but that's not actually changing the contents of the existing string.)

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

Laravel - Pass more than one variable to view

Passing multiple variables to a Laravel view

//Passing variable to view using compact method    
return view('viewName', compact('var1','var2','var3'));

//Passing variable to view using with Method
return view('viewName')->with(['var1'=>value1,'var2'=>value2,'var3'=>'value3']);

//Passing variable to view using Associative Array
return view('viewName', ['var1'=>value1,'var2'=>value2,'var3'=>value3]);

Read here about Passing Data to Views in Laravel

Java Best Practices to Prevent Cross Site Scripting

Use both. In fact refer a guide like the OWASP XSS Prevention cheat sheet, on the possible cases for usage of output encoding and input validation.

Input validation helps when you cannot rely on output encoding in certain cases. For instance, you're better off validating inputs appearing in URLs rather than encoding the URLs themselves (Apache will not serve a URL that is url-encoded). Or for that matter, validate inputs that appear in JavaScript expressions.

Ultimately, a simple thumb rule will help - if you do not trust user input enough or if you suspect that certain sources can result in XSS attacks despite output encoding, validate it against a whitelist.

Do take a look at the OWASP ESAPI source code on how the output encoders and input validators are written in a security library.

Compare every item to every other item in ArrayList

This code helped me get this behaviour: With a list a,b,c, I should get compared ab, ac and bc, but any other pair would be excess / not needed.

import java.util.*;
import static java.lang.System.out;

// rl = rawList; lr = listReversed
ArrayList<String> rl = new ArrayList<String>();
ArrayList<String> lr = new ArrayList<String>();


for (String itemA : rl) {
        for (String itemZ : lr) {
        System.out.println(itemA + itemZ);

The loop goes as like in this picture: Triangular comparison visual example

or as this:

   |   f    e    d    c    b   a
a  |  af   ae   ad   ac   ab   ·
b  |  bf   be   bd   bc   ·   
c  |  cf   ce   cd   ·      
d  |  df   de   ·         
e  |  ef   ·            
f  |  ·               

total comparisons is a triangular number (n * n-1)/2

Environ Function code samples for VBA

Environ() gets you the value of any environment variable. These can be found by doing the following command in the Command Prompt:


If you wanted to get the username, you would do:


If you wanted to get the fully qualified name, you would do:

Environ("userdomain") & "\" & Environ("username")


Find html label associated with a given input

document.querySelector("label[for=" + + "]");

This answers the question in the simplest and leanest manner. This uses vanilla javascript and works on all main-stream proper browsers.

Remove a fixed prefix/suffix from a string in Bash

$ foo=${string#"$prefix"}
$ foo=${foo%"$suffix"}
$ echo "${foo}"

This is documented in the Shell Parameter Expansion section of the manual:


The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the # case) or the longest matching pattern (the ## case) deleted. […]


The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the % case) or the longest matching pattern (the %% case) deleted. […]

How to position a div in bottom right corner of a browser?

This snippet works in IE7 at least

<!DOCTYPE html>
<meta charset=utf-8 />
  #foo {
    position: fixed;
    bottom: 0;
    right: 0;
  <div id="foo">Hello World</div>

java, get set methods

To understand get and set, it's all related to how variables are passed between different classes.

The get method is used to obtain or retrieve a particular variable value from a class.

A set value is used to store the variables.

The whole point of the get and set is to retrieve and store the data values accordingly.

What I did in this old project was I had a User class with my get and set methods that I used in my Server class.

The User class's get set methods:

public int getuserID()
        //getting the userID variable instance
        return userID;
    public String getfirstName()
        //getting the firstName variable instance
        return firstName;
    public String getlastName()
        //getting the lastName variable instance
        return lastName;
    public int getage()
        //getting the age variable instance
        return age;

    public void setuserID(int userID)
        //setting the userID variable value
        this.userID = userID;
    public void setfirstName(String firstName)
        //setting the firstName variable text
        this.firstName = firstName;
    public void setlastName(String lastName)
        //setting the lastName variable text
        this.lastName = lastName;
    public void setage(int age)
        //setting the age variable value
        this.age = age;

Then this was implemented in the run() method in my Server class as follows:

//creates user object
                User use = new User(userID, firstName, lastName, age);
                //Mutator methods to set user objects

How to convert a Title to a URL slug in jQuery?

Yet another one. Short and keeps special characters:

imaginação é mato => imaginacao-e-mato

function slugify (text) {
  const a = 'àáäâãèéëêìíïîòóöôùúüûñçßÿœærsn?????u?z?·/_,:;'
  const b = 'aaaaaeeeeiiiioooouuuuncsyoarsnpwgnmuxzh------'
  const p = new RegExp(a.split('').join('|'), 'g')

  return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(p, c =>
        b.charAt(a.indexOf(c)))     // Replace special chars
    .replace(/&/g, '-and-')         // Replace & with 'and'
    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '')             // Trim - from end of text

Error related to only_full_group_by when executing a query in MySql

For localhost / wampserver 3 we can set sql-mode = user_mode to remove this error:

click on wamp icon -> MySql -> MySql Setting -> sql-mode -> user_mode

then restart wamp or apache

ORDER BY the IN value list

SELECT * FROM "comments" JOIN (
  SELECT 1 as "id",1 as "order" UNION ALL 
) j ON "comments"."id" = j."id" ORDER BY j.ORDER

or if you prefer evil over good:

SELECT * FROM "comments" WHERE ("comments"."id" IN (1,3,2,4))
ORDER BY POSITION(','+"comments"."id"+',' IN ',1,3,2,4,')

How to install OpenJDK 11 on Windows?

AdoptOpenJDK is a new website hosted by the java community. You can find .msi installers for OpenJDK 8 through 14 there, which will perform all the things listed in the question (Unpacking, registry keys, PATH variable updating (and JAVA_HOME), uninstaller...).

how to make a html iframe 100% width and height?

Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%.

I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone.

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

For your example, you'd add this:

interface JQuery{

Edit: oops, basarat is correct below. I'm not sure why I thought it was compiling but I've updated this answer.

Can not connect to local PostgreSQL

I had this problem plaguing me, and upon further investigation (running rake db:setup), I saw that rails was trying to connect to a previously used postgres instance - one which was stored in env variables as DATABASE_URL.

The fix: unset DATABASE_URL


iOS Launching Settings -> Restrictions URL Scheme


prefs: will NOT work since iOS 10.

How to initialize an array's length in JavaScript?

[...Array(6)].map(x => 0);
// [0, 0, 0, 0, 0, 0]


// [0, 0, 0, 0, 0, 0]

Note: you can't loop empty slots i.e. Array(4).forEach(() => …)


( typescript safe )

Array(6).fill(null).map((_, i) => i);
// [0, 1, 2, 3, 4, 5]


Classic method using a function ( works in any browser )

function NewArray(size) {
    var x = [];
    for (var i = 0; i < size; ++i) {
        x[i] = i;
    return x;

var a = NewArray(10);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Creating nested arrays

When creating a 2D array with the fill intuitively should create new instances. But what actually going to happen is the same array will be stored as a reference.

var a = Array(3).fill([6]);
// [  [6], [6], [6]  ]

// [  [6, 9], [6, 9], [6, 9]  ]


var a = [...Array(3)].map(x => []);

a[0].push(4, 2);
// [  [4, 2], [], []  ]

So a 3x2 Array will look something like this:

[...Array(3)].map(x => Array(2).fill(0));
// [  [0, 0], [0, 0], [0, 0]  ]

N-dimensional array

function NArray(...dimensions) {
    var index = 0;
    function NArrayRec(dims) {
        var first = dims[0], next = dims.slice().splice(1); 
        if(dims.length > 1) 
            return Array(dims[0]).fill(null).map((x, i) => NArrayRec(next ));
        return Array(dims[0]).fill(null).map((x, i) => (index++));
    return NArrayRec(dimensions);

var arr = NArray(3, 2, 4);
// [   [  [ 0,  1,  2,  3 ] , [  4,  5,  6,  7]  ],
//     [  [ 8,  9,  10, 11] , [ 12, 13, 14, 15]  ],
//     [  [ 16, 17, 18, 19] , [ 20, 21, 22, 23]  ]   ]

Initialize a chessboard

var Chessboard = [...Array(8)].map((x, j) => {
    return Array(8).fill(null).map((y, i) => {
        return `${String.fromCharCode(65 + i)}${8 - j}`;

// [ [A8, B8, C8, D8, E8, F8, G8, H8],
//   [A7, B7, C7, D7, E7, F7, G7, H7],
//   [A6, B6, C6, D6, E6, F6, G6, H6],
//   [A5, B5, C5, D5, E5, F5, G5, H5],
//   [A4, B4, C4, D4, E4, F4, G4, H4],
//   [A3, B3, C3, D3, E3, F3, G3, H3],
//   [A2, B2, C2, D2, E2, F2, G2, H2],
//   [A1, B1, C1, D1, E1, F1, G1, H1] ]

Math filled values

handy little method overload when working with math

function NewArray( size , method, linear )
    method = method || ( i => i ); 
    linear = linear || false;
    var x = [];
    for( var i = 0; i < size; ++i )
        x[ i ] = method( linear ? i / (size-1) : i );
    return x;

NewArray( 4 ); 
// [ 0, 1, 2, 3 ]

NewArray( 4, Math.sin ); 
// [ 0, 0.841, 0.909, 0.141 ]

NewArray( 4, Math.sin, true );
// [ 0, 0.327, 0.618, 0.841 ]

var pow2 = ( x ) => x * x;

NewArray( 4, pow2 ); 
// [ 0, 1, 4, 9 ]

NewArray( 4, pow2, true ); 
// [ 0, 0.111, 0.444, 1 ]

Entity Framework Query for inner join

from s in db.Services
join sa in db.ServiceAssignments on s.Id equals sa.ServiceId
where sa.LocationId == 1
select s

Where db is your DbContext. Generated query will look like (sample for EF6):

SELECT [Extent1].[Id] AS [Id]
       -- other fields from Services table
FROM [dbo].[Services] AS [Extent1]
INNER JOIN [dbo].[ServiceAssignments] AS [Extent2]
    ON [Extent1].[Id] = [Extent2].[ServiceId]
WHERE [Extent2].[LocationId] = 1

What is the purpose of "&&" in a shell command?

####################### && or (Logical AND) ######################

if [[ ($first_command == 1) && ($two_command == 2)]];then
 echo "Equal"

When program checks if command, then the program creates a number called exit code, if both conditions are true, exit code is zero (0), otherwise, exit code is positive number. only when displaying Equal if exit code is produced zero (0) that means both conditions are true.

How do I automatically resize an image for a mobile site?

img {
  max-width: 100%;

Should set the image to take up 100% of its containing element.

Could not load file or assembly 'System.Web.WebPages.Razor, Version=

You have upgraded to Razor 3. Remember that VS 12 (until update 4) doesn't support it. Install The Razor 3 from nuget or downgrade it through these step

Angular 2: 404 error occur when I refresh through the browser

Update for Angular 2 final version

In app.module.ts:

  • Add imports:

      import { HashLocationStrategy, LocationStrategy } from '@angular/common';
  • And in NgModule provider, add:

      {provide: LocationStrategy, useClass: HashLocationStrategy}

Example (app.module.ts):

import { NgModule }       from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { HashLocationStrategy, LocationStrategy } from '@angular/common';

    declarations: [AppComponent],
    imports: [BrowserModule],
    providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
    bootstrap: [AppComponent],
export class AppModule {}


Use RouterModule.forRoot with the {useHash: true} argument.

Example:(from angular docs)

import { NgModule } from '@angular/core';

const routes: Routes = [//routes in here];

  imports: [
    RouterModule.forRoot(routes, { useHash: true })
  bootstrap: [AppComponent]
export class AppModule { }

Get path from open file in Python

You can get it like this also.

filepath = os.path.abspath(

How to time Java program execution speed

use long startTime=System.currentTimeMillis() for start time, at the top of the loop

put long endTime= System.currentTimeMillis(); outside the end of the loop. You'll have to subtract the values to get the runtime in milliseconds.

If you want time in nanoseconds, check out System.nanoTime()

Using JSON POST Request

An example using jQuery is below. Hope this helps

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<title>My jQuery JSON Web Page</title>
<script type="text/javascript" src=""></script>
<script type="text/javascript">

JSONTest = function() {

    var resultDiv = $("#resultDivContainer");

        url: "",
        type: "POST",
        data: { apiKey: "23462", method: "example", ip: "" },
        dataType: "json",
        success: function (result) {
            switch (result) {
                case true:
        error: function (xhr, ajaxOptions, thrownError) {


<h1>My jQuery JSON Web Page</h1>

<div id="resultDivContainer"></div>

<button type="button" onclick="JSONTest()">JSON</button>


Firebug debug process

Firebug XHR debug process

How to use Bootstrap 4 in ASP.NET Core

Try Libman, it's as simple as Bower and you can specify wwwroot/lib/ as the download folder.

Getting current directory in .NET web application

The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.

You want HttpRuntime.AppDomainAppPath.

If you're in an HTTP request, you can also call Server.MapPath("~/Whatever").

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

Below method solved my problem:

In ubuntu

Type: sudo vi /etc/mysql/my.cnf

type A to enter insert mode

In the last line paste below two line code:


Type esc to exit input mode

Type :wq to save and close vim.

Type sudo service mysql restart to restart MySQL.

Simple Deadlock Examples

Simple example from

public class Deadlock {

public static void printMessage(String message) {

    System.out.println(String.format("%s %s ", Thread.currentThread().getName(), message));


private static class Friend {

    private String name;

    public Friend(String name) { = name;

    public void bow(Friend friend) {

        printMessage("Acquiring lock on " +;

        synchronized(this) {
            printMessage("Acquired lock on " +;
            printMessage(name + " bows " +;


    public void bowBack(Friend friend) {

        printMessage("Acquiring lock on " +;

        synchronized (this) {
            printMessage("Acquired lock on " +;
            printMessage( + " bows back");



public static void main(String[] args) throws InterruptedException {

    Friend one = new Friend("one");
    Friend two = new Friend("two");

    new Thread(new Runnable() {
        public void run() {

    new Thread(new Runnable() {
        public void run() {



Thread-0 Acquiring lock on one 
Thread-1 Acquiring lock on two 
Thread-0 Acquired lock on one 
Thread-1 Acquired lock on two 
Thread-1 two bows one 
Thread-0 one bows two 
Thread-1 Acquiring lock on one 
Thread-0 Acquiring lock on two 

Thread Dump:

2016-03-14 12:20:09
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.74-b02 mixed mode):

"DestroyJavaVM" #13 prio=5 os_prio=0 tid=0x00007f472400a000 nid=0x3783 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Thread-1" #12 prio=5 os_prio=0 tid=0x00007f472420d800 nid=0x37a3 waiting for monitor entry [0x00007f46e89a5000]
   java.lang.Thread.State: BLOCKED (on object monitor)
    at com.anantha.algorithms.ThreadJoin$Friend.bowBack(
    - waiting to lock <0x000000076d0583a0> (a com.anantha.algorithms.ThreadJoin$Friend)
    at com.anantha.algorithms.ThreadJoin$Friend.bow(
    - locked <0x000000076d0583e0> (a com.anantha.algorithms.ThreadJoin$Friend)
    at com.anantha.algorithms.ThreadJoin$

"Thread-0" #11 prio=5 os_prio=0 tid=0x00007f472420b800 nid=0x37a2 waiting for monitor entry [0x00007f46e8aa6000]
   java.lang.Thread.State: BLOCKED (on object monitor)
    at com.anantha.algorithms.ThreadJoin$Friend.bowBack(
    - waiting to lock <0x000000076d0583e0> (a com.anantha.algorithms.ThreadJoin$Friend)
    at com.anantha.algorithms.ThreadJoin$Friend.bow(
    - locked <0x000000076d0583a0> (a com.anantha.algorithms.ThreadJoin$Friend)
    at com.anantha.algorithms.ThreadJoin$

"Monitor Ctrl-Break" #10 daemon prio=5 os_prio=0 tid=0x00007f4724211000 nid=0x37a1 runnable [0x00007f46e8def000]
   java.lang.Thread.State: RUNNABLE
    at Method)
    at sun.nio.cs.StreamDecoder.readBytes(
    at sun.nio.cs.StreamDecoder.implRead(
    - locked <0x000000076d20afb8> (a
    - locked <0x000000076d20afb8> (a
    at com.intellij.rt.execution.application.AppMain$

"Service Thread" #9 daemon prio=9 os_prio=0 tid=0x00007f47240c9800 nid=0x3794 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C1 CompilerThread3" #8 daemon prio=9 os_prio=0 tid=0x00007f47240c6800 nid=0x3793 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread2" #7 daemon prio=9 os_prio=0 tid=0x00007f47240c4000 nid=0x3792 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread1" #6 daemon prio=9 os_prio=0 tid=0x00007f47240c2800 nid=0x3791 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread0" #5 daemon prio=9 os_prio=0 tid=0x00007f47240bf800 nid=0x3790 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Signal Dispatcher" #4 daemon prio=9 os_prio=0 tid=0x00007f47240be000 nid=0x378f waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Finalizer" #3 daemon prio=8 os_prio=0 tid=0x00007f472408c000 nid=0x378e in Object.wait() [0x00007f46e98c5000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x000000076cf88ee0> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(
    - locked <0x000000076cf88ee0> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(
    at java.lang.ref.Finalizer$

"Reference Handler" #2 daemon prio=10 os_prio=0 tid=0x00007f4724087800 nid=0x378d in Object.wait() [0x00007f46e99c6000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x000000076cf86b50> (a java.lang.ref.Reference$Lock)
    at java.lang.Object.wait(
    at java.lang.ref.Reference.tryHandlePending(
    - locked <0x000000076cf86b50> (a java.lang.ref.Reference$Lock)
    at java.lang.ref.Reference$

"VM Thread" os_prio=0 tid=0x00007f4724080000 nid=0x378c runnable 

"GC task thread#0 (ParallelGC)" os_prio=0 tid=0x00007f472401f000 nid=0x3784 runnable 

"GC task thread#1 (ParallelGC)" os_prio=0 tid=0x00007f4724021000 nid=0x3785 runnable 

"GC task thread#2 (ParallelGC)" os_prio=0 tid=0x00007f4724022800 nid=0x3786 runnable 

"GC task thread#3 (ParallelGC)" os_prio=0 tid=0x00007f4724024800 nid=0x3787 runnable 

"GC task thread#4 (ParallelGC)" os_prio=0 tid=0x00007f4724026000 nid=0x3788 runnable 

"GC task thread#5 (ParallelGC)" os_prio=0 tid=0x00007f4724028000 nid=0x3789 runnable 

"GC task thread#6 (ParallelGC)" os_prio=0 tid=0x00007f4724029800 nid=0x378a runnable 

"GC task thread#7 (ParallelGC)" os_prio=0 tid=0x00007f472402b800 nid=0x378b runnable 

"VM Periodic Task Thread" os_prio=0 tid=0x00007f47240cc800 nid=0x3795 waiting on condition 

JNI global references: 16

Found one Java-level deadlock:
  waiting to lock monitor 0x00007f46dc003f08 (object 0x000000076d0583a0, a com.anantha.algorithms.ThreadJoin$Friend),
  which is held by "Thread-0"
  waiting to lock monitor 0x00007f46dc006008 (object 0x000000076d0583e0, a com.anantha.algorithms.ThreadJoin$Friend),
  which is held by "Thread-1"

Java stack information for the threads listed above:
    at com.anantha.algorithms.ThreadJoin$Friend.bowBack(
    - waiting to lock <0x000000076d0583a0> (a com.anantha.algorithms.ThreadJoin$Friend)
    at com.anantha.algorithms.ThreadJoin$Friend.bow(
    - locked <0x000000076d0583e0> (a com.anantha.algorithms.ThreadJoin$Friend)
    at com.anantha.algorithms.ThreadJoin$
    at com.anantha.algorithms.ThreadJoin$Friend.bowBack(
    - waiting to lock <0x000000076d0583e0> (a com.anantha.algorithms.ThreadJoin$Friend)
    at com.anantha.algorithms.ThreadJoin$Friend.bow(
    - locked <0x000000076d0583a0> (a com.anantha.algorithms.ThreadJoin$Friend)
    at com.anantha.algorithms.ThreadJoin$

Found 1 deadlock.

 PSYoungGen      total 74752K, used 9032K [0x000000076cf80000, 0x0000000772280000, 0x00000007c0000000)
  eden space 64512K, 14% used [0x000000076cf80000,0x000000076d8520e8,0x0000000770e80000)
  from space 10240K, 0% used [0x0000000771880000,0x0000000771880000,0x0000000772280000)
  to   space 10240K, 0% used [0x0000000770e80000,0x0000000770e80000,0x0000000771880000)
 ParOldGen       total 171008K, used 0K [0x00000006c6e00000, 0x00000006d1500000, 0x000000076cf80000)
  object space 171008K, 0% used [0x00000006c6e00000,0x00000006c6e00000,0x00000006d1500000)
 Metaspace       used 3183K, capacity 4500K, committed 4864K, reserved 1056768K
  class space    used 352K, capacity 388K, committed 512K, reserved 1048576K

IntelliJ: Never use wildcard imports

If non of above works for you, then it is worth to check if you have any packages under Preference > Editor > Code Style > Java > Imports > Packages to Use Import with "*"

How to install bcmath module?

If still anyone is not getting how to install bcmath as it has lots of other dependant modules to install like php7.2-common, etc.

Try using synaptic application, to install the same. fire command.\

sudo apt-get install synaptic

Open the synaptic application and then click on search tab.

search for bcmath

search results will show all the packages depends on php.

Install as per your convenience.

and install with all auto populated dependancies it required to install.

That's it.

Manifest Merger failed with multiple errors in Android Studio

this is very simple error only occur when you define any activity call two time in mainifest.xml file Example like

<activity android:name="com.futuretech.mpboardexam.Game" ></activity>

//and launcher also------like that

//solution:use only one 

How can getContentResolver() be called in Android?

This one worked for me getBaseContext();

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

By overriding valueOf in a class declaration, it can be done:

class Thing {
    constructor() {
        this.value = 1;

    valueOf() {
        return this.value++;

const a = new Thing();

if(a == 1 && a == 2 && a == 3) {

What happens is that valueOf is called in each comparison operator. On the first one, a will equal 1, on the second, a will equal 2, and so on and so forth, because each time valueOf is called, the value of a is incremented.

Therefore the console.log will fire and output (in my terminal anyways) Thing: { value: 4}, indicating the conditional was true.

Is there a way of setting culture for a whole application? All current threads and new threads?

Actually you can set the default thread culture and UI culture, but only with Framework 4.5+

I put in this static constructor

static MainWindow()
  CultureInfo culture = CultureInfo
  var dtf = culture.DateTimeFormat;
  dtf.ShortTimePattern = (string)Microsoft.Win32.Registry.GetValue(
    "HKEY_CURRENT_USER\\Control Panel\\International", "sShortTime", "hh:mm tt");
  CultureInfo.DefaultThreadCurrentUICulture = culture;

and put a breakpoint in the Convert method of a ValueConverter to see what arrived at the other end. CultureInfo.CurrentUICulture ceased to be en-US and became instead en-AU complete with my little hack to make it respect regional settings for ShortTimePattern.

Hurrah, all is well in the world! Or not. The culture parameter passed to the Convert method is still en-US. Erm, WTF?! But it's a start. At least this way

  • you can fix the UI culture once when your app loads
  • it's always accessible from CultureInfo.CurrentUICulture
  • string.Format("{0}", DateTime.Now) will use your customised regional settings

If you can't use version 4.5 of the framework then give up on setting CurrentUICulture as a static property of CultureInfo and set it as a static property of one of your own classes. This won't fix default behaviour of string.Format or make StringFormat work properly in bindings then walk your app's logical tree to recreate all the bindings in your app and set their converter culture.

How to pass a value to razor variable from javascript variable?

I see that this problem was discussed some time ago, but if anyone 'll meet with this again, here is my solution:

In your *.cshtml View file:

var data = JsFunction("@Html.Raw(Model.Path)");
$(function () {
    $("#btn").click(function () {
        var model = { Id: '@Html.Raw(Model.Id)', Data: data }
            type: "POST",
            url: "/Controller/Action",
            data: model,
            datatype: "html",
            success: function() {

JavaScript variable model is something that I need to pass to Razor ViewModel. It can be done with ajax request. You just need to have proper argument/s in your action, that matches Json object created in JavaScript.

Hope it'll help someone!

Functions are not valid as a React child. This may happen if you return a Component instead of from render

I was able to resolve this by using my calling my high order component before exporting the class component. My problem was specifically using react-i18next and its withTranslation method, but here was the solution:

export default withTranslation()(Header);

And then I was able to call the class Component as originally I had hoped:

<Header someProp={someValue} />

What's the difference between a method and a function?

A method is on an object.
A function is independent of an object.

For Java and C#, there are only methods.
For C, there are only functions.

For C++ and Python it would depend on whether or not you're in a class.

VBA Public Array : how to?

This worked for me, seems to work as global :

Dim savePos(2 To 8) As Integer

And can call it from every sub, for example getting first element :

MsgBox (savePos(2))

Instantiate and Present a viewController in Swift

akashivskyy's answer works just fine! But, in case you have some trouble returning from the presented view controller, this alternative can be helpful. It worked for me!


let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("someViewController") as! UIViewController
// Alternative way to present the new view controller
self.navigationController?.showViewController(vc, sender: nil)


UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MyStoryboardName" bundle:nil];
UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"someViewController"];
[self.navigationController showViewController:vc sender:nil];

Gridview with two columns and auto resized images

Here's a relatively easy method to do this. Throw a GridView into your layout, setting the stretch mode to stretch the column widths, set the spacing to 0 (or whatever you want), and set the number of columns to 2:


<?xml version="1.0" encoding="utf-8"?>



Make a custom ImageView that maintains its aspect ratio:


public class SquareImageView extends ImageView {
    public SquareImageView(Context context) {

    public SquareImageView(Context context, AttributeSet attrs) {
        super(context, attrs);

    public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width

Make a layout for a grid item using this SquareImageView and set the scaleType to centerCrop:


<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android=""




Now make some sort of adapter for your GridView:


private final class MyAdapter extends BaseAdapter {
    private final List<Item> mItems = new ArrayList<Item>();
    private final LayoutInflater mInflater;

    public MyAdapter(Context context) {
        mInflater = LayoutInflater.from(context);

        mItems.add(new Item("Red",;
        mItems.add(new Item("Magenta",   R.drawable.magenta));
        mItems.add(new Item("Dark Gray", R.drawable.dark_gray));
        mItems.add(new Item("Gray",      R.drawable.gray));
        mItems.add(new Item("Green",;
        mItems.add(new Item("Cyan",      R.drawable.cyan));

    public int getCount() {
        return mItems.size();

    public Item getItem(int i) {
        return mItems.get(i);

    public long getItemId(int i) {
        return mItems.get(i).drawableId;

    public View getView(int i, View view, ViewGroup viewGroup) {
        View v = view;
        ImageView picture;
        TextView name;

        if (v == null) {
            v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
            v.setTag(, v.findViewById(;
            v.setTag(, v.findViewById(;

        picture = (ImageView) v.getTag(;
        name = (TextView) v.getTag(;

        Item item = getItem(i);


        return v;

    private static class Item {
        public final String name;
        public final int drawableId;

        Item(String name, int drawableId) {
   = name;
            this.drawableId = drawableId;

Set that adapter to your GridView:

public void onCreate(Bundle savedInstanceState) {
    GridView gridView = (GridView)findViewById(;
    gridView.setAdapter(new MyAdapter(this));

And enjoy the results:

Example GridView

What are the differences between the BLOB and TEXT datatypes in MySQL?

BLOB stores binary data which are more than 2 GB. Max size for BLOB is 4 GB. Binary data means unstructured data i.e images audio files vedio files digital signature

Text is used to store large string.

Incrementing a date in JavaScript

Tomorrow in one line in pure JS but it's ugly !

new Date(new Date().setDate(new Date().getDate() + 1))

Here is the result :

Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)

Variable declaration in a header file

You can (should) declare it as extern in a header file, and define it in exactly 1 .c file.

Note that that .c file should also use the header and that the standard pattern looks like:

// file.h
extern int x;  // declaration

// file.c
#include "file.h"
int x = 1;    // definition and re-declaration

Finding median of list in Python

(Works with ):

def median(lst):
    n = len(lst)
    s = sorted(lst)
    return (sum(s[n//2-1:n//2+1])/2.0, s[n//2])[n % 2] if n else None

>>> median([-5, -5, -3, -4, 0, -1])


>>> from numpy import median
>>> median([1, -4, -1, -1, 1, -3])

For , use statistics.median:

>>> from statistics import median
>>> median([5, 2, 3, 8, 9, -2])

Running SSH Agent when starting Git Bash on Windows

Create a new .bashrc file in your ~ directory.

There you can put your commands that you want executed everytime you start the bash

iterating quickly through list of tuples

Assuming a bit more memory usage is not a problem and if the first item of your tuple is hashable, you can create a dict out of your list of tuples and then looking up the value is as simple as looking up a key from the dict. Something like:

dct = dict(tuples)
val = dct.get(key) # None if item not found else the corresponding value

EDIT: To create a reverse mapping, use something like:

revDct = dict((val, key) for (key, val) in tuples)

how to change the default positioning of modal in bootstrap?

I get a better result setting this class:

.modal-dialog {
  position: absolute;
  top: 50px;
  right: 100px;
  bottom: 0;
  left: 0;
  z-index: 10040;
  overflow: auto;
  overflow-y: auto;

With bootstrap 3.3.7.

(all credits to msnfreaky for the idea...)

'const int' vs. 'int const' as function parameters in C++ and C

Prakash is correct that the declarations are the same, although a little more explanation of the pointer case might be in order.

"const int* p" is a pointer to an int that does not allow the int to be changed through that pointer. "int* const p" is a pointer to an int that cannot be changed to point to another int.


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

Andrey Tarasevich provides the following explanation:

  1. On Google Groups
  2. On

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

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

Consider the following code sketch:

if (<condition>)

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

if (<condition>)

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

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

if (<condition>)

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

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

Now this code:

if (<condition>)

will compile without any problems.

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

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

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

In this case add id to the button in RowDataBound of the grid. It will solve your problem.

The value violated the integrity constraints for the column

As a slight alternative to @FazianMubasher's answer, instead of allowing NULL for the specified column (which may for many reasons not be possible), you could also add a Conditional Split Task to branch NULL values to an error file, or just to ignore them:

enter image description here

enter image description here

How to use Scanner to accept only valid int as input

  1. the condition num2 < num1 should be num2 <= num1 if num2 has to be greater than num1
  2. not knowing what the kb object is, I'd read a String and then trying Integer.parseInt() and if you don't catch an exception then it's a number, if you do, read a new one, maybe by setting num2 to Integer.MIN_VALUE and using the same type of logic in your example.

How do you clear a stringstream variable?

You can clear the error state and empty the stringstream all in one line

std::stringstream().swap(m); // swap m with a default constructed stringstream

This effectively resets m to a default constructed state

Reading data from a website using C#

 WebClient client = new WebClient();
            using (Stream data = client.OpenRead(Text))
                using (StreamReader reader = new StreamReader(data))
                    string content = reader.ReadToEnd();
                    string pattern = @"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)";
                    MatchCollection matches = Regex.Matches(content,pattern);
                    List<string> urls = new List<string>();
                    foreach (Match match in matches)


How do I run all Python unit tests in a directory?

Well by studying the code above a bit (specifically using TextTestRunner and defaultTestLoader), I was able to get pretty close. Eventually I fixed my code by also just passing all test suites to a single suites constructor, rather than adding them "manually", which fixed my other problems. So here is my solution.

import glob
import unittest

test_files = glob.glob('test_*.py')
module_strings = [test_file[0:len(test_file)-3] for test_file in test_files]
suites = [unittest.defaultTestLoader.loadTestsFromName(test_file) for test_file in module_strings]
test_suite = unittest.TestSuite(suites)
test_runner = unittest.TextTestRunner().run(test_suite)

Yeah, it is probably easier to just use nose than to do this, but that is besides the point.

What does 'const static' mean in C and C++?

It's a small space optimization.

When you say

const int foo = 42;

You're not defining a constant, but creating a read-only variable. The compiler is smart enough to use 42 whenever it sees foo, but it will also allocate space in the initialized data area for it. This is done because, as defined, foo has external linkage. Another compilation unit can say:

extern const int foo;

To get access to its value. That's not a good practice since that compilation unit has no idea what the value of foo is. It just knows it's a const int and has to reload the value from memory whenever it is used.

Now, by declaring that it is static:

static const int foo = 42;

The compiler can do its usual optimization, but it can also say "hey, nobody outside this compilation unit can see foo and I know it's always 42 so there is no need to allocate any space for it."

I should also note that in C++, the preferred way to prevent names from escaping the current compilation unit is to use an anonymous namespace:

namespace {
    const int foo = 42; // same as static definition above

How to deny access to a file in .htaccess

Within an htaccess file, the scope of the <Files> directive only applies to that directory (I guess to avoid confusion when rules/directives in the htaccess of subdirectories get applied superceding ones from the parent).

So you can have:

<Files "log.txt">  
  Order Allow,Deny
  Deny from all

For Apache 2.4+, you'd use:

<Files "log.txt">  
  Require all denied

In an htaccess file in your inscription directory. Or you can use mod_rewrite to sort of handle both cases deny access to htaccess file as well as log.txt:

RewriteRule /?\.htaccess$ - [F,L]

RewriteRule ^/?inscription/log\.txt$ - [F,L]

Handle Button click inside a row in RecyclerView

this is how I handle multiple onClick events inside a recyclerView:

Edit : Updated to include callbacks (as mentioned in other comments). I have used a WeakReference in the ViewHolder to eliminate a potential memory leak.

Define interface :

public interface ClickListener {

    void onPositionClicked(int position);
    void onLongClicked(int position);

Then the Adapter :

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    private final ClickListener listener;
    private final List<MyItems> itemsList;

    public MyAdapter(List<MyItems> itemsList, ClickListener listener) {
        this.listener = listener;
        this.itemsList = itemsList;

    @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_row_layout), parent, false), listener);

    @Override public void onBindViewHolder(MyViewHolder holder, int position) {
        // bind layout and data etc..

    @Override public int getItemCount() {
        return itemsList.size();

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {

        private ImageView iconImageView;
        private TextView iconTextView;
        private WeakReference<ClickListener> listenerRef;

        public MyViewHolder(final View itemView, ClickListener listener) {

            listenerRef = new WeakReference<>(listener);
            iconImageView = (ImageView) itemView.findViewById(;
            iconTextView = (TextView) itemView.findViewById(;


        // onClick Listener for view
        public void onClick(View v) {

            if (v.getId() == iconTextView.getId()) {
                Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(v.getContext(), "ROW PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();

        //onLongClickListener for view
        public boolean onLongClick(View v) {

            final AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
            builder.setTitle("Hello Dialog")
                    .setMessage("LONG CLICK DIALOG WINDOW FOR ICON " + String.valueOf(getAdapterPosition()))
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {


            return true;

Then in your activity/fragment - whatever you can implement : Clicklistener - or anonymous class if you wish like so :

MyAdapter adapter = new MyAdapter(myItems, new ClickListener() {
            @Override public void onPositionClicked(int position) {
                // callback performed on click

            @Override public void onLongClicked(int position) {
                // callback performed on click

To get which item was clicked you match the view id i.e. v.getId() == whateverItem.getId()

Hope this approach helps!

PHP - auto refreshing page

Try out this as well. Your page will refresh every 10sec


  <meta http-equiv="refresh" content="10; url="<?php echo $_SERVER['PHP_SELF']; ?>">


How do I make a self extract and running installer

It's simple with open source 7zip SFX-Packager - easy way to just "Drag & drop" folders onto it, and it creates a portable/self-extracting package.

How to access command line arguments of the caller inside a function?

If you want to have your arguments C style (array of arguments + number of arguments) you can use $@ and $#.

$# gives you the number of arguments.
$@ gives you all arguments. You can turn this into an array by args=("$@").

So for example:

echo $# arguments passed
echo ${args[0]} ${args[1]} ${args[2]}

Note that here ${args[0]} actually is the 1st argument and not the name of your script.

Maximum concurrent connections to MySQL

I can assure you that raw speed ultimately lies in the non-standard use of Indexes for blazing speed using large tables.

Create a mocked list by mockito

OK, this is a bad thing to be doing. Don't mock a list; instead, mock the individual objects inside the list. See Mockito: mocking an arraylist that will be looped in a for loop for how to do this.

Also, why are you using PowerMock? You don't seem to be doing anything that requires PowerMock.

But the real cause of your problem is that you are using when on two different objects, before you complete the stubbing. When you call when, and provide the method call that you are trying to stub, then the very next thing you do in either Mockito OR PowerMock is to specify what happens when that method is called - that is, to do the thenReturn part. Each call to when must be followed by one and only one call to thenReturn, before you do any more calls to when. You made two calls to when without calling thenReturn - that's your error.

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

A simpler solution on recent versions of tmux (tested on 1.9) you can now do :

tmux detach -a

-a is for all other client on this session except the current one

You can alias it in your .[bash|zsh]rc

alias takeover="tmux detach -a"

Workflow: You can connect to your session normally, and if you are bothered by another session that forced down your tmux window size you can simply call takeover.

Can we cast a generic object to a custom object type in javascript?

This is just a wrap up of Sayan Pal answer in a shorter form, ES5 style :

var Foo = function(){ = undefined; = undefined;

var foo = Object.assign(new Foo(),{
    bar: "whatever",
    buzz: "something else"

I like it because it is the closest to the very neat object initialisation in .Net:

var foo = new Foo()
    bar: "whatever",

What is the difference between class and instance methods?

An instance method applies to an instance of the class (i.e. an object) whereas a class method applies to the class itself.

In C# a class method is marked static. Methods and properties not marked static are instance methods.

class Foo {
  public static void ClassMethod() { ... }
  public void InstanceMethod() { ... }

How can I ping a server port with PHP?

socket_create needs to be run as root on a UNIX system with;

$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);

Phone: numeric keyboard for text input

You can try like this:

<input type="number" name="input">
<input type="submit" value="Next" formnovalidate="formnovalidate">

But be careful: If your input contains something other than a number, it will not be transmitted to the server.

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

You can't, as far as I know, make the entire OS understand an http:+domain URL. You can only register new schemes (I use x-darkslide: in my app). If the app is installed, Mobile Safari will launch the app correctly.

However, you would have to handle the case where the app isn't installed with a "Still here? Click this link to download the app from iTunes." in your web page.

Parsing time string in Python

datetime.datetime.strptime has problems with timezone parsing. Have a look at the dateutil package:

>>> from dateutil import parser
>>> parser.parse("Tue May 08 15:14:45 +0800 2012")
datetime.datetime(2012, 5, 8, 15, 14, 45, tzinfo=tzoffset(None, 28800))

powershell mouse move does not prevent idle mode

Try this: (source:

Add-Type -AssemblyName System.Windows.Forms 

$position = [System.Windows.Forms.Cursor]::Position  
[System.Windows.Forms.Cursor]::Position = $position 

    while(1) {  
    $position = [System.Windows.Forms.Cursor]::Position  
    [System.Windows.Forms.Cursor]::Position = $position  

    $time = Get-Date;  
    $shorterTimeString = $time.ToString("HH:mm:ss");  

    Write-Host $shorterTimeString "Mouse pointer has been moved 1 pixel to the right"  
    #Set your duration between each mouse move
    Start-Sleep -Seconds 150  

how to do file upload using jquery serialization

You can upload files via AJAX by using the FormData method. Although IE7,8 and 9 do not support FormData functionality.

    url: "ajax.php", 
    type: "POST",             
    data: new FormData('form'),
    contentType: false,       
    cache: false,             
    success: function(data) {

How to draw vectors (physical 2D/3D vectors) in MATLAB?

I found this arrow(start, end) function on MATLAB Central which is perfect for this purpose of drawing vectors with true magnitude and direction.

"UnboundLocalError: local variable referenced before assignment" after an if statement

Before I start, I'd like to note that I can't actually test this since your script reads data from a file that I don't have.

'T' is defined in a local scope for the declared function. In the first instance 'T' is assigned the value of 'data[2]' because the conditional statement above apparently evaluates to True. Since the second call to the function causes the 'UnboundLocalError' exception to occur, the local variable 'T' is getting set and the conditional assignment is never getting triggered.

Since you appear to want to return the first bit of data in the file that matches your conditonal statement, you might want to modify you function to look like this:

def temp_sky(lreq, breq):
    for line in tfile:
        data = line.split()
        if ( abs(float(data[0]) - lreq) <= 0.1 and abs(float(data[1]) - breq) <= 0.1):            
            return data[2]
    return None

That way the desired value gets returned when it is found, and 'None' is returned when no matching data is found.

Xampp localhost/dashboard

Type in your URL localhost/[name of your folder in htdocs]

How to get first N elements of a list in C#?

var firstFiveItems = myList.Take(5);

Or to slice:

var secondFiveItems = myList.Skip(5).Take(5);

And of course often it's convenient to get the first five items according to some kind of order:

var firstFiveArrivals = myList.OrderBy(i => i.ArrivalTime).Take(5);

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

I had the same problem and I resolved it like this:

  • Open MySQL my.ini file
  • In [mysqld] section, add the following line: innodb_force_recovery = 1
  • Save the file and try starting MySQL
  • Remove that line which you just added and Save

How to execute powershell commands from a batch file?


;@echo off
;Findstr -rbv ; %0 | powershell -c - 

set-location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
set-location ZoneMap\Domains
new-itemproperty . -Name http -Value 2 -Type DWORD

;echo done
;pause & goto :eof

Find in Files: Search all code in Team Foundation Server

This add-in claims to have the functionality that I believe you seek:

Team Foundation Sidekicks

Convert generator object to list for debugging

Simply call list on the generator.

lst = list(gen)

Be aware that this affects the generator which will not return any further items.

You also cannot directly call list in IPython, as it conflicts with a command for listing lines of code.

Tested on this file:

def gen():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
import ipdb

g1 = gen()

text = "aha" + "bebe"

mylst = range(10, 20)

which when run:

$ python 
> /home/javl/sandbox/so/debug/<module>()
---> 10 g1 = gen()

ipdb> n
> /home/javl/sandbox/so/debug/<module>()
---> 12 text = "aha" + "bebe"

ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.

General method for escaping function/variable/debugger name conflicts

There are debugger commands p and pp that will print and prettyprint any expression following them.

So you could use it as follows:

$ python 
> /home/javl/sandbox/so/debug/<module>()
---> 10 g1 = gen()

ipdb> n
> /home/javl/sandbox/so/debug/<module>()
---> 12 text = "aha" + "bebe"

ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c

There is also an exec command, called by prefixing your expression with !, which forces debugger to take your expression as Python one.

ipdb> !list(g1)

For more details see help p, help pp and help exec when in debugger.

ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']

Javascript parse float is ignoring the decimals after my comma

javascript's parseFloat doesn't take a locale parameter. So you will have to replace , with .

parseFloat('0,04'.replace(/,/, '.')); // 0.04

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

Here an example of how I do that, I don't know if it is the best solution, but works perfectly.

First, code in HTML. Look at ng-class, it's calling hasError function. Look also to the input's name declaration. I use the $index to create different input names.

<div data-ng-repeat="tipo in currentObject.Tipo"
    ng-class="{'has-error': hasError(planForm, 'TipoM', 'required', $index) || hasError(planForm, 'TipoM', 'maxlength', $index)}">
    <input ng-model="tipo.Nombre" maxlength="100" required
        name="{{'TipoM' + $index}}"/>

And now, here is the hasError function:

$scope.hasError = function (form, elementName, errorType, index) {
           if (form == undefined
               || elementName == undefined
               || errorType == undefined
               || index == undefined)
               return false;

           var element = form[elementName + index];
           return (element != null && element.$error[errorType] && element.$touched);

Change border color on <select> HTML form

You can set the border color in IE however there are some issues.

Argh... I could have sworn you could do this... just tested and realized I wasn't correct. The notes below still apply though.

  1. in IE8 (Beta1 -> RC1) changing the border color or the background color/image causes a de-theming of the control in WindowsXP (the drop arrow and box look like Windows 95)

  2. you still can't style the options within the select control very well because IE doesn't support it. (see bug #291)

Parse large JSON file in Nodejs

I think you need to use a database. MongoDB is a good choice in this case because it is JSON compatible.

UPDATE: You can use mongoimport tool to import JSON data into MongoDB.

mongoimport --collection collection --file collection.json

regex for zip-code

For the listed three conditions only, these expressions might work also:


Please see this demo for additional explanation.

If we would have had unexpected additional spaces in between 5 and 4 digits or a continuous 9 digits zip code, such as:

12345 1234
12345  1234

this expression for instance would be a secondary option with less constraints:


Please see this demo for additional explanation.

RegEx Circuit visualizes regular expressions:

enter image description here


const regex = /^\d{5}[-\s]?(?:\d{4})?$/gm;_x000D_
const str = `12345_x000D_
12345 1234_x000D_
12345 1234_x000D_
12345  1234_x000D_
let m;_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
    // This is necessary to avoid infinite loops with zero-width matches_x000D_
    if (m.index === regex.lastIndex) {_x000D_
    // The result can be accessed through the `m`-variable._x000D_
    m.forEach((match, groupIndex) => {_x000D_
        console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_

What is lexical scope?

I understand them through examples. :)

First, lexical scope (also called static scope), in C-like syntax:

void fun()
    int x = 5;

    void fun2()
        printf("%d", x);

Every inner level can access its outer levels.

There is another way, called dynamic scope used by the first implementation of Lisp, again in a C-like syntax:

void fun()
    printf("%d", x);

void dummy1()
    int x = 5;


void dummy2()
    int x = 10;


Here fun can either access x in dummy1 or dummy2, or any x in any function that call fun with x declared in it.


will print 5,


will print 10.

The first one is called static because it can be deduced at compile-time, and the second is called dynamic because the outer scope is dynamic and depends on the chain call of the functions.

I find static scoping easier for the eye. Most languages went this way eventually, even Lisp (can do both, right?). Dynamic scoping is like passing references of all variables to the called function.

As an example of why the compiler can not deduce the outer dynamic scope of a function, consider our last example. If we write something like this:

if(/* some condition */)

The call chain depends on a run time condition. If it is true, then the call chain looks like:

dummy1 --> fun()

If the condition is false:

dummy2 --> fun()

The outer scope of fun in both cases is the caller plus the caller of the caller and so on.

Just to mention that the C language does not allow nested functions nor dynamic scoping.

How do I login and authenticate to Postgresql after a fresh install?

The main difference between logging in with a postgres user or any other user created by us, is that when using the postgres user it is NOT necessary to specify the host with -h and instead for another user if.

Login with postgres user

$ psql -U postgres 

Creation and login with another user

# CREATE ROLE usertest LOGIN PASSWORD 'pwtest';
# CREATE DATABASE dbtest WITH OWNER = usertest;
# SHOW port;
# \q

$ psql -h localhost -d dbtest -U usertest -p 5432



How to center absolute div horizontally using CSS?

You can't use margin:auto; on position:absolute; elements, just remove it if you don't need it, however, if you do, you could use left:30%; ((100%-40%)/2) and media queries for the max and min values:

.container {
    position: absolute;
    top: 15px;
    left: 30%;
    z-index: 2;
    height: 60px;
    overflow: hidden;
    background: #fff;

@media all and (min-width:960px) {

    .container {
        left: 50%;
        width: 960px;


@media all and (max-width:600px) {

    .container {
        left: 50%;
        width: 600px;


Import Google Play Services library in Android Studio

I solved the problem by installing the google play services package in sdk manager.

After it, create a new application & in the build.gradle add this

compile ''

Like this

dependencies {
    compile ''
    compile ''

Change the row color in DataGridView based on the quantity of a cell value

This might be helpful

  1. Use the "RowPostPaint" event
  2. The name of the column is NOT the "Header" of the column. You have to go to the properties for the DataGridView => then select the column => then look for the "Name" property

I converted this from C# ('From:

    Private Sub dgv_EmployeeTraining_RowPostPaint(sender As Object, e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) 
    Handles dgv_EmployeeTraining.RowPostPaint

    If e.RowIndex < Me.dgv_EmployeeTraining.RowCount - 1 Then
        Dim dgvRow As DataGridViewRow = Me.dgv_EmployeeTraining.Rows(e.RowIndex)

    '<== This is the header Name
        'If CInt(dgvRow.Cells("EmployeeStatus_Training_e26").Value) <> 2 Then  

    '<== But this is the name assigned to it in the properties of the control
        If CInt(dgvRow.Cells("DataGridViewTextBoxColumn15").Value.ToString) <> 2 Then   

            dgvRow.DefaultCellStyle.BackColor = Color.FromArgb(236, 236, 255)

            dgvRow.DefaultCellStyle.BackColor = Color.LightPink

        End If

    End If

End Sub

How to parseInt in Angular.js

You cannot (at least at the moment) use parseInt inside angular expressions, as they're not evaluated directly. Quoting the doc:

Angular does not use JavaScript's eval() to evaluate expressions. Instead Angular's $parse service processes these expressions.

Angular expressions do not have access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs.

So you can define a total() method in your controller, then use it in the expression:

// ... somewhere in controller
$ = function() { 
  return parseInt($scope.num1) + parseInt($scope.num2) 

// ... in HTML
Total: {{ total() }}

Still, that seems to be rather bulky for a such a simple operation as adding the numbers. The alternative is converting the results with -0 op:

Total: {{num1-0 + (num2-0)|number}}

... but that'll obviously won't parseInt values, only cast them to Numbers (|number filter prevents showing null if this cast results in NaN). So choose the approach that suits your particular case.

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

Another way, is simply add the headers to your route:

router.get('/', function(req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // If needed
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // If needed
    res.setHeader('Access-Control-Allow-Credentials', true); // If needed

    res.send('cors problem fixed:)');

change pgsql port

There should be a line in your postgresql.conf file that says:

port = 1486

Change that.

The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/

On Windows it is C:\Program Files\PostgreSQL\9.3\data

Don't forget to sudo service postgresql restart for changes to take effect.

Subtract days, months, years from a date in JavaScript

This does not answer the question fully, but for anyone who is able to calculate the number of days by which they would like to offset an initial date then the following method will work:

myDate.setUTCDate(myDate.getUTCDate() + offsetDays);

offsetDays can be positive or negative and the result will be correct for any given initial date with any given offset.

Making a Bootstrap table column fit to content

Make a class that will fit table cell width to content

.table {
    white-space: nowrap;
    width: 1%;

How to extract epoch from LocalDate and LocalDateTime?

The classes LocalDate and LocalDateTime do not contain information about the timezone or time offset, and seconds since epoch would be ambigious without this information. However, the objects have several methods to convert them into date/time objects with timezones by passing a ZoneId instance.


LocalDate date = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = date.atStartOfDay(zoneId).toEpochSecond();


LocalDateTime time = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = time.atZone(zoneId).toEpochSecond();

Change table header color using bootstrap

Try This:

table.table tr th{background-color:blue !important; font-color:white !important;}

hope this helps..

How can I test a change made to Jenkinsfile locally?

Jenkins has a 'Replay' feature, which enables you to quickly replay a job without updating sources:

Replay feature

R: Break for loop

your break statement should break out of the for (in in 1:n).

Personally I am always wary with break statements and double check it by printing to the console to double check that I am in fact breaking out of the right loop. So before you test add the following statement, which will let you know if you break before it reaches the end. However, I have no idea how you are handling the variable n so I don't know if it would be helpful to you. Make a n some test value where you know before hand if it is supposed to break out or not before reaching n.

for (in in 1:n)
    if (in == n)         #add this statement
        "sorry but the loop did not break"

    id_novo <- new_table_df$ID[in]
    else if(in == n)
        sold_df <- rbind(sold_df,old_table_df[out,])

What is the native keyword in Java for?

functions that implement native code are declared native.

The Java Native Interface (JNI) is a programming framework that enables Java code running in a Java Virtual Machine (JVM) to call, and to be called by, native applications (programs specific to a hardware and operating system platform) and libraries written in other languages such as C, C++ and assembly.

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

The execution says it's putting the jacoco data in /Users/davea/Dropbox/workspace/myproject/target/jacoco.exec but your maven configuration is looking for the data in ${basedir}/target/coverage-reports/jacoco-unit.exec.

UTF-8, UTF-16, and UTF-32

In UTF-32 all of characters are coded with 32 bits. The advantage is that you can easily calculate the length of the string. The disadvantage is that for each ASCII characters you waste an extra three bytes.

In UTF-8 characters have variable length, ASCII characters are coded in one byte (eight bits), most western special characters are coded either in two bytes or three bytes (for example € is three bytes), and more exotic characters can take up to four bytes. Clear disadvantage is, that a priori you cannot calculate string's length. But it's takes lot less bytes to code Latin (English) alphabet text, compared to UTF-32.

UTF-16 is also variable length. Characters are coded either in two bytes or four bytes. I really don't see the point. It has disadvantage of being variable length, but hasn't got the advantage of saving as much space as UTF-8.

Of those three, clearly UTF-8 is the most widely spread.

"error: assignment to expression with array type error" when I assign a struct field (C)

Please check this example here: Accessing Structure Members

There is explained that the right way to do it is like this:

strcpy( , "Egzona");
printf( "Name : %s\n",;

How do I configure the proxy settings so that Eclipse can download new plugins?

Manual + disable SOCKS didn't work for me (still tried to use SOCKS and my company proxy refused it),
Native + changed eclipse.ini worked for me


These settings require IDE restart (sometimes with -clean -refresh command line options).

Java8, Eclipse Neon3, slow proxy server:


GCC: array type has incomplete element type

It's the array that's causing trouble in:

void print_graph(g_node graph_node[], double weight[][], int nodes);

The second and subsequent dimensions must be given:

void print_graph(g_node graph_node[], double weight[][32], int nodes);

Or you can just give a pointer to pointer:

void print_graph(g_node graph_node[], double **weight, int nodes);

However, although they look similar, those are very different internally.

If you're using C99, you can use variably-qualified arrays. Quoting an example from the C99 standard (section § Array Declarators):

void fvla(int m, int C[m][m]); // valid: VLA with prototype scope

void fvla(int m, int C[m][m])  // valid: adjusted to auto pointer to VLA
    typedef int VLA[m][m];     // valid: block scope typedef VLA
    struct tag {
        int (*y)[n];           // invalid: y not ordinary identifier
        int z[n];              // invalid: z not ordinary identifier
    int D[m];                  // valid: auto VLA
    static int E[m];           // invalid: static block scope VLA
    extern int F[m];           // invalid: F has linkage and is VLA
    int (*s)[m];               // valid: auto pointer to VLA
    extern int (*r)[m];        // invalid: r has linkage and points to VLA
    static int (*q)[m] = &B;   // valid: q is a static block pointer to VLA

Question in comments

[...] In my main(), the variable I am trying to pass into the function is a double array[][], so how would I pass that into the function? Passing array[0][0] into it gives me incompatible argument type, as does &array and &array[0][0].

In your main(), the variable should be:

double array[10][20];

or something faintly similar; maybe

double array[][20] = { { 1.0, 0.0, ... }, ... };

You should be able to pass that with code like this:

typedef struct graph_node
    int X;
    int Y;
    int active;
} g_node;

void print_graph(g_node graph_node[], double weight[][20], int nodes);

int main(void)
    g_node g[10];
    double array[10][20];
    int n = 10;

    print_graph(g, array, n);
    return 0;

That compiles (to object code) cleanly with GCC 4.2 (i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)) and also with GCC 4.7.0 on Mac OS X 10.7.3 using the command line:

/usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -c zzz.c

Get cursor position (in characters) within a text Input field

Got a very simple solution. Try the following code with verified result-

    function f1(el) {
    var val = el.value;
    alert(val.slice(0, el.selectionStart).length);
<input type=text id=t1 value=abcd>
    <button onclick="f1(document.getElementById('t1'))">check position</button>

I'm giving you the fiddle_demo

Eliminate space before \begin{itemize}

The way to fix this sort of problem is to redefine the relevant list environment. The enumitem package is my favourite way to do this sort of thing; it has many options and parameters that can be varied, either for all lists or for each list individually.

Here's how to do (something like) what it is I think you want:




What does a bitwise shift (left or right) do and what is it used for?

Left Shift

x = x * 2^value (normal operation)

x << value (bit-wise operation)

x = x * 16 (which is the same as 2^4)

The left shift equivalent would be x = x << 4

Right Shift

x = x / 2^value (normal arithmetic operation)

x >> value (bit-wise operation)

x = x / 8 (which is the same as 2^3)

The right shift equivalent would be x = x >> 3

How to check if a variable is both null and /or undefined in JavaScript

You can wrap it in your own function:

function isNullAndUndef(variable) {

    return (variable !== null && variable !== undefined);

clear form values after submission ajax

You can do this inside your $.post calls success callback like this


            //return the data

              //hide the graphic

              //clear fields


"Untrusted App Developer" message when installing enterprise iOS Application

You cannot avoid this unless you distribute an application via the App Store.

You get this message because the application is signed via an enterprise certificate that has not yet been trusted by the user. Apple force this prompt to appear because the application that is being installed hasn't gone through the App Store review process so is technically untrusted.

Once the user has accepted the prompt, the certificate will be marked as trusted and the application can be installed (along with any other future applications that you wish to install that have been signed with the same certificate)

Note: As pointed out in the comments, as of iOS 8, uninstalling all applications from a specific certificate will cause the prompt to be shown again once an application from said certificate is re-installed.

Here is the link to Apple website that confirms this info:

Convert a list to a string in C#

If you want something slightly more complex than a simple join you can use LINQ e.g.

var result = myList.Aggregate((total, part) => total + "(" + part.ToLower() + ")");

Will take ["A", "B", "C"] and produce "(a)(b)(c)"

CSS transition shorthand with multiple properties?

I made it work with this:

.element {
   transition: height 3s ease-out, width 5s ease-in;

Using Page_Load and Page_PreRender in ASP.Net

Page_Load happens after ViewState and PostData is sent into all of your server side controls by ASP.NET controls being created on the page. Page_Init is the event fired prior to ViewState and PostData being reinstated. Page_Load is where you typically do any page wide initilization. Page_PreRender is the last event you have a chance to handle prior to the page's state being rendered into HTML. Page_Load is the more typical event to work with.

How do I create a readable diff of two spreadsheets using git diff?

I got the problem like you so I decide to write small tool to help me out. Please check ExcelDiff_Tools. It comes with several key points:

  • Support xls, xlsx, xlsm.
  • With formula cell. It will compare both formula and value.
  • I try to make UI look like standard diff text viewer with : modified, deleted, added, unchanged status. Please take a look with image below for example: enter image description here

matplotlib colorbar for scatter

From the matplotlib docs on scatter 1:

cmap is only used if c is an array of floats

So colorlist needs to be a list of floats rather than a list of tuples as you have it now. plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. vmin and vmax can then control the limits of your colorbar. Things outside vmin/vmax get the colors of the endpoints.

How does this work for you?

import matplotlib.pyplot as plt
cm ='RdYlBu')
xy = range(20)
z = xy
sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm)

Image Example

phpmailer: Reply using only "Reply To" address

I have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:

$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');

Looking at the phpmailer code in more detail this is the offending line:

public function SetFrom($address, $name = '',$auto=1) {
   $address = trim($address);
   $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
   if (!self::ValidateAddress($address)) {
     $this->SetError($this->Lang('invalid_address').': '. $address);
     if ($this->exceptions) {
       throw new phpmailerException($this->Lang('invalid_address').': '.$address);
     echo $this->Lang('invalid_address').': '.$address;
     return false;
   $this->From = $address;
   $this->FromName = $name;
   if ($auto) {
      if (empty($this->ReplyTo)) {
         $this->AddAnAddress('ReplyTo', $address, $name);
      if (empty($this->Sender)) {
         $this->Sender = $address;
   return true;

Specifically this line:

if (empty($this->ReplyTo)) {
   $this->AddAnAddress('ReplyTo', $address, $name);

Thanks for your help everyone!

Reading a date using DataReader

        /// <summary>
    /// Returns a new conContractorEntity instance filled with the DataReader's current record data
    /// </summary>
    protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
        return new conContractorEntity()
            ConId = reader["conId"].ToString().Length > 0 ? int.Parse(reader["conId"].ToString()) : 0,
            ConEmail = reader["conEmail"].ToString(),
            ConCopyAdr = reader["conCopyAdr"].ToString().Length > 0 ? bool.Parse(reader["conCopyAdr"].ToString()) : true,
            ConCreateTime = reader["conCreateTime"].ToString().Length > 0 ? DateTime.Parse(reader["conCreateTime"].ToString()) : DateTime.MinValue


        /// <summary>
    /// Returns a new conContractorEntity instance filled with the DataReader's current record data
    /// </summary>
    protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
        return new conContractorEntity()
            ConId = GetValue<int>(reader["conId"]),
            ConEmail = reader["conEmail"].ToString(),
            ConCopyAdr = GetValue<bool>(reader["conCopyAdr"], true),
            ConCreateTime = GetValue<DateTime>(reader["conCreateTime"])

// Base methods
        protected T GetValue<T>(object obj)
        if (typeof(DBNull) != obj.GetType())
            return (T)Convert.ChangeType(obj, typeof(T));
        return default(T);

    protected T GetValue<T>(object obj, object defaultValue)
        if (typeof(DBNull) != obj.GetType())
            return (T)Convert.ChangeType(obj, typeof(T));
        return (T)defaultValue;

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

How can I make the computer beep in C#?

Try this


Numpy converting array from float to strings

You seem a bit confused as to how numpy arrays work behind the scenes. Each item in an array must be the same size.

The string representation of a float doesn't work this way. For example, repr(1.3) yields '1.3', but repr(1.33) yields '1.3300000000000001'.

A accurate string representation of a floating point number produces a variable length string.

Because numpy arrays consist of elements that are all the same size, numpy requires you to specify the length of the strings within the array when you're using string arrays.

If you use x.astype('str'), it will always convert things to an array of strings of length 1.

For example, using x = np.array(1.344566), x.astype('str') yields '1'!

You need to be more explict and use the '|Sx' dtype syntax, where x is the length of the string for each element of the array.

For example, use x.astype('|S10') to convert the array to strings of length 10.

Even better, just avoid using numpy arrays of strings altogether. It's usually a bad idea, and there's no reason I can see from your description of your problem to use them in the first place...

How to use a class from one C# project with another C# project

All too often a new developer asks this simple question which is a common problem specifically with Visual Studio IDE's. Few people answer the specific question and often critique the question or give "guesses" for solutions which don't answer the common problems. The first common problem is the IDE leads you to create new projects rather than add new files (.java, .py, .cpp, .c) to the existing solution (by default it creates a new solution) unless you change the project name and add to the current solution. This problem occurs for Python, java, c#, C++ and C project folders.

The new developer selecting "new>project>project name and changing the solution directory to "use same solution" still creates a new "project" in the same solution space, but not in the same directory space as the current user interface file or command line file which still leads to problems with "package not found" errors when building and running the project or solution. This is why the above coding suggestions to importing packages, classes, methods and functions only work (and thus don't answer the question) when the "library" file or "separate behavior" file is not only in the same solution directory path, but also in the same "user interface" or "command shell" application directory space. This does does not happen when you add another project using the new>project>project type commands of the IDE. The problem here is the new project is stored in a different directory than the existing Client or User interface code files. To create a new "file" in the same project space rather than new project the beginner needs to do the following that Microsoft won't do for you and even misleads you away from the intuitively obvious by default.

  1. Select the "application" you want to import the new behavior into (from another file)
  2. Select project>add new item
  3. Select the "program file template type" such as,, filetype.c, filetype.cpp, filetype.C#, etc. or a library class file type (something other than startup file options you see when you create a new application project or create a new library project).
  4. A new file name with default name is created in your project.
  5. Change the default name of the file to something like or faç, etc.

NOW the code recommendations to import libraries or using namespaces will work as described in the comments above and you don't have to change path statements or change solutions paths and solution names that Microsoft won't let you change easily (i.e. you can change the filenames or project names but the IDE won't automatically change the project path or the solution path names).

The following is a Python example but works similar for C#, java, or C/C++ using the includes, namespaces or using code commands appropriate to each language to find code in other classes/projects in the SAME DIRECTORY SPACE.

The application file "hello world" importing from other code files in the same directory.

Note the python white space delimiters are not going to space correctly in this stackoverflow comment editor:

print ("test")

from CIXMPythonFacade import ClassA


from CIXMPythonFacade import functionA 


class ClassName(object): 
         def __init__(object, parameter):
         object.parameter = value

The library file or "façade" file containing classes, methods or functions you want to import.

class class1(object):
    """description of class"""

class ClassA(object):
    print ("test2")
    def methodA():
        print ("test3")

def functionA ():
    print ("test4")
    return (0)


NOW how do you actually solve the mess that the IDE leads you into? To import code from another file in the same directory space you add a reference to it.

  1. Select the application file
  2. Select Project>add reference
  3. Choose the filename visible with the right directory path (check it)
  4. The reference is now available to the interpreter, the code checker and/or the compiler.

OK so now that you have this problem solved, how do you really link two separate projects together in the same solution space?

  1. You have to go to both the indexer or "intellisense" options and the compiler/interpreter and physically check or change/add the directory path statements if they are something other than what points to your "second" project or solution space. When you do the path changes or change the path variables to your workspace and to the specific locations of the projects which are different directory spaces the compiler and the code analyzer can then find these libraries, headers.h, namespaces, project or file locations.
  2. To remove old projects you created by mistake it is even worse. You have to exit the Visual Studio IDE, open windows explorer, go to the workspace directory ...documents\visualstudio xxx\solutionname\packagename select the file or folder, right click and "delete" file or folder.
  3. When you re-enter the IDE and select open solution or open package/solution, the old files and solution/package names are gone as are their misleading path statements which fools the compiler and code analyzer to look at the old directory even though you changed the filename and changed the project name, it does not change the directory path with it.

Microsoft really, really needs to fix these problem so you can intuitively create what most people want to create as new files in the same directories and remove solutions by selecting them and deleting them from the IDE. Beginners get so frustrated with directory path statements so flexible for seasoned developers, but so unfair to new developers in their defaults.

Hope this really helps you new guys and stops seasoned developers from giving you the wrong answers that don't work for you. They assume you already understand path statements and just want to type the right code...which is also why the tunnel in on trying to correct your code but does not help you fix the problem. This is probably the most common problem continually described on stackoverflow with wrong answers that don't work for new programmers.

Pipe to/from the clipboard in Bash script

  xsel -b

Does the job for X Window, and it is mostly already installed. A look in the man page of xsel is worth the effort.