Programs & Examples On #Operationcontract

WCF Service, the type provided as the service attribute values…could not be found

I had this error when I had the current build configuration in Visual Studio set to something other than Debug.

Task<> does not contain a definition for 'GetAwaiter'

GetAwaiter(), that is used by await, is implemented as an extension method in the Async CTP. I'm not sure what exactly are you using (you mention both the Async CTP and VS 2012 RC in your question), but it's possible the Async targeting pack uses the same technique.

The problem then is that extension methods don't work with dynamic. What you can do is to explicitly specify that you're working with a Task, which means the extension method will work, and then switch back to dynamic:

private async void MyButtonClick(object sender, RoutedEventArgs e)
    dynamic request = new SerializableDynamicObject();
    request.Operation = "test";

    Task<SerializableDynamicObject> task = Client(request);
    dynamic result = await task;

    // use result here

Or, since the Client() method is actually not dynamic, you could call it with SerializableDynamicObject, not dynamic, and so limit using dynamic as much as possible:

private async void MyButtonClick(object sender, RoutedEventArgs e)
    var request = new SerializableDynamicObject();
    dynamic dynamicRequest = request;
    dynamicRequest.Operation = "test";

    var task = Client(request);
    dynamic result = await task;

    // use result here

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

While I was able to solve this problem in one computer following the other users solutions, the command netsh didn't solve the issue in one of my machines and even though the current user had administrator rights I was still getting the "HTTP could not register URL.... Your process does not have access rights to this namespace". So I'm sharing my solution in case you still don't get it to work with the other solutions too.

After also trying to give write permissions to the user in the physical directory of my website and getting no success, I finally decided trying to change IIS settings.

As the images below show, I configured the Physical Path Credentials of my website to connect as an specifc user, which was an admin account with DOMAIN\username and password, and this was enough to make the error disapear.

enter image description here

enter image description here

enter image description here

Could not find an implementation of the query pattern

You must have forgotten to add a using statement to the file like this:

using System.Linq;

When to use DataContract and DataMember attributes?

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged.

Windows Communication Foundation (WCF) uses a serialization engine called the Data Contract Serializer by default to serialize and deserialize data (convert it to and from XML). All .NET Framework primitive types, such as integers and strings, as well as certain types treated as primitives, such as DateTime and XmlElement, can be serialized with no other preparation and are considered as having default data contracts. Many .NET Framework types also have existing data contracts.

You can find the full article here.

How do I return clean JSON from a WCF Service?

In your IServece.cs add the following tag : BodyStyle = WebMessageBodyStyle.Bare

 [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "Getperson/{id}")]

    List<personClass> Getperson(string id);

How to Consume WCF Service with Android

From my recent experience i would recommend ksoap library to consume a Soap WCF Service, its actually really easy, this anddev thread migh help you out too.

WCF Service Returning "Method Not Allowed"

It sounds like you're using an incorrect address:

To access the Service I enter http://localhost/project/myService.svc/FileUpload

Assuming you mean this is the address you give your client code then I suspect it should actually be:


How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

Detect if an input has text in it using CSS -- on a page I am visiting and do not control?

You can use the placeholder trick as written above w/o required field.

The problem with required is that when you wrote something, then deleted it - the input will now always be red as part of the HTML5 spec - then you'll need a CSS as written above to fix/override it.

You can simple do thing w/o required

<input type="text" placeholder="filter here" id="mytest" />


#mytest:placeholder-shown {
/* if placeholder is shown - meaning - no value in input */
  border: black 1px solid;
  color: black;
#mytest {
  /* placeholder isn't shown - we have a value in input */
  border: red 1px solid;
  color: red;

Code pen:

How to generate the whole database script in MySQL Workbench?

in mysql workbench server>>>>>>export Data then follow instructions it will generate insert statements for all tables data each table will has .sql file for all its contained data

How do I correctly use "Not Equal" in MS Access?

In Access, you will probably find a Join is quicker unless your tables are very small:

FROM Table1 
ON Table1.Column1 = Table2.Column1  
WHERE Table2.Column1 Is Null

This will exclude from the list all records with a match in Table2.

How can I select random files from a directory in bash?

This is the only script I can get to play nice with bash on MacOS. I combined and edited snippets from the following two links:

ls command: how can I get a recursive full-path listing, one line per file?


# Reads a given directory and picks a random file.

# The directory you want to use. You could use "$1" instead if you
# wanted to parametrize it.
# DIR="$1"

# Internal Field Separator set to newline, so file names with
# spaces do not break our script.

if [[ -d "${DIR}" ]]
  # Runs ls on the given dir, and dumps the output into a matrix,
  # it uses the new lines character as a field delimiter, as explained above.
  #  file_matrix=($(ls -LR "${DIR}"))

  file_matrix=($(ls -R $DIR | awk '; /:$/&&f{s=$0;f=0}; /:$/&&!f{sub(/:$/,"");s=$0;f=1;next}; NF&&f{ print s"/"$0 }'))

  # This is the command you want to run on a random file.
  # Change "ls -l" by anything you want, it's just an example.
  ls -l "${file_matrix[$((RANDOM%num_files))]}"

exit 0

How to convert AAR to JAR

The AAR file consists of a JAR file and some resource files (it is basically a standard zip file with a custom file extension). Here are the steps to convert:

  1. Extract the AAR file using standard zip extract (rename it to *.zip to make it easier)
  2. Find the classes.jar file in the extracted files
  3. Rename it as you like and use that jar file in your project

Converting binary to decimal integer output

Try this solution:

def binary_int_to_decimal(binary):
    n = 0
    for d in binary:
        n = n * 2 + d

    return n

How to determine when a Git branch was created?

Try this

  git for-each-ref --format='%(committerdate) %09 %(authorname) %09 %(refname)'

document.createElement("script") synchronously

This works for modern 'evergreen' browsers that support async/await and fetch.

This example is simplified, without error handling, to show the basic principals at work.

// This is a modern JS dependency fetcher - a "webpack" for the browser
const addDependentScripts = async function( scriptsToAdd ) {

  // Create an empty script element
  const s=document.createElement('script')

  // Fetch each script in turn, waiting until the source has arrived
  // before continuing to fetch the next.
  for ( var i = 0; i < scriptsToAdd.length; i++ ) {
    let r = await fetch( scriptsToAdd[i] )

    // Here we append the incoming javascript text to our script element.
    s.text += await r.text()

  // Finally, add our new script element to the page. It's
  // during this operation that the new bundle of JS code 'goes live'.

// call our browser "webpack" bundler
addDependentScripts( [
] )

SQL Not Like Statement not working

I just came across the same issue, and solved it, but not before I found this post. And seeing as your question wasn't really answered, here's my solution (which will hopefully work for you, or anyone else searching for the same thing I did;

Instead of;




Basically moving the "NOT" the other side of the field I was evaluating worked for me.

Pointers in C: when to use the ampersand and the asterisk?

Actually, you have it down pat, there's nothing more you need to know :-)

I would just add the following bits:

  • the two operations are opposite ends of the spectrum. & takes a variable and gives you the address, * takes an address and gives you the variable (or contents).
  • arrays "degrade" to pointers when you pass them to functions.
  • you can actually have multiple levels on indirection (char **p means that p is a pointer to a pointer to a char.

As to things working differently, not really:

  • arrays, as already mentioned, degrade to pointers (to the first element in the array) when passed to functions; they don't preserve size information.
  • there are no strings in C, just character arrays that, by convention, represent a string of characters terminated by a zero (\0) character.
  • When you pass the address of a variable to a function, you can de-reference the pointer to change the variable itself (normally variables are passed by value (except for arrays)).

How to reset index in a pandas dataframe?

Another solutions are assign RangeIndex or range:

df.index = pd.RangeIndex(len(df.index))

df.index = range(len(df.index))

It is faster:

df = pd.DataFrame({'a':[8,7], 'c':[2,4]}, index=[7,8])
df = pd.concat([df]*10000)
print (df.head())

In [298]: %timeit df1 = df.reset_index(drop=True)
The slowest run took 7.26 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 105 µs per loop

In [299]: %timeit df.index = pd.RangeIndex(len(df.index))
The slowest run took 15.05 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.84 µs per loop

In [300]: %timeit df.index = range(len(df.index))
The slowest run took 7.10 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 14.2 µs per loop

What version of MongoDB is installed on Ubuntu

When you entered in mongo shell using "mongo" command , that time only you will notice

MongoDB shell version v3.4.0-rc2
connecting to: mongodb://
MongoDB server version: 3.4.0-rc2

also you can try command,in mongo shell , db.version()

Get array of object's keys


For getting all of the keys of an Object you can use Object.keys(). Object.keys() takes an object as an argument and returns an array of all the keys.


const object = {_x000D_
  a: 'string1',_x000D_
  b: 42,_x000D_
  c: 34_x000D_
const keys = Object.keys(object)_x000D_
console.log(keys.length) // we can easily access the total amount of properties the object has

In the above example we store an array of keys in the keys const. We then can easily access the amount of properties on the object by checking the length of the keys array.

Getting the values with: Object.values()

The complementary function of Object.keys() is Object.values(). This function takes an object as an argument and returns an array of values. For example:

const object = {_x000D_
  a: 'random',_x000D_
  b: 22,_x000D_
  c: true_x000D_

How can I get selector from jQuery object

.selector has been deprecated as of version 1.7, removed as of 1.9

The jQuery object has a selector property I saw when digging in its code yesterday. Don't know if it's defined in the docs are how reliable it is (for future proofing). But it works!

$('*').selector // returns *

Edit: If you were to find the selector inside the event, that information should ideally be part of the event itself and not the element because an element could have multiple click events assigned through various selectors. A solution would be to use a wrapper to around bind(), click() etc. to add events instead of adding it directly.

jQuery.fn.addEvent = function(type, handler) {
    this.bind(type, {'selector': this.selector}, handler);

The selector is being passed as an object's property named selector. Access it as

Let's try it on some markup (

<p class='info'>some text and <a>a link</a></p>?

$('p a').addEvent('click', function(event) {
    alert(; // p a

Disclaimer: Remember that just as with live() events, the selector property may be invalid if DOM traversal methods are used.

<div><a>a link</a></div>

The code below will NOT work, as live relies on the selector property which in this case is a.parent() - an invalid selector.

$('a').parent().live(function() { alert('something'); });

Our addEvent method will fire, but you too will see the wrong selector - a.parent().

How to make a boolean variable switch between true and false every time a method is invoked?

in java when you set a value to variable, it return new value. So

private boolean getValue()
     return value = !value;

How do you view ALL text from an ntext or nvarchar(max) in SSMS?

PowerShell Alternative

This is an old post and I read through the answers. Still, I found it a bit too painful to output multi-line large text fields unaltered from SSMS. I ended up writing a small C# program for my needs, but got to thinking it could probably be done using the command line. Turns out, it is fairly easy to do so with PowerShell.

Start by installing the SqlServer module from an administrative PowerShell.

Install-Module -Name SqlServer

Use Invoke-Sqlcmd to run your query:

$Rows = Invoke-Sqlcmd -Query "select BigColumn from SomeTable where Id = 123" `
    -As DataRows -MaxCharLength 1000000 -ConnectionString $ConnectionString

This will return an array of rows that you can output to the console as follows:


Or output to a file as follows:

$Rows[0].BigColumn | Out-File -FilePath .\output.txt -Encoding UTF8

The result is a beautiful un-truncated text written to a file for viewing/editing. I am sure there is a similar command to save back the text to SQL Server, although that seems like a different question.

EDIT: It turns out that there was an answer by @dvlsc that described this approach as a secondary solution. I think because it was listed as a secondary answer, is the reason I missed it in the first place. I am going to leave my answer which focuses on the PowerShell approach, but wanted to at least give credit where it was due.

How do I profile memory usage in Python?

maybe it help:
<see additional>

pip install gprof2dot
sudo apt-get install graphviz

gprof2dot -f pstats profile_for_func1_001 | dot -Tpng -o profile.png

def profileit(name):
    def inner(func):
        def wrapper(*args, **kwargs):
            prof = cProfile.Profile()
            retval = prof.runcall(func, *args, **kwargs)
            # Note use of name from outer scope
            return retval
        return wrapper
    return inner

def func1(...)

Make function wait until element exists

Just use setTimeOut with recursion:

waitUntilElementIsPresent(callback: () => void): void {
    if (!this.methodToCheckIfElementIsPresent()) {
        setTimeout(() => this.waitUntilElementIsPresent(callback), 500);


this.waitUntilElementIsPresent(() => console.log('Element is present!'));

You can limit amount of attempts, so an error will be thrown when the element is not present after the limit:

waitUntilElementIsPresent(callback: () => void, attempt: number = 0): void {
    const maxAttempts = 10;
    if (!this.methodToCheckIfElementIsPresent()) {
        setTimeout(() => this.waitUntilElementIsPresent(callback, attempt), 500);
    } else if (attempt >= maxAttempts) {

extract column value based on another column pandas dataframe

Use df[df['B']==3]['A'].values if you just want item itself without the brackets

How to run a jar file in a linux commandline

sudo -sH
java -jar filename.jar

Keep in mind to never run executable file in as root.

Can a JSON value contain a multiline string

I'm not sure of your exact requirement but one possible solution to improve 'readability' is to store it as an array.

  "testCases" :
    "case.1" :
      "scenario" : "this the case 1.",
      "result" : ["this is a very long line which is not easily readble.",
                  "so i would like to write it in multiple lines.",
                  "but, i do NOT require any new lines in the output."]


The join in back again whenever required with

result.join(" ")

How to download Visual Studio 2017 Community Edition for offline installation?

I have used the exact steps from here and it worked flawlessly :

In 3 simple steps:

Step 1 : Download the respective Visual Studio 2017 version from the download page (

Step 2: Open your command prompt as Administarator, point to where your Visual studio download exe is and execute the following command (this command is specifically for Web & Desktop development) :

vs_community.exe --layout c:\vs2017layout --add Microsoft.VisualStudio.Workload.ManagedDesktop --add Microsoft.VisualStudio.Workload.NetWeb --add Component.GitHub.VisualStudio --includeOptional --lang en-US

Step 3 : Traverse to the path c:\vs2017layout in your command prompt and then run the following command (this command is specifically for Web & Desktop development)

vs_community.exe --add Microsoft.VisualStudio.Workload.ManagedDesktop --add Microsoft.VisualStudio.Workload.NetWeb --add Component.GitHub.VisualStudio --includeOptional

How can I set the value of a DropDownList using jQuery?

If you working with index you can set the selected index directly with .attr():

$("#mydropdownlist").attr('selectedIndex', 0);

This will set it to the first value in the droplist.

Edit: The way I did it above used to work. But it seems like it doesn't any longer.

But as Han so pleasantly points out in the comments, the correct way to do it is:

$("#mydropdownlist").get(0).selectedIndex = index_here;

How to declare a global variable in a .js file

Yes you can access them. You should declare them in 'public space' (outside any functions) as:

var globalvar1 = 'value';

You can access them later on, also in other files.

How to delete parent element using jQuery

You could also use this:


Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("");
URL url = new URL(domain + "/files/resource.xml");


Why do we need virtual functions in C++?

The keyword virtual tells the compiler it should not perform early binding. Instead, it should automatically install all the mechanisms necessary to perform late binding. To accomplish this, the typical compiler1 creates a single table (called the VTABLE) for each class that contains virtual functions.The compiler places the addresses of the virtual functions for that particular class in the VTABLE. In each class with virtual functions,it secretly places a pointer, called the vpointer (abbreviated as VPTR), which points to the VTABLE for that object. When you make a virtual function call through a base-class pointer the compiler quietly inserts code to fetch the VPTR and look up the function address in the VTABLE, thus calling the correct function and causing late binding to take place.

More details in this link

How do I get the name of the active user via the command line in OS X?

Via here

Checking the owner of /dev/console seems to work well.

stat -f "%Su" /dev/console

How to create a trie in Python

Python Class for Trie

Trie Data Structure can be used to store data in O(L) where L is the length of the string so for inserting N strings time complexity would be O(NL) the string can be searched in O(L) only same goes for deletion.

Can be clone from

class Node:
    def __init__(self):
        self.children = [None]*26
        self.isend = False
class trie:
    def __init__(self,):
        self.__root = Node()
    def __len__(self,):
        return len(self.search_byprefix(''))
    def __str__(self):
        ll =  self.search_byprefix('')
        string = ''
        for i in ll:
        return string
    def chartoint(self,character):
        return ord(character)-ord('a')
    def remove(self,string):
        ptr = self.__root
        length = len(string)
        for idx in range(length):
            i = self.chartoint(string[idx])
            if ptr.children[i] is not None:
                ptr = ptr.children[i]
                raise ValueError("Keyword doesn't exist in trie")
        if ptr.isend is not True:
            raise ValueError("Keyword doesn't exist in trie")
        ptr.isend = False
    def insert(self,string):
        ptr = self.__root
        length = len(string)
        for idx in range(length):
            i = self.chartoint(string[idx])
            if ptr.children[i] is not None:
                ptr = ptr.children[i]
                ptr.children[i] = Node()
                ptr = ptr.children[i]
        ptr.isend = True
    def search(self,string):
        ptr = self.__root
        length = len(string)
        for idx in range(length):
            i = self.chartoint(string[idx])
            if ptr.children[i] is not None:
                ptr = ptr.children[i]
                return False
        if ptr.isend is not True:
            return False
        return True
    def __getall(self,ptr,key,key_list):
        if ptr is None:
        if ptr.isend==True:
        for i in range(26):
            if ptr.children[i]  is not None:
    def search_byprefix(self,key):
        ptr = self.__root
        key_list = []
        length = len(key)
        for idx in range(length):
            i = self.chartoint(key[idx])
            if ptr.children[i] is not None:
                ptr = ptr.children[i]
                return None
        return key_list

t = trie()

Code Oputpt

['minakshi', 'minhaj']

What __init__ and self do in Python?

A brief illustrative example

In the hope it might help a little, here's a simple example I used to understand the difference between a variable declared inside a class, and a variable declared inside an __init__ function:

class MyClass(object):
    i = 123
    def __init__(self):
        self.i = 345
a = MyClass()



Ruby on Rails generates model field:type - what are the options for field:type?

There are lots of data types you can mention while creating model, some examples are:

:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean, :references



How do I open the "front camera" on the Android platform?

public void surfaceCreated(SurfaceHolder holder) {
    try {
        mCamera =;

        Camera.Parameters p = mCamera.getParameters();
    } catch (IOException e) {
        // TODO Auto-generated catch block

Using variable in SQL LIKE statement

DECLARE @SearchLetter2 char(1)

Set this to a longer char.

Why is JavaFX is not included in OpenJDK 8 on Ubuntu Wily (15.10)?

According to the packages list in Ubuntu Wily Xenial Bionic there is a package named openjfx. This should be a candidate for what you're looking for:

JavaFX/OpenJFX 8 - Rich client application platform for Java

You can install it via:

sudo apt-get install openjfx

It provides the following JAR files to the OpenJDK installation on Ubuntu systems:


If you want to have sources available, for example for debugging, you can additionally install:

sudo apt-get install openjfx-source

rotate image with css

Perform rotation using transform: rotate(xdeg) and also apply overflow: hidden to the parent component to avoid overlapping effect

.div-parent {
   overflow: hidden

.div-child {
   transform: rotate(270deg);

AngularJS : Initialize service with asynchronous data

You can use JSONP to asynchronously load service data. The JSONP request will be made during the initial page load and the results will be available before your application starts. This way you won't have to bloat your routing with redundant resolves.

You html would look like this:

<script src=""></script>

function MyService {
  this.getData = function(){
MyService.setData = function(data) { = data;

.service('MyService', MyService)

<script src="/some_data.php?jsonp=MyService.setData"></script>

How to use LogonUser properly to impersonate domain user from workgroup client

Invalid login/password could be also related to issues in your DNS server - that's what happened to me and cost me good 5 hours of my life. See if you can specify ip address instead on domain name.

Parsing date string in Go

If you have worked with time/date formatting/parsing in other languages you might have noticed that the other languages use special placeholders for time/date formatting. For eg ruby language uses

%d for day
%Y for year

etc. Golang, instead of using codes such as above, uses date and time format placeholders that look like date and time only. Go uses standard time, which is:

Mon Jan 2 15:04:05 MST 2006  (MST is GMT-0700)
01/02 03:04:05PM '06 -0700

So if you notice Go uses

01 for the day of the month,
02 for the month
03 for hours,
04 for minutes
05 for second
and so on

Therefore for example for parsing 2020-01-29, layout string should be 06-01-02 or 2006-01-02.

You can refer to the full placeholder layout table at this link -

Synchronous XMLHttpRequest warning and <script>

In my case this was caused by the flexie script which was part of the "CDNJS Selections" app offered by Cloudflare.

According to Cloudflare "This app is being deprecated in March 2015". I turned it off and the message disappeared instantly.

You can access the apps by visiting

null check in jsf expression language

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

How to remove all white spaces from a given text file

This answer is similar to other however as some people have been complaining that the output goes to STDOUT i am just going to suggest redirecting it to the original file and overwriting it. I would never normally suggest this but sometimes quick and dirty works.

cat file.txt | tr -d " \t\n\r" > file.txt

Convert a String representation of a Dictionary to a dictionary?

To summarize:

import ast, yaml, json, timeit

descs=['short string','long string']

for  desc,string in zip(descs,strings):
    for  func in funcs:
        print(func.__module__+' '+func.__name__+':')
        %timeit func(string)        


*** short string ***

json loads:
4.47 µs ± 33.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
builtins eval:
24.1 µs ± 163 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
ast literal_eval:
30.4 µs ± 299 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
yaml load:
504 µs ± 1.29 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

*** long string ***

json loads:
29.6 µs ± 230 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
builtins eval:
219 µs ± 3.92 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
ast literal_eval:
331 µs ± 1.89 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
yaml load:
9.02 ms ± 92.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Conclusion: prefer json.loads

How to get the Enum Index value in C#

Use a cast:

public enum MyEnum : int    {
    A = 0,
    B = 1,
    AB = 2,

int val = (int)MyEnum.A;

How to save an HTML5 Canvas as an image on a server?

In addition to Salvador Dali's answer:

on the server side don't forget that the data comes in base64 string format. It's important because in some programming languages you need to explisitely say that this string should be regarded as bytes not simple Unicode string.

Otherwise decoding won't work: the image will be saved but it will be an unreadable file.

Distinct in Linq based on only one field of the table

but I need results where r.text is not duplicated

Sounds as if you want this:

table1.GroupBy(x => x.Text)
      .Where(g => g.Count() == 1)
      .Select(g => g.First());

This will select rows where the Text is unique.

How to add custom validation to an AngularJS form?

Some great examples and libs presented in this thread, but they didn't quite have what I was looking for. My approach: angular-validity -- a promise based validation lib for asynchronous validation, with optional Bootstrap styling baked-in.

An angular-validity solution for the OP's use case might look something like this:

<input  type="text" name="field4" ng-model="field4"
        validity-eval="!(field1 && field2 && field3 && !field4)"
        validity-message-eval="This field is required">

Here's a Fiddle, if you want to take it for a spin. The lib is available on GitHub, has detailed documentation, and plenty of live demos.

Maximum Length of Command Line String

As @Sugrue I'm also digging out an old thread.

To explain why there is 32768 (I think it should be 32767, but lets believe experimental testing result) characters limitation we need to dig into Windows API.

No matter how you launch program with command line arguments it goes to ShellExecute, CreateProcess or any extended their version. These APIs basically wrap other NT level API that are not officially documented. As far as I know these calls wrap NtCreateProcess, which requires OBJECT_ATTRIBUTES structure as a parameter, to create that structure InitializeObjectAttributes is used. In this place we see UNICODE_STRING. So now lets take a look into this structure:

typedef struct _UNICODE_STRING {
    USHORT Length;
    USHORT MaximumLength;
    PWSTR  Buffer;

It uses USHORT (16-bit length [0; 65535]) variable to store length. And according this, length indicates size in bytes, not characters. So we have: 65535 / 2 = 32767 (because WCHAR is 2 bytes long).

There are a few steps to dig into this number, but I hope it is clear.

Also, to support @sunetos answer what is accepted. 8191 is a maximum number allowed to be entered into cmd.exe, if you exceed this limit, The input line is too long. error is generated. So, answer is correct despite the fact that cmd.exe is not the only way to pass arguments for new process.

Display SQL query results in php

You cannot directly see the query result using mysql_query its only fires the query in mysql nothing else.

For getting the result you have to add a lil things in your script like

 $sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) ORDER BY idM1O LIMIT 1";

 $result = mysql_query($sql);
 //echo [$result];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

This will give you result;

How to run a Python script in the background even after I logout SSH?

If you've already started the process, and don't want to kill it and restart under nohup, you can send it to the background, then disown it.

Ctrl+Z (suspend the process)

bg (restart the process in the background

disown %1 (assuming this is job #1, use jobs to determine)

How to submit a form with JavaScript by clicking a link?

this works well without any special function needed. Much easier to write with php as well. <input onclick="this.form.submit()"/>

Run class in Jar file

Use java -cp myjar.jar com.mypackage.myClass.

  1. If the class is not in a package then simply java -cp myjar.jar myClass.

  2. If you are not within the directory where myJar.jar is located, then you can do:

    1. On Unix or Linux platforms:

      java -cp /location_of_jar/myjar.jar com.mypackage.myClass

    2. On Windows:

      java -cp c:\location_of_jar\myjar.jar com.mypackage.myClass

CSS how to make scrollable list

Another solution would be as below where the list is placed under a drop-down button.

  <button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
    >Markets<span class="caret"></span></button>

    <ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
      {{ }}

django change default runserver port

create a bash script with the following:

exec ./ runserver<your_port>

save it as runserver in the same dir as

chmod +x runserver

and run it as


SQL Server: Attach incorrect version 661

SQL Server 2008 databases are version 655. SQL Server 2008 R2 databases are 661. You are trying to attach an 2008 R2 database (v. 661) to an 2008 instance and this is not supported. Once the database has been upgraded to an 2008 R2 version, it cannot be downgraded. You'll have to either upgrade your 2008 SP2 instance to R2, or you have to copy out the data in that database into an 2008 database (eg using the data migration wizard, or something equivalent).

The message is misleading, to say the least, it says 662 because SQL Server 2008 SP2 does support 662 as a database version, this is when 15000 partitions are enabled in the database, see Support for 15000 Partitions.docx. Enabling the support bumps the DB version to 662, disabling it moves it back to 655. But SQL Server 2008 SP2 does not support 661 (the R2 version).

How can I create a blank/hardcoded column in a sql query?

    0 as placeholder

And '' as placeholder for strings.

Socket transport "ssl" in PHP not enabled

I was having problem in Windows 7 with PHP 5.4.0 in command line, using Xampp 1.8.1 server. This is what i did:

  1. Rename php.ini-production to php.ini (in C:\xampp\php\ folder)
  2. Edit php.ini and uncomment extension_dir=ext.
  3. Also uncomment extension=php_openssl.dll.

After that it worked fine.

Equation for testing if a point is inside a circle

As said above -- use Euclidean distance.

from math import hypot

def in_radius(c_x, c_y, r, x, y):
    return math.hypot(c_x-x, c_y-y) <= r

Bootstrap footer at the bottom of the page

In my case for Bootstrap4:

<body class="d-flex flex-column min-vh-100">
    <div class="wrapper flex-grow-1"></div>

Switch case with fallthrough?

  • Do not use () behind function names in bash unless you like to define them.
  • use [23] in case to match 2 or 3
  • static string cases should be enclosed by '' instead of ""

If enclosed in "", the interpreter (needlessly) tries to expand possible variables in the value before matching.

case "$C" in

For case insensitive matching, you can use character classes (like [23]):

case "$C" in

# will match C='Abra' and C='abra'

# will match all letter cases at any char like `abra`, `ABRA` or `AbRa`


But abra didn't hit anytime because it will be matched by the first case.

If needed, you can omit ;; in the first case to continue testing for matches in following cases too. (;; jumps to esac)

In Bash, how can I check if a string begins with some value?

I always try to stick with POSIX sh instead of using Bash extensions, since one of the major points of scripting is portability (besides connecting programs, not replacing them).

In sh, there is an easy way to check for an "is-prefix" condition.

case $HOST in node*)
    # Your code here

Given how old, arcane and crufty sh is (and Bash is not the cure: It's more complicated, less consistent and less portable), I'd like to point out a very nice functional aspect: While some syntax elements like case are built-in, the resulting constructs are no different than any other job. They can be composed in the same way:

if case $HOST in node*) true;; *) false;; esac; then
    # Your code here

Or even shorter

if case $HOST in node*) ;; *) false;; esac; then
    # Your code here

Or even shorter (just to present ! as a language element -- but this is bad style now)

if ! case $HOST in node*) false;; esac; then
    # Your code here

If you like being explicit, build your own language element:

beginswith() { case $2 in "$1"*) true;; *) false;; esac; }

Isn't this actually quite nice?

if beginswith node "$HOST"; then
    # Your code here

And since sh is basically only jobs and string-lists (and internally processes, out of which jobs are composed), we can now even do some light functional programming:

beginswith() { case $2 in "$1"*) true;; *) false;; esac; }
checkresult() { if [ $? = 0 ]; then echo TRUE; else echo FALSE; fi; }

all() {
    test=$1; shift
    for i in "$@"; do
        $test "$i" || return

all "beginswith x" x xy xyz ; checkresult  # Prints TRUE
all "beginswith x" x xy abc ; checkresult  # Prints FALSE

This is elegant. Not that I'd advocate using sh for anything serious -- it breaks all too quickly on real world requirements (no lambdas, so we must use strings. But nesting function calls with strings is not possible, pipes are not possible, etc.)

Adding new column to existing DataFrame in Python pandas

If the column you are trying to add is a series variable then just :

df["new_columns_name"]=series_variable_name #this will do it for you

This works well even if you are replacing an existing column.just type the new_columns_name same as the column you want to replace.It will just overwrite the existing column data with the new series data.

AngularJS - Trigger when radio button is selected

There are at least 2 different methods of invoking functions on radio button selection:

1) Using ng-change directive:

<input type="radio" ng-model="value" value="foo" ng-change='newValue(value)'>

and then, in a controller:

$scope.newValue = function(value) {

Here is the jsFiddle:

2) Watching the model for changes. This doesn't require anything special on the input level:

<input type="radio" ng-model="value" value="foo">

but in a controller one would have:

$scope.$watch('value', function(value) {

And the jsFiddle:

Knowing more about your the use case would help to propose an adequate solution.

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

Do the following (see in photo)

  1. Goto asset catalog
  2. right-click and choose "Add New Launch Image"

    • iPhone 6 -> 750 x 1334
    • iPhone 6 Plus -> 1242 x 2208 and 2208 x 1242

enter image description here

How do check if a PHP session is empty?


add a temporary column with a value

I'm rusty on SQL but I think you could use select as to make your own temporary query columns.

select field1, field2, 'example' as newfield from table1

That would only exist in your query results, of course. You're not actually modifying the table.

Can I use Class.newInstance() with constructor arguments?

Do not use Class.newInstance(); see this thread: Why is Class.newInstance() evil?

Like other answers say, use Constructor.newInstance() instead.

Setting the default Java character encoding

I think a better approach than setting the platform's default character set, especially as you seem to have restrictions on affecting the application deployment, let alone the platform, is to call the much safer String.getBytes("charsetName"). That way your application is not dependent on things beyond its control.

I personally feel that String.getBytes() should be deprecated, as it has caused serious problems in a number of cases I have seen, where the developer did not account for the default charset possibly changing.

Get epoch for a specific date using Javascript

Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

const unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
const javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');

// expected output: 0

// expected output: 818035920000

Explore more at: Date.parse()

Resize command prompt through commands

You can use /start /max [your batch] it will fill the screen with the program it oppose to /min

How to convert password into md5 in jquery?

<script src=""></script>
    var passhash = CryptoJS.MD5(password).toString();

      { user: username, pass: passhash },
      'json' );

Format JavaScript date as yyyy-mm-dd

Reformatting a date string is fairly straightforward, e.g.

var s = 'Sun May 11,2014';_x000D_
function reformatDate(s) {_x000D_
  function z(n){return ('0' + n).slice(-2)}_x000D_
  var months = [,'jan','feb','mar','apr','may','jun',_x000D_
  var b = s.split(/\W+/);_x000D_
  return b[3] + '-' +_x000D_
    z(months.indexOf(b[1].substr(0,3).toLowerCase())) + '-' +_x000D_

SQL Server : GROUP BY clause to get comma-separated values

SELECT  [ReportId], 
        SUBSTRING(d.EmailList,1, LEN(d.EmailList) - 1) EmailList
            SELECT DISTINCT [ReportId]
            FROM Table1
        ) a
            SELECT [Email] + ', ' 
            FROM Table1 AS B 
            WHERE A.[ReportId] = B.[ReportId]
            FOR XML PATH('')
        ) D (EmailList) 

SQLFiddle Demo

Execution order of events when pressing PrimeFaces p:commandButton

I just love getting information like BalusC gives here - and he is kind enough to help SO many people with such GOOD information that I regard his words as gospel, but I was not able to use that order of events to solve this same kind of timing issue in my project. Since BalusC put a great general reference here that I even bookmarked, I thought I would donate my solution for some advanced timing issues in the same place since it does solve the original poster's timing issues as well. I hope this code helps someone:

        <p:pickList id="formPickList" 
                    itemValue="#{mediaFiles}" >
            <f:facet name="sourceCaption">Available Media</f:facet>
            <f:facet name="targetCaption">Chosen Media</f:facet>

        <p:commandButton id="viewStream_btn" 
                         value="Stream chosen media" 
                         icon="fa fa-download"
                         style="margin-top:5px" >
            <p:ajax process="formPickList"  />

The dialog is at the top of the XHTML outside this form and it has a form of its own embedded in the dialog along with a datatable which holds additional commands for streaming the media that all needed to be primed and ready to go when the dialog is presented. You can use this same technique to do things like download customized documents that need to be prepared before they are streamed to the user's computer via fileDownload buttons in the dialog box as well.

As I said, this is a more complicated example, but it hits all the high points of your problem and mine. When the command button is clicked, the result is to first insure the backing bean is updated with the results of the pickList, then tell the backing bean to prepare streams for the user based on their selections in the pick list, then update the controls in the dynamic dialog with an update, then show the dialog box ready for the user to start streaming their content.

The trick to it was to use BalusC's order of events for the main commandButton and then to add the <p:ajax process="formPickList" /> bit to ensure it was executed first - because nothing happens correctly unless the pickList updated the backing bean first (something that was not happening for me before I added it). So, yea, that commandButton rocks because you can affect previous, pending and current components as well as the backing beans - but the timing to interrelate all of them is not easy to get a handle on sometimes.

Happy coding!

mysql query order by multiple items

SELECT some_cols
FROM prefix_users
WHERE (some conditions)
ORDER BY pic_set DESC, last_activity;

How to use jQuery to show/hide divs based on radio button selection?

    $("input[name=group1]").change(function() {
        var test = $(this).val();

It's correct input[name=group1] in this example. However, thanks for the code!

How to get name of the computer in VBA?

Looks like I'm late to the game, but this is a common question...

This is probably the code you want.

Please note that this code is in the public domain, from Usenet, MSDN, and the Excellerando blog.

Public Function ComputerName() As String
'' Returns the host name

'' Uses late-binding: bad for performance and stability, useful for 
'' code portability. The correct declaration is:

'   Dim objNetwork  As IWshRuntimeLibrary.WshNetwork
'   Set objNetwork = New IWshRuntimeLibrary.WshNetwork

    Dim objNetwork As Object
    Set objNetwork = CreateObject("WScript.Network")

    ComputerName = objNetwork.ComputerName
    Set objNetwork = Nothing

End Function

You'll probably need this, too:

Public Function UserName(Optional WithDomain As Boolean = False) As String
'' Returns the user's network name

'' Uses late-binding: bad for performance and stability, useful for
'' code portability. The correct declaration is:

'   Dim objNetwork  As IWshRuntimeLibrary.WshNetwork
'   Set objNetwork = New IWshRuntimeLibrary.WshNetwork

    Dim objNetwork As Object
    Set objNetwork = CreateObject("WScript.Network")

    If WithDomain Then
        UserName = objNetwork.UserDomain & "\" & objNetwork.UserName
        UserName = objNetwork.UserName
    End If
    Set objNetwork = Nothing

End Function

How to create a TextArea in Android

If you do not want to allow user to enter text TextView is the best option here. Any how you can also add EditText for this purpose. here is a sample code for that.

This would automatically show scrollbar if there is more text than the specified lines.

    android:scrollbars="vertical" />

Edit: Adding attributes below to textView would make it a textArea that would not be editable.

android:minLines="6" // optional

How to calculate sum of a formula field in crystal Reports?

The only reason that I know of why a formula wouldn't be available to summarize on is if it didn't reference any database fields or whose value wasn't dynamic throughout sections of the report. For example, if you have a formula that returns a constant it won't be available. Or if it only references a field that is set throughout the report and returns a value based on that field, like "if {parameter}=1 then 1" would not be available either.

In general, the formula's value should not be static through the sections of the report you're summarizing over (Though the way Crystal determines this is beyond me and this doesn't seem to be a hard and fast rule)

EDIT: One other reason why a formula wouldn't be available is if you're already using a summary function in that formula. Only one level of summaries at a time!

Iterate through every file in one directory

To skip . & .., you can use Dir::each_child.

Dir.each_child('/path/to/dir') do |filename|
  puts filename

Dir::children returns an array of the filenames.

How to write a stored procedure using phpmyadmin and how to use it through php?

/*what is wrong with the following?*/

    in  pStatus char(1), 
    out pStatusDescr  char(10))
    IF (pStatus == 'Y THEN
 SET pStatusDescr = 'Active';
    ELSEIF (pStatus == 'N') THEN
        SET pStatusDescr = 'In-Active';
        SET pStatusDescr = 'Unknown';
    END IF;


How to window.scrollTo() with a smooth effect

2018 Update

Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.

const btn = document.getElementById('elem');_x000D_
btn.addEventListener('click', () => window.scrollTo({_x000D_
  top: 400,_x000D_
  behavior: 'smooth',_x000D_
#x {_x000D_
  height: 1000px;_x000D_
  background: lightblue;_x000D_
<div id='x'>_x000D_
  <button id='elem'>Click to scroll</button>_x000D_

Older solutions

You can do something like this:

var btn = document.getElementById('x');_x000D_
btn.addEventListener("click", function() {_x000D_
  var i = 10;_x000D_
  var int = setInterval(function() {_x000D_
    window.scrollTo(0, i);_x000D_
    i += 10;_x000D_
    if (i >= 200) clearInterval(int);_x000D_
  }, 20);_x000D_
body {_x000D_
  background: #3a2613;_x000D_
  height: 600px;_x000D_
<button id='x'>click</button>

ES6 recursive approach:

const btn = document.getElementById('elem');_x000D_
const smoothScroll = (h) => {_x000D_
  let i = h || 0;_x000D_
  if (i < 200) {_x000D_
    setTimeout(() => {_x000D_
      window.scrollTo(0, i);_x000D_
      smoothScroll(i + 10);_x000D_
    }, 10);_x000D_
btn.addEventListener('click', () => smoothScroll());
body {_x000D_
  background: #9a6432;_x000D_
  height: 600px;_x000D_
<button id='elem'>click</button>

how to convert java string to Date object

var startDate = "06/27/2007";
startDate = new Date(startDate);


"Cannot create an instance of OLE DB provider" error as Windows Authentication user

Similar situation for following configuration:

  • Windows Server 2012 R2 Standard
  • MS SQL server 2008 (tested also SQL 2012)
  • Oracle 10g client (OracleDB v8.1.7)
  • MSDAORA provider
  • Error ID: 7302

My solution:

  • Install 32bit MS SQL Server (64bit MSDAORA doesn't exist)
  • Install 32bit Oracle 10g patch (set W7 compatibility on setup.exe)
  • Restart SQL services
  • Check Allow in process in MSDAORA provider
  • Test linked oracle server connection

Listing information about all database files in SQL Server

If you rename your Database, MS SQL Server does not rename the underlying files.

Following query gives you the current name of the database and the Logical file name (which might be the original name of the Database when it was created) and also corresponding physical file names.

Note: Un-comment the last line to see only the actual data files

select  db.database_id, "Database Name", "Logical File Name",
from    sys.master_files files 
        join sys.databases db on db.database_id = files.database_id 
--                           and files.type_desc = 'ROWS'


error LNK2001: unresolved external symbol (C++)

Sounds like you are using Microsoft Visual C++. If that is the case, then the most possibility is that you don't compile your two.cpp with one.cpp (one.cpp is the implementation for one.h).

If you are from command line (cmd.exe), then try this first: cl -o two.exe one.cpp two.cpp

If you are from IDE, right click on the project name from Solution Explore. Then choose Add, Existing Item.... Add one.cpp into your project.

Can't find android device using "adb devices" command

I know this thread is old, but I think this could still help. Almost all the time "it just works" on OS X, but sometimes new/prototype or obscure devices aren't picked up. Try to help it out with these steps (I'm not near my Mac right now, but I did this last night and think I remember):

  1. Open System Profiler and find the device on USB. View it's details to find the Vendor ID. For example, Motorola devices will show 0x2bb8. Or just Google for your vendor's hardware id.

    If nothing shown, make sure to try different cables. Android File Transfer is good for detecting the device if you have a valid cable.

  2. Edit ~/.android/adb_usb.ini to include that Vendor ID. If the file doesn't exist, create it with that line only.

  3. Restart ADB

    adb kill-server 
    adb start-server
  4. Maybe unplug/plugin your phone.

And hopefully you see your device.

Changing CSS for last <li>

2015 Answer: CSS last-of-type allows you to style the last item.

ul li:last-of-type { color: red; }

PopupWindow $BadTokenException: Unable to add window -- token null is not valid

A popup's parent can't itself be a popup. Both of their parents must be the same. So, if you create a popup inside a popup, you must save the parent's popup and make it a parent.

here's an example

Angular 2 Sibling Component Communication

This is not what you exactly want but for sure will help you out

I'm surprised there's not more information out there about component communication <=> consider this tutorial by angualr2

For sibling components communication, I'd suggest to go with sharedService. There are also other options available though.

import {Component,bind} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from 'angular2/http';
import {NameService} from 'src/nameService';

import {TheContent} from 'src/content';
import {Navbar} from 'src/nav';

  selector: 'app',
  directives: [TheContent,Navbar],
  providers: [NameService],
  template: '<navbar></navbar><thecontent></thecontent>'

export class App {
  constructor() {
    console.log('App started');


Please refer to link at top for more code.

Edit: This is a very small demo. You have already mention that you have already tried with sharedService. So please consider this tutorial by angualr2 for more information.

How to analyze information from a Java core dump?

IBM provide a number of tools which can be used on the sun jvm as well. Take a look at some of the projects on alphaworks, they provide a heap and thread dump analyzers


How to detect a textbox's content has changed

I'd like to ask why you are trying to detect when the content of the textbox changed in real time?

An alternative would be to set a timer (via setIntval?) and compare last saved value to the current one and then reset a timer. This would guarantee catching ANY change, whether caused by keys, mouse, some other input device you didn't consider, or even JavaScript changing the value (another possiblity nobody mentioned) from a different part of the app.

How to make Twitter bootstrap modal full screen

My variation of the solution: (scss)

  .modal {
        .modal-dialog.modal-fs {
            width: 100%;
            margin: 0;
            box-shadow: none;
            height: 100%;
            .modal-content {
                border: none;
                border-radius: 0;
                box-shadow: none;
                box-shadow: none;
                height: 100%;


.modal .modal-dialog.modal-fs {
  width: 100%;
  margin: 0;
  box-shadow: none;
  height: 100%;
.modal .modal-dialog.modal-fs .modal-content {
  border: none;
  border-radius: 0;
  box-shadow: none;
  box-shadow: none;
  height: 100%;

disable Bootstrap's Collapse open/close animation

If you find the 1px jump before expanding and after collapsing when using the CSS solution a bit annoying, here's a simple JavaScript solution for Bootstrap 3...

Just add this somewhere in your code:

    $('.collapse').on('', function(e) {
    $('[data-toggle="collapse"]').on('click', function(e) {

How do I turn a String into a InputStreamReader in java?

Are you trying to get a) Reader functionality out of InputStreamReader, or b) InputStream functionality out of InputStreamReader? You won't get b). InputStreamReader is not an InputStream.

The purpose of InputStreamReader is to take an InputStream - a source of bytes - and decode the bytes to chars in the form of a Reader. You already have your data as chars (your original String). Encoding your String into bytes and decoding the bytes back to chars would be a redundant operation.

If you are trying to get a Reader out of your source, use StringReader.

If you are trying to get an InputStream (which only gives you bytes), use apache commons IOUtils.toInputStream(..) as suggested by other answers here.

set font size in jquery

$("#"+styleTarget).css('font-size', newFontSize);

c# open a new form then close the current form?

Many different ways have already been described by the other answers. However, many of them either involved ShowDialog() or that form1 stay open but hidden. The best and most intuitive way in my opinion is to simply close form1 and then create form2 from an outside location (i.e. not from within either of those forms). In the case where form1 was created in Main, form2 can simply be created using Application.Run just like form1 before. Here's an example scenario:

I need the user to enter their credentials in order for me to authenticate them somehow. Afterwards, if authentication was successful, I want to show the main application to the user. In order to accomplish this, I'm using two forms: LogingForm and MainForm. The LoginForm has a flag that determines whether authentication was successful or not. This flag is then used to decide whether to create the MainForm instance or not. Neither of these forms need to know about the other and both forms can be opened and closed gracefully. Here's the code for this:

class LoginForm : Form
    public bool UserSuccessfullyAuthenticated { get; private set; }

    void LoginButton_Click(object s, EventArgs e)
        if(AuthenticateUser(/* ... */))
            UserSuccessfullyAuthenticated = true;

static class Program
    static void Main()
        LoginForm loginForm = new LoginForm();

            // MainForm is defined elsewhere
            Application.Run(new MainForm());

How do you get a timestamp in JavaScript?

Get TimeStamp In JavaScript

In JavaScript, a timestamp is the number of milliseconds that have passed since January 1, 1970.

If you don't intend to support < IE8, you can use

new Date().getTime(); + new Date(); and;

to directly get the timestamp without having to create a new Date object.

To return the required timestamp

new Date("11/01/2018").getTime()

How to check if an object implements an interface?

For an instance

Character.Gorgon gor = new Character.Gorgon();

Then do

gor instanceof Monster

For a Class instance do

Class<?> clazz = Character.Gorgon.class;

Php header location redirect not working

I have experienced that kind of issue before and now I'm not using header('Location: pageExample.php'); anymore, instead I'm using javascript's document.location.

Change your:

header('Location: page1.php');

To something like this:

echo "<script type='text/javascript'> document.location = 'page1.php'; </script>";

And what is the purpose of echo $_POST['cancel']; by the way?, just delete that line if what you want is just the redirection. I've been using that <script> every time and it doesn't fail me. :-)

How can I create an array with key value pairs?

No need array_push function.if you want to add multiple item it works fine. simply try this and it worked for me

class line_details {
   var $commission_one=array();
   foreach($_SESSION['commission'] as $key=>$data){
          $row=  explode('-', $key);
          $this->commission_one[$row['0']]= $row['1'];            


How do I find all the files that were created today in Unix/Linux?

You can use find and ls to accomplish with this:

find . -type f -exec ls -l {} \; |  egrep "Aug 26";

It will find all files in this directory, display useful informations (-l) and filter the lines with some date you want... It may be a little bit slow, but still useful in some cases.

Cannot import keras after installation

Ran to the same issue, Assuming your using anaconda3 and your using a venv with >= python=3.6:

python -m pip install keras
sudo python -m pip install --user tensorflow

How can I rename column in laravel using migration?

The above answer is great or if it will not hurt you, just rollback the migration and change the name and run migration again.

 php artisan migrate:rollback

A regular expression to exclude a word/string

As you want to exclude both words, you need a conjuction:


Now both conditions must be true (neither ignoreme nor ignoreme2 is allowed) to have a match.

Looking to understand the iOS UIViewController lifecycle

As per Apple's doc — Start Developing iOS Apps (Swift) — Work with View Controllers — Understand the View Controller Lifecycle

viewDidLoad()—Called when the view controller’s content view (the top of its view hierarchy) is created and loaded from a storyboard. … Use this method to perform any additional setup required by your view controller.

viewWillAppear()—Called just before the view controller’s content view is added to the app’s view hierarchy. Use this method to trigger any operations that need to occur before the content view is presented onscreen

viewDidAppear()—Called just after the view controller’s content view has been added to the app’s view hierarchy. Use this method to trigger any operations that need to occur as soon as the view is presented onscreen, such as fetching data or showing an animation.

viewWillDisappear()—Called just before the view controller’s content view is removed from the app’s view hierarchy. Use this method to perform cleanup tasks like committing changes or resigning the first responder status.

viewDidDisappear()—Called just after the view controller’s content view has been removed from the app’s view hierarchy. Use this method to perform additional teardown activities.

How to show Snackbar when Activity starts?

You can also define a super class for all your activities and find the view once in the parent activity.

for example :

public class AppActivity extends AppCompatActivity {

    protected View content;

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        content = findViewById(;

and your snacks would look like this in every activity in your app:

Snackbar.make(content, "hello every body", Snackbar.LENGTH_SHORT).show();

It is better for performance you have to find the view once for every activity.

CSS to set A4 paper size


body {
  background: rgb(204,204,204); 
page[size="A4"] {
  background: white;
  width: 21cm;
  height: 29.7cm;
  display: block;
  margin: 0 auto;
  margin-bottom: 0.5cm;
  box-shadow: 0 0 0.5cm rgba(0,0,0,0.5);
@media print {
  body, page[size="A4"] {
    margin: 0;
    box-shadow: 0;


<page size="A4"></page>
<page size="A4"></page>
<page size="A4"></page>


How to split the screen with two equal LinearLayouts?

To Split a layout to equal parts

Use Layout Weights. Keep in mind that it is important to set layout_width as 0dp on children to make it work as intended.

on parent layout:

  1. Set weightSum of parent Layout as 1 (android:weightSum="1")

on the child layout:

  1. Set layout_width as 0dp (android:layout_width="0dp")
  2. Set layout_weight as 0.5 [half of weight sum fr equal two] (android:layout_weight="0.5")

To split layout to three equal parts:

  • parent: weightSum 3
  • child: layout_weight: 1

To split layout to four equal parts:

  • parent: weightSum 1
  • child: layout_weight: 0.25

To split layout to n equal parts:

  • parent: weightSum n
  • child: layout_weight: 1

Below is an example layout for splitting layout to two equal parts.



        <TextView .. />

        <EditText .../>



        <TextView ../>

        <EditText ../>



Limit the height of a responsive image with css

I set the below 3 styles to my img tag

max-height: 500px;
height: 70%;
width: auto;

What it does that for desktop screen img doesn't grow beyond 500px but for small mobile screens, it will shrink to 70% of the outer container. Works like a charm.

It also works width property.

How to differ sessions in browser-tabs?

Storing the timeStamp in window.sessionStorage if it is not already set. This will give a unique value for each tab(even if the URLs are same)

Hope this helps.

How can I print the contents of a hash in Perl?

The easiest way in my experiences is to just use Dumpvalue.

use Dumpvalue;
my %hash = { key => "value", foo => "bar" };
my $dumper = new DumpValue();

Works like a charm and you don't have to worry about formatting the hash, as it outputs it like the Perl debugger does (great for debugging). Plus, Dumpvalue is included with the stock set of Perl modules, so you don't have to mess with CPAN if you're behind some kind of draconian proxy (like I am at work).

How can I make a "color map" plot in matlab?

By default mesh will color surface values based on the (default) jet colormap (i.e. hot is higher). You can additionally use surf for filled surface patches and set the 'EdgeColor' property to 'None' (so the patch edges are non-visible).

[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;

% surface in 3D

enter image description here

2D map: You can get a 2D map by switching the view property of the figure

% 2D map using view

enter image description here

... or treating the values in Z as a matrix, viewing it as a scaled image using imagesc and selecting an appropriate colormap.

% using imagesc to view just Z
colormap jet; 

enter image description here

The color pallet of the map is controlled by colormap(map), where map can be custom or any of the built-in colormaps provided by MATLAB:

enter image description here

Update/Refining the map: Several design options on the map (resolution, smoothing, axis etc.) can be controlled by the regular MATLAB options. As @Floris points out, here is a smoothed, equal-axis, no-axis labels maps, adapted to this example:

surf(X, Y, Z,'EdgeColor', 'None', 'facecolor', 'interp');
axis equal; 
axis off;

enter image description here

How to get the return value from a thread in python?

Parris / kindall's answer join/return answer ported to Python 3:

from threading import Thread

def foo(bar):
    print('hello {0}'.format(bar))
    return "foo"

class ThreadWithReturnValue(Thread):
    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None):
        Thread.__init__(self, group, target, name, args, kwargs, daemon=daemon)

        self._return = None

    def run(self):
        if self._target is not None:
            self._return = self._target(*self._args, **self._kwargs)

    def join(self):
        return self._return

twrv = ThreadWithReturnValue(target=foo, args=('world!',))

print(twrv.join())   # prints foo

Note, the Thread class is implemented differently in Python 3.

How to change the floating label color of TextInputLayout

to change color of the text label when you are focusing on it. i.e. typing in it. you have to add specify

<item name="android:textColorPrimary">@color/yourcolorhere</item>

Just a note: You have to add all these implementations to your main theme.

What do Push and Pop mean for Stacks?

Ok. As the other answerers explained, a stack is a last-in, first-out data structure. You add an element to the top of the stack with a Push operation. You take an element off the top with a Pop operation. The elements are removed in reverse order to the order they were put inserted (hence Last In, First Out). For example, if you push the elments 1,2,3 in that order, the number 3 will be at the top of the stack. A Pop operation will remove it (it was the last in) and leave 2 at the top of the stack.

Regarding the rest of the lecture, the lecturer tried to describe a stack-based machine that evaluates arithmetic expressions. The machine operates by continuously popping 3 elements from the top of the stack. The first two elements are operands and the third is an operator (+, -, *, /). It then applies this operator on the operands, and pushes the result onto the stack. The process continues until there is only one element on the stack, which is the value of the expression.

So, suppose we begin by pushing the values "+/*23-21*5-41" in left-to-right order onto the stack. We then pop 3 elements from the top. The last in is first out, which means the first 3 element are "1", "4", and "-" in that order. We push the number 3 (the result of 4-1) onto the stack, then pop the three topmost elements: 3, 5, *. Push the result, 15, onto the stack, and so on.

How to resolve Nodejs: Error: ENOENT: no such file or directory

In my case the issue was caused by using a file path starting at the directory where the script was executing rather than at the root of the project.

My directory stucture was like this: projectfolder/ +-- package.json +-- scriptFolder/ ¦ +-- myScript.js

And I was calling fs.createReadStream('users.csv') instead of the correct fs.createReadStream('scriptFolder/users.csv')

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

I have found this on MS connect:

Yes, you need to install Visual Studio 2010 on your build machine to build database projects. Doing so does not require an additional license of Visual Studio.

So, this is the only option that I have for now.

Presto SQL - Converting a date string to date format

If your string is in ISO 8601 format, you can also use from_iso8601_timestamp

How to use XMLReader in PHP?

XMLReader is well documented on PHP site. This is a XML Pull Parser, which means it's used to iterate through nodes (or DOM Nodes) of given XML document. For example, you could go through the entire document you gave like this:

$reader = new XMLReader();
if (!$reader->open("data.xml"))
    die("Failed to open 'data.xml'");
    $node = $reader->expand();
    // process $node...

It is then up to you to decide how to deal with the node returned by XMLReader::expand().

Select current date by default in ASP.Net Calendar control

Two ways of doing it.

Late binding

<asp:Calendar ID="planning" runat="server" SelectedDate="<%# DateTime.Now %>"></asp:Calendar>

Code behind way (Page_Load solution)

protected void Page_Load(object sender, EventArgs e)

private void BindCalendar()
    planning.SelectedDate = DateTime.Today;

Altough, I strongly recommend to do it from a BindMyStuff way. Single entry point easier to debug. But since you seems to know your game, you're all set.

What is the best way to implement a "timer"?

It's not clear what type of application you're going to develop (desktop, web, console...)

The general answer, if you're developing Windows.Forms application, is use of

System.Windows.Forms.Timer class. The benefit of this is that it runs on UI thread, so it's simple just define it, subscribe to its Tick event and run your code on every 15 second.

If you do something else then windows forms (it's not clear from the question), you can choose System.Timers.Timer, but this one runs on other thread, so if you are going to act on some UI elements from the its Elapsed event, you have to manage it with "invoking" access.

Wget output document and headers to STDOUT

wget -S -O - works as expected for me, but with a caveat: the headers are considered debugging information and as such they are sent to the standard error rather than the standard output. If you are redirecting the standard output to a file or another process, you will only get the document contents.

You can try redirecting the standard error to the standard output as a possible solution. For example, in bash:

$ wget -q -S -O - 2>&1 | grep ...


$ wget -q -S -O - 1>wget.txt 2>&1

The -q option suppresses the progress bar and some other annoyingly chatty parts of the wget output.

Are multiple `.gitignore`s frowned on?

You can have multiple .gitignore, each one of course in its own directory.
To check which gitignore rule is responsible for ignoring a file, use git check-ignore: git check-ignore -v -- afile.

And you can have different version of a .gitignore file per branch: I have already seen that kind of configuration for ensuring one branch ignores a file while the other branch does not: see this question for instance.

If your repo includes several independent projects, it would be best to reference them as submodules though.
That would be the actual best practices, allowing each of those projects to be cloned independently (with their respective .gitignore files), while being referenced by a specific revision in a global parent project.
See true nature of submodules for more.

Note that, since git 1.8.2 (March 2013) you can do a git check-ignore -v -- yourfile in order to see which gitignore run (from which .gitignore file) is applied to 'yourfile', and better understand why said file is ignored.
See "which gitignore rule is ignoring my file?"

Loading scripts after page load?

You will need to inspect the DOM to check this works. Jquery is needed.

   var el = document.createElement('script');
   el.type = 'application/ld+json';
   el.text = JSON.stringify({ "@context": "",  "@type": "Recipe", "name": "My recipe name" });


How to add an extra row to a pandas dataframe

Upcoming pandas 0.13 version will allow to add rows through loc on non existing index data. However, be aware that under the hood, this creates a copy of the entire DataFrame so it is not an efficient operation.

Description is here and this new feature is called Setting With Enlargement.

Doctrine findBy 'does not equal'

Based on the answer from Luis, you can do something more like the default findBy method.

First, create a default repository class that is going to be used by all your entities.

/* $config is the entity manager configuration object. */
$config->setDefaultRepositoryClassName( 'MyCompany\Repository' );

Or you can edit this in config.yml

doctrine: orm: default_repository_class: MyCompany\Repository



namespace MyCompany;

use Doctrine\ORM\EntityRepository;

class Repository extends EntityRepository {

    public function findByNot( array $criteria, array $orderBy = null, $limit = null, $offset = null )
        $qb = $this->getEntityManager()->createQueryBuilder();
        $expr = $this->getEntityManager()->getExpressionBuilder();

        $qb->select( 'entity' )
            ->from( $this->getEntityName(), 'entity' );

        foreach ( $criteria as $field => $value ) {
            // IF INTEGER neq, IF NOT notLike
            if($this->getEntityManager()->getClassMetadata($this->getEntityName())->getFieldMapping($field)["type"]=="integer") {
                $qb->andWhere( $expr->neq( 'entity.' . $field, $value ) );
            } else {
                $qb->andWhere( $expr->notLike( 'entity.' . $field, $qb->expr()->literal($value) ) );

        if ( $orderBy ) {

            foreach ( $orderBy as $field => $order ) {

                $qb->addOrderBy( 'entity.' . $field, $order );

        if ( $limit )
            $qb->setMaxResults( $limit );

        if ( $offset )
            $qb->setFirstResult( $offset );

        return $qb->getQuery()


The usage is the same than the findBy method, example:

$entityManager->getRepository( 'MyRepo' )->findByNot(
    array( 'status' => Status::STATUS_DISABLED )

Generating a Random Number between 1 and 10 Java

This will work for generating a number 1 - 10. Make sure you import Random at the top of your code.

import java.util.Random;

If you want to test it out try something like this.

Random rn = new Random();

for(int i =0; i < 100; i++)
    int answer = rn.nextInt(10) + 1;

Also if you change the number in parenthesis it will create a random number from 0 to that number -1 (unless you add one of course like you have then it will be from 1 to the number you've entered).

How to Update Multiple Array Elements in mongodb

I've been looking for a solution to this using the newest driver for C# 3.6 and here's the fix I eventually settled on. The key here is using "$[]" which according to MongoDB is new as of version 3.6. See[] for more information.

Here's the code:

   var filter = Builders<Scene>.Filter.Where(i => i.ID != null);
   var update = Builders<Scene>.Update.Unset("area.$[].discoveredBy");
   var result = collection.UpdateMany(filter, update, new UpdateOptions { IsUpsert = true});

For more context see my original post here: Remove array element from ALL documents using MongoDB C# driver

Cannot GET / Nodejs Error

If you are getting this error, it could be because you don't have a route defined for your get.

For example:

const express = require('express');

const app = express();

app.get('/people', function (req, res) {


http://http://localhost:3000/people --> this works
http://http://localhost:3000 --> this will output Cannot GET / message.

How to center text vertically with a large font-awesome icon?

Try set your icon as height: 100%

You don't need to do anything with the wrapper (say, your button).

This requires Font Awesome 5. Not sure if it works for older FA versions.

.wrap svg {
    height: 100%;

Note that the icon is actually a svg graphic.


How to create websockets server in PHP


// server.php

$server = stream_socket_server("tcp://", $errno, $errorMessage);

if($server == false) {
    throw new Exception("Could not bind to socket: $errorMessage");


for(;;) {
    $client = @stream_socket_accept($server);

    if($client) {
        stream_copy_to_stream($client, $client);

from one terminal run : php server.php

from another terminal run: echo "hello woerld" | nc 8002

Angular 2 / 4 / 5 not working in IE11

The latest version of core-js lib provides the polyfills from a different path. so use the following in the polyfills.js. And also change the target value to es5 in the tsconfig.base.json

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es/symbol';
import 'core-js/es/object';
import 'core-js/es/function';
import 'core-js/es/parse-int';
import 'core-js/es/parse-float';
import 'core-js/es/number';
import 'core-js/es/math';
import 'core-js/es/string';
import 'core-js/es/date';
import 'core-js/es/array';
import 'core-js/es/regexp';
import 'core-js/es/map';

How to get resources directory path programmatically

I'm assuming the contents of src/main/resources/ is copied to WEB-INF/classes/ inside your .war at build time. If that is the case you can just do (substituting real values for the classname and the path being loaded).

URL sqlScriptUrl = MyServletContextListener.class

ngrok command not found

add line in .zshrc

# vi .zshrc

alias ngrok="/usr/local/lib/node_modules/node/lib/node_modules/node/lib/node_modules/ngrok/bin/ngrok"

How to manually install a pypi module without pip/easy_install?

To further explain Sheena's answer, I needed to have setup-tools installed as a dependency of another tool e.g. more-itertools.


Click the Clone or download button and choose your method. I placed these into a dev/py/libs directory in my user home directory. It does not matter where they are saved, because they will not be installed there.

Installing setup-tools

You will need to run the following inside the setup-tools directory.

python install

General dependencies installation

Now you can navigate to the more-itertools direcotry and install it as normal.

  1. Download the package
  2. Unpackage it if it's an archive
  3. Navigate (cd ...) into the directory containing
  4. If there are any installation instructions contained in the documentation contained herein, read and follow the instructions OTHERWISE
  5. Type in: python install

Find rows that have the same value on a column in MySQL

Get the entire record as you want using the condition with inner select query.

FROM   member
WHERE  email IN (SELECT email
                 FROM   member
                 WHERE  login_id = [email protected]) 

PIL image to array (numpy array to array) - Python

Based on zenpoy's answer:

import Image
import numpy

def image2pixelarray(filepath):
    filepath : str
        Path to an image file

        A list of lists which make it simple to access the greyscale value by
    im ='L')
    (width, height) = im.size
    greyscale_map = list(im.getdata())
    greyscale_map = numpy.array(greyscale_map)
    greyscale_map = greyscale_map.reshape((height, width))
    return greyscale_map

Reducing the gap between a bullet and text in a list item

You could try the following. But it requires you to put a <span> element inside the <li> elements

<style type="text/css">
ul.a li span{



<ul class="a">
  <li><span>Coca Cola</span></li>

How to state in requirements.txt a direct github source

Since pip v1.5, (released Jan 1 2014: CHANGELOG, PR) you may also specify a subdirectory of a git repo to contain your module. The syntax looks like this:

pip install -e git+https://git.repo/some_repo.git#egg=my_subdir_pkg&subdirectory=my_subdir_pkg # install a python package from a repo subdirectory

Note: As a pip module author, ideally you'd probably want to publish your module in it's own top-level repo if you can. Yet this feature is helpful for some pre-existing repos that contain python modules in subdirectories. You might be forced to install them this way if they are not published to pypi too.

Python dictionary replace values

via dict.update() function

In case you need a declarative solution, you can use dict.update() to change values in a dict.

Either like this:

my_dict.update({'key1': 'value1', 'key2': 'value2'})

or like this:

my_dict.update(key1='value1', key2='value2')

via dictionary unpacking

Since Python 3.5 you can also use dictionary unpacking for this:

my_dict = { **my_dict, 'key1': 'value1', 'key2': 'value2'}

Note: This creates a new dictionary.

via merge operator or update operator

Since Python 3.9 you can also use the merge operator on dictionaries:

my_dict = my_dict | {'key1': 'value1', 'key2': 'value2'}

Note: This creates a new dictionary.

Or you can use the update operator:

my_dict |= {'key1': 'value1', 'key2': 'value2'}

Histogram using gnuplot?

As usual, Gnuplot is a fantastic tool for plotting sweet looking graphs and it can be made to perform all sorts of calculations. However, it is intended to plot data rather than to serve as a calculator and it is often easier to use an external programme (e.g. Octave) to do the more "complicated" calculations, save this data in a file, then use Gnuplot to produce the graph. For the above problem, check out the "hist" function is Octave using [freq,bins]=hist(data), then plot this in Gnuplot using

set style histogram rowstacked gap 0
set style fill solid 0.5 border lt -1
plot "./data.dat" smooth freq with boxes

Load image from resources

You can do this using the ResourceManager:

public bool info(string channel)
   object o = Properties.Resources.ResourceManager.GetObject(channel);
   if (o is Image)
       channelPic.Image = o as Image;
       return true;
   return false;

what's the correct way to send a file from REST web service to client?

Since youre using JSON, I would Base64 Encode it before sending it across the wire.

If the files are large, try to look at BSON, or some other format that is better with binary transfers.

You could also zip the files, if they compress well, before base64 encoding them.

How do I obtain a Query Execution Plan in SQL Server?

In addition to the comprehensive answer already posted sometimes it is useful to be able to access the execution plan programatically to extract information. Example code for this is below.

EXEC StartCapture @@SPID, @TraceID OUTPUT
EXEC sp_help 'sys.objects' /*<-- Call your stored proc of interest here.*/
EXEC StopCapture @TraceID

Example StartCapture Definition

@Spid INT,
DECLARE @maxfilesize BIGINT = 5
DECLARE @filepath NVARCHAR(200) = N'C:\trace_' + LEFT(NEWID(),36)

EXEC sp_trace_create @TraceID OUTPUT, 0, @filepath, @maxfilesize, NULL 

exec sp_trace_setevent @TraceID, 122, 1, 1
exec sp_trace_setevent @TraceID, 122, 22, 1
exec sp_trace_setevent @TraceID, 122, 34, 1
exec sp_trace_setevent @TraceID, 122, 51, 1
exec sp_trace_setevent @TraceID, 122, 12, 1
-- filter for spid
EXEC sp_trace_setfilter @TraceID, 12, 0, 0, @Spid
-- start the trace
EXEC sp_trace_setstatus @TraceID, 1

Example StopCapture Definition

@TraceID INT
     as (SELECT CAST(TextData AS VARCHAR(MAX)) AS TextData,
                /*costs accumulate up the tree so the MAX should be the root*/
                MAX(EstimatedTotalSubtreeCost) AS EstimatedTotalSubtreeCost
         FROM   fn_trace_getinfo(@TraceID) fn
                CROSS APPLY fn_trace_gettable(CAST(value AS NVARCHAR(200)), 1)
                CROSS APPLY (SELECT CAST(TextData AS XML) AS xPlan) x
                CROSS APPLY (SELECT T.relop.value('@EstimatedTotalSubtreeCost',
                                            'float') AS EstimatedTotalSubtreeCost
                             FROM   xPlan.nodes('//sql:RelOp') T(relop)) ca
         WHERE  property = 2
                AND TextData IS NOT NULL
                AND ObjectName not in ( 'StopCapture', 'fn_trace_getinfo' )
         GROUP  BY CAST(TextData AS VARCHAR(MAX)),
SELECT ObjectName,
       SUM(EstimatedTotalSubtreeCost) AS EstimatedTotalSubtreeCost

-- Stop the trace
EXEC sp_trace_setstatus @TraceID, 0
-- Close and delete the trace
EXEC sp_trace_setstatus @TraceID, 2

Check if event exists on element

$('body').click(function(){ alert('test' )})

var foo = $.data( $('body').get(0), 'events' ).click
// you can query $.data( object, 'events' ) and get an object back, then see what events are attached to it.

$.each( foo, function(i,o) {
    alert(i) // guid of the event
    alert(o) // the function definition of the event handler

You can inspect by feeding the object reference ( not the jQuery object though ) to $.data, and for the second argument feed 'events' and that will return an object populated with all the events such as 'click'. You can loop through that object and see what the event handler does.

Xcode couldn't find any provisioning profiles matching

You can get this issue if Apple update their terms. Simply log into your dev account and accept any updated terms and you should be good (you will need to goto Xcode -> project->signing and capabilities and retry the certificate check. This should get you going if terms are the issue.

Android emulator: How to monitor network traffic?

You can start the emulator with the command -avd Adfmf -http-proxy http://SYSTEM_IP:PORT. I used HTTP Analyzer, but it should work for anything else. More details can be found here:

How do I set an ASP.NET Label text from code behind on page load?

In your ASP.NET page:

<asp:Label ID="UserNameLabel" runat="server" />

In your code behind (assuming you're using C#):

function Page_Load(object sender, EventArgs e)
    if (!Page.IsPostBack)
       UserNameLabel.Text = "User Name";

Get selected value in dropdown list using JavaScript

You can use querySelector.


var myElement = document.getElementById('ddlViewBy');

var myValue = myElement.querySelector('[selected]').value;

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

I discovered this error on a recent application project. I was writing to run from the command line or the browser window, so I was using server detection to get the relative URL of the document I was asking for. The trouble was, the site is https, and each time I attempted to access http://(same server), cURL helpfully changed it to https.

This works fine from the browser, but from the command-line, I'd then get an SSL error even with both verify's set to false. What I had to do was,

1) Check $_SERVER['HTTP_HOST']. If present, use ($_SERVER['HTTPS'] ? "https://" : "http://").$_SERVER['HTTP_HOST']

2) Check $_SERVER['COMPUTERNAME'], and if it matched the production server, provide the https URL. ("https://(servername)")

3) If neither condition passed, it means I'm running command-line on a different server, and use "http://localhost".

Now, this worked, but it's a hack. Also, I never did figure out why on one server (https) cURL changed my URL, while on the other (also https) it left my URL alone.


How to search file text for a pattern and replace it with a given value

Actually, Ruby does have an in-place editing feature. Like Perl, you can say

ruby -pi.bak -e "gsub(/oldtext/, 'newtext')" *.txt

This will apply the code in double-quotes to all files in the current directory whose names end with ".txt". Backup copies of edited files will be created with a ".bak" extension ("foobar.txt.bak" I think).

NOTE: this does not appear to work for multiline searches. For those, you have to do it the other less pretty way, with a wrapper script around the regex.

How do I get a PHP class constructor to call its parent's parent's constructor?

You can call Grandpa::__construct from where you want and the $this keyword will refer to your current class instance. But be carefull with this method you cannot access to protected properties and methods of current instance from this other context, only to public elements. => All work and officialy supported.


// main class that everything inherits
class Grandpa 
    public function __construct()
        echo $this->one; // will print 1
        echo $this->two; // error cannot access protected property


class Papa extends Grandpa
    public function __construct()
        // call Grandpa's constructor

class Kiddo extends Papa
    public $one = 1;
    protected $two = 2;
    public function __construct()

new Kiddo();

insert data from one table to another in mysql

  INSERT INTO mt_magazine_subscription ( 
      status ) 
      (SELECT magazine_subscription_id, 
              magazine_id,'1' as status
       FROM tbl_magazine_subscription 
       ORDER BY magazine_subscription_id ASC))

Batchfile to create backup and rename with timestamp

try this:

ren "File 1-1" "File 1 - %date:/=-% %time::=-%"

On - window.location.hash - Change?

var page_url = ''; // full path leading up to hash;
var current_url_w_hash = page_url + window.location.hash; // now you might have something like:

function TrackHash() {
    if (document.location != page_url + current_url_w_hash) {
        window.location = document.location;
    return false;
var RunTabs = setInterval(TrackHash, 200);

That's it... now, anytime you hit your back or forward buttons, the page will reload as per the new hash value.

TypeError: cannot perform reduce with flexible type

When your are trying to apply prod on string type of value like:

['-214' '-153' '-58' ..., '36' '191' '-37']

you will get the error.

Solution: Append only integer value like [1,2,3], and you will get your expected output.

If the value is in string format before appending then, in the array you can convert the type into int type and store it in a list.

FIX CSS <!--[if lt IE 8]> in IE

Also, the comment tag


is only supported in IE 8 and below, so if that's exactly what you're trying to target, you could wrap them in comment tag. They're the same as

<!--[if lte IE 8]><![endif]-->

In which lte means "less than or equal to".

See: Conditional Comments.

How can I position my jQuery dialog to center?

I had a problem with this and I finally figured this out. Until today I was using a really old version of jQuery, version 1.8.2.

Everywhere where I had used dialog I had initialised it with the following position option:

    position: "center"

However, I found that removing position: "center" or replacing it with the correct syntax didn't do the trick, for example:

    position: {
       my: "center",
       at: "center",
       of: window

Although the above is correct, I was also using option to set the position as center when I loaded the page, in the old way, like so:

// The wrong old way of keeping a dialog centered
passwordDialogInstance.dialog("option", "position", "center");

This was causing all of my dialog windows to stick to the top left of the view port.

I had to replace all instances of this with the correct new syntax below:

    { my: "center", at: "center", of: window }

libxml/tree.h no such file or directory

Ray Wenderlich has a blog post about using gdata that solves this problem. Basically these simple steps:

In XCode, click Project\Edit Project Settings and make sure “All Configurations” are checked.

Find the Search Paths\Header Search Paths setting and add /usr/include/libxml2 to the list.

Finally, find the Linking\Other Linker Flags section and add -lxml2 to the list.

original post: read and write xml documents with gdataxml

Process list on Linux via Python

The sanctioned way of creating and using child processes is through the subprocess module.

import subprocess
pl = subprocess.Popen(['ps', '-U', '0'], stdout=subprocess.PIPE).communicate()[0]
print pl

The command is broken down into a python list of arguments so that it does not need to be run in a shell (By default the subprocess.Popen does not use any kind of a shell environment it just execs it). Because of this we cant simply supply 'ps -U 0' to Popen.

MetadataException when using Entity Framework Entity Connection

Found the problem.

The standard metadata string looks like this:


And this works fine in most cases. However, in some (including mine) Entity Framework get confused and does not know which dll to look in. Therefore, change the metadata string to:


And it will work. It was this link that got me on the right track:

Although I had the oposite problem, did not work in unit test, but worked in service.

Ruby String to Date Conversion

Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")

Should be:

Date.strptime(updated, '%a, %d %b %Y %H:%M:%S %Z')

Formatting DataBinder.Eval data

There is an optional overload for DataBinder.Eval to supply formatting:

<%# DataBinder.Eval(Container.DataItem, "expression"[, "format"]) %>

The format parameter is a String value, using the value placeholder replacement syntax (called composite formatting) like this:

<asp:Label id="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate", "{0:dddd d MMMM}") %>'</label>

How to right align widget in horizontal linear layout Android?

Use match_parent and gravity to set the TextView text to right, like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""

    <TextView android:text="TextView" android:id="@+id/textView1"


How merge two objects array in angularjs?

$ is not a function 

same problem with me but i solve the problem by

 $ = [].concat($ , data)

Using moment.js to convert date to string "MM/dd/yyyy"

I think you just have incorrect casing in the format string. According to the documentation this should work for you: MM/DD/YYYY

moment.js documentation

Display Python datetime without time

For me, I needed to KEEP a timetime object because I was using UTC and it's a bit of a pain. So, this is what I ended up doing:

date = datetime.datetime.utcnow()

start_of_day = date - datetime.timedelta(

end_of_day = start_of_day + datetime.timedelta(

Example output:

>>> date
datetime.datetime(2016, 10, 14, 17, 21, 5, 511600)
>>> start_of_day
datetime.datetime(2016, 10, 14, 0, 0)
>>> end_of_day
datetime.datetime(2016, 10, 14, 23, 59, 59)

Enable the display of line numbers in Visual Studio

Line numbers are not on by default. To turn on line numbers just go to Tools -> Options -> Text Editor -> All Languages -> General -> Display and check Line numbers:

Is Ruby pass by reference or by value?

The other answerers are all correct, but a friend asked me to explain this to him and what it really boils down to is how Ruby handles variables, so I thought I would share some simple pictures / explanations I wrote for him (apologies for the length and probably some oversimplification):

Q1: What happens when you assign a new variable str to a value of 'foo'?

str = 'foo'
str.object_id # => 2000

enter image description here

A: A label called str is created that points at the object 'foo', which for the state of this Ruby interpreter happens to be at memory location 2000.

Q2: What happens when you assign the existing variable str to a new object using =?

str = 'bar'.tap{|b| puts "bar: #{b.object_id}"} # bar: 2002
str.object_id # => 2002

enter image description here

A: The label str now points to a different object.

Q3: What happens when you assign a new variable = to str?

str2 = str
str2.object_id # => 2002

enter image description here

A: A new label called str2 is created that points at the same object as str.

Q4: What happens if the object referenced by str and str2 gets changed?

str2.replace 'baz'
str2 # => 'baz'
str  # => 'baz'
str.object_id # => 2002
str2.object_id # => 2002

enter image description here

A: Both labels still point at the same object, but that object itself has mutated (its contents have changed to be something else).

How does this relate to the original question?

It's basically the same as what happens in Q3/Q4; the method gets its own private copy of the variable / label (str2) that gets passed in to it (str). It can't change which object the label str points to, but it can change the contents of the object that they both reference to contain else:

str = 'foo'

def mutate(str2)
  puts "str2: #{str2.object_id}"
  str2.replace 'bar'
  str2 = 'baz'
  puts "str2: #{str2.object_id}"

str.object_id # => 2004
mutate(str) # str2: 2004, str2: 2006
str # => "bar"
str.object_id # => 2004

Ruby function to remove all white spaces?

"1232 23 2 23 232 232".delete(' ')
=> "123223223232232"

Delete works faster =)

user         system     total      real
gsub, s      0.180000   0.010000   0.190000 (0.193014)
gsub, s+     0.200000   0.000000   0.200000 (0.196408)
gsub, space  0.220000   0.000000   0.220000 (0.222711)
gsub, join   0.200000   0.000000   0.200000 (0.193478)
delete       0.040000   0.000000   0.040000 (0.045157)

Find and replace - Add carriage return OR Newline

Just a minor word of warning... a lot of environments use, or need, "\r\n" and not just "\n". I ran into an issue with Visual Studio not matching my regex string at the end of the line because I left off the "\r" of "\r\n", so my string couldn't match with a missing invisible character.

So, if you are doing a find, or a replace, consider the "\r".

For a little more detail on "\r" and "\n", see:

Adding/removing items from a JavaScript object with jQuery

Adding an object in a json array

var arrList = [];
var arr = {};   
arr['worker_id'] = worker_id;
arr['worker_nm'] = worker_nm;

Removing an object from a json

It worker for me.

  arrList = $.grep(arrList, function (e) { 

        if(e.worker_id == worker_id) {
            return false;
        } else {
            return true;

It returns an array without that object.

Hope it helps.

How to detect if URL has changed after hash in JavaScript

Found a working answer in a separate thread:

There's no one event that will always work, and monkey patching the pushState event is pretty hit or miss for most major SPAs.

So smart polling is what's worked best for me. You can add as many event types as you like, but these seem to be doing a really good job for me.

Written for TS, but easily modifiable:

const locationChangeEventType = "MY_APP-location-change";

// called on creation and every url change
export function observeUrlChanges(cb: (loc: Location) => any) {
  window.addEventListener(locationChangeEventType, () => cb(window.location));

function assertLocationChangeObserver() {
  const state = window as any as { MY_APP_locationWatchSetup: any };
  if (state.MY_APP_locationWatchSetup) { return; }
  state.MY_APP_locationWatchSetup = true;

  let lastHref = location.href;

  ["popstate", "click", "keydown", "keyup", "touchstart", "touchend"].forEach((eventType) => {
    window.addEventListener(eventType, () => {
      requestAnimationFrame(() => {
        const currentHref = location.href;
        if (currentHref !== lastHref) {
          lastHref = currentHref;
          window.dispatchEvent(new Event(locationChangeEventType));


observeUrlChanges((loc) => {

Why am I getting InputMismatchException?

I encountered the same problem. Strange, but the reason was that the object Scanner interprets fractions depending on localization of system. If the current localization uses a comma to separate parts of the fractions, the fraction with the dot will turn into type String. Hence the error ...

Html.Raw() in ASP.NET MVC Razor view

You shouldn't be calling .ToString().

As the error message clearly states, you're writing a conditional in which one half is an IHtmlString and the other half is a string.
That doesn't make sense, since the compiler doesn't know what type the entire expression should be.

There is never a reason to call Html.Raw(...).ToString().
Html.Raw returns an HtmlString instance that wraps the original string.
The Razor page output knows not to escape HtmlString instances.

However, calling HtmlString.ToString() just returns the original string value again; it doesn't accomplish anything.

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

DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture are present in Framework 4.0 too, but they are Private. Using Reflection you can easily set them. This will affect all threads where CurrentCulture is not explicitly set (running threads too).

Public Sub SetDefaultThreadCurrentCulture(paCulture As CultureInfo)
    Thread.CurrentThread.CurrentCulture.GetType().GetProperty("DefaultThreadCurrentCulture").SetValue(Thread.CurrentThread.CurrentCulture, paCulture, Nothing)
    Thread.CurrentThread.CurrentCulture.GetType().GetProperty("DefaultThreadCurrentUICulture").SetValue(Thread.CurrentThread.CurrentCulture, paCulture, Nothing)
End Sub

IF EXISTS before INSERT, UPDATE, DELETE for optimization

You should not do it for UPDATE and DELETE, as if there is impact on performance, it is not a positive one.

For INSERT there might be situations where your INSERT will raise an exception (UNIQUE CONSTRAINT violation etc), in which case you might want to prevent it with the IF EXISTS and handle it more gracefully.

How to remove default chrome style for select Input?

-webkit-appearance: none;

and add your own style

"ImportError: No module named" when trying to run Python script

Happened to me with the directory utils. I was trying to import this directory as:

from utils import somefile

utils is already a package in python. Just change your directory name to something different and it should work just fine.

How to create circular ProgressBar in android?

You can try this Circle Progress library

enter image description here

enter image description here

NB: please always use same width and height for progress views







Show div on scrollDown after 800px

If you want to show a div after scrolling a number of pixels:

Working Example

$(document).scroll(function() {
  var y = $(this).scrollTop();
  if (y > 800) {
  } else {

$(document).scroll(function() {
  var y = $(this).scrollTop();
  if (y > 800) {
  } else {
body {
  height: 1600px;
.bottomMenu {
  display: none;
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 60px;
  border-top: 1px solid #000;
  background: red;
  z-index: 1;
<script src=""></script>
<p>Scroll down... </p>
<div class="bottomMenu"></div>

Its simple, but effective.

Documentation for .scroll()
Documentation for .scrollTop()

If you want to show a div after scrolling a number of pixels,

without jQuery:

Working Example

myID = document.getElementById("myID");

var myScrollFunc = function() {
  var y = window.scrollY;
  if (y >= 800) {
    myID.className = "bottomMenu show"
  } else {
    myID.className = "bottomMenu hide"

window.addEventListener("scroll", myScrollFunc);

myID = document.getElementById("myID");

var myScrollFunc = function() {
  var y = window.scrollY;
  if (y >= 800) {
    myID.className = "bottomMenu show"
  } else {
    myID.className = "bottomMenu hide"

window.addEventListener("scroll", myScrollFunc);
body {
  height: 2000px;
.bottomMenu {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 60px;
  border-top: 1px solid #000;
  background: red;
  z-index: 1;
  transition: all 1s;
.hide {
  opacity: 0;
  left: -100%;
.show {
  opacity: 1;
  left: 0;
<div id="myID" class="bottomMenu hide"></div>

Documentation for .scrollY
Documentation for .className
Documentation for .addEventListener

If you want to show an element after scrolling to it:

Working Example

$('h1').each(function () {
    var y = $(document).scrollTop();
    var t = $(this).parent().offset().top;
    if (y > t) {
    } else {

$(document).scroll(function() {
  //Show element after user scrolls 800px
  var y = $(this).scrollTop();
  if (y > 800) {
  } else {

  // Show element after user scrolls past 
  // the top edge of its parent 
  $('h1').each(function() {
    var t = $(this).parent().offset().top;
    if (y > t) {
    } else {
body {
  height: 1600px;
.bottomMenu {
  display: none;
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 60px;
  border-top: 1px solid #000;
  background: red;
  z-index: 1;
.scrollPast {
  width: 100%;
  height: 150px;
  background: blue;
  position: relative;
  top: 50px;
  margin: 20px 0;
h1 {
  display: none;
  position: absolute;
  bottom: 0;
<script src=""></script>
<p>Scroll Down...</p>
<div class="scrollPast">
  <h1>I fade in when you scroll to my parent</h1>

<div class="scrollPast">
  <h1>I fade in when you scroll to my parent</h1>

<div class="scrollPast">
  <h1>I fade in when you scroll to my parent</h1>

<div class="bottomMenu">I fade in when you scroll past 800px</div>

Note that you can't get the offset of elements set to display: none;, grab the offset of the element's parent instead.

Documentation for .each()
Documentation for .parent()
Documentation for .offset()

If you want to have a nav or div stick or dock to the top of the page once you scroll to it and unstick/undock when you scroll back up:

Working Example

$(document).scroll(function () {
    //stick nav to top of page
    var y = $(this).scrollTop();
    var navWrap = $('#navWrap').offset().top;
    if (y > navWrap) {
    } else {

#navWrap {
nav {
    height: 70px;
.sticky {
    position: fixed;

$(document).scroll(function () {
    //stick nav to top of page
    var y = $(this).scrollTop();
    var navWrap = $('#navWrap').offset().top;
    if (y > navWrap) {
    } else {
body {
#navWrap {
nav {
    height: 70px;
.sticky {
    position: fixed;
h1 {
    margin: 0;
<script src=""></script>
<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas,
  imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum
  oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.</p>
<div id="navWrap">
    <h1>I stick to the top when you scroll down and unstick when you scroll up to my original position</h1>

<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas,
  imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum
  oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.</p>

Fixing slow initial load for IIS

I'd use B because that in conjunction with worker process recycling means there'd only be a delay while it's recycling. This avoids the delay normally associated with initialization in response to the first request after idle. You also get to keep the benefits of recycling.

How to extract a string using JavaScript Regex?

this is how you can parse iCal files with javascript

    function calParse(str) {

        function parse() {
            var obj = {};
            while(str.length) {
                var p = str.shift().split(":");
                var k = p.shift(), p = p.join();
                switch(k) {
                    case "BEGIN":
                        obj[p] = parse();
                    case "END":
                        return obj;
                        obj[k] = p;
            return obj;
        str = str.replace(/\n /g, " ").split("\n");
        return parse().VCALENDAR;

    example = 
    'PRODID:-//hacksw/handcal//NONSGML v1.0//EN\n'+
    'SUMMARY:Bastille Day Party\n'+

    cal = calParse(example);

In Perl, how can I read an entire file into a string?

Either set $/ to undef (see jrockway's answer) or just concatenate all the file's lines:

$content = join('', <$fh>);

It's recommended to use scalars for filehandles on any Perl version that supports it.

Is multiplication and division using shift operators in C actually faster?

In the case of signed integers and right shift vs division, it can make a difference. For negative numbers, the shift rounds rounds towards negative infinity whereas division rounds towards zero. Of course the compiler will change the division to something cheaper, but it will usually change it to something that has the same rounding behavior as division, because it is either unable to prove that the variable won't be negative or it simply doesn't care. So if you can prove that a number won't be negative or if you don't care which way it will round, you can do that optimization in a way that is more likely to make a difference.

Converting HTML string into DOM elements?

Why not use insertAdjacentHTML

for example:

// <div id="one">one</div> 
var d1 = document.getElementById('one'); 
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');

// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here

ggplot combining two plots from different data.frames

The only working solution for me, was to define the data object in the geom_line instead of the base object, ggplot.

Like this:

ggplot() + 
geom_line(data=Data1, aes(x=A, y=B), color='green') + 
geom_line(data=Data2, aes(x=C, y=D), color='red')

instead of

ggplot(data=Data1, aes(x=A, y=B), color='green') + 
geom_line() + 
geom_line(data=Data2, aes(x=C, y=D), color='red')

More info here

Add support library to Android Studio project

This is way more simpler with Maven dependency feature:

  1. Open File -> Project Structure... menu.
  2. Select Modules in the left pane, choose your project's main module in the middle pane and open Dependencies tab in the right pane.
  3. Click the plus sign in the right panel and select "Maven dependency" from the list. A Maven dependency dialog will pop up.
  4. Enter "support-v4" into the search field and click the icon with magnifying glass.
  5. Select "" from the drop-down list.
  6. Click "OK".
  7. Clean and rebuild your project.

Hope this will help!

Negative regex for Perl string pattern match

If my understanding is correct then you want to match any line which has Clinton and Reagan, in any order, but not Bush. As suggested by Stuck, here is a version with lookahead assertions:


use strict;
use warnings;

my $regex = qr/

while (<DATA>) {
    next unless (/$regex/);
    print $_, "\n";

shouldn't match - reagan came first, then clinton, finally bush
first match - first two: reagan and clinton
second match - first two reverse: clinton and reagan
shouldn't match - last two: clinton and bush
shouldn't match - reverse: bush and clinton
shouldn't match - and then came obama, along comes mary
shouldn't match - to clinton with perl


first match - first two: reagan and clinton
second match - first two reverse: clinton and reagan

as desired it matches any line which has Reagan and Clinton in any order.

You may want to try reading how lookahead assertions work with examples at

they are very tasty :)

Does Python have a package/module management system?

Recent progress

March 2014: Good news! Python 3.4 ships with Pip. Pip has long been Python's de-facto standard package manager. You can install a package like this:

pip install httpie

Wahey! This is the best feature of any Python release. It makes the community's wealth of libraries accessible to everyone. Newbies are no longer excluded from using community libraries by the prohibitive difficulty of setup.

However, there remains a number of outstanding frustrations with the Python packaging experience. Cumulatively, they make Python very unwelcoming for newbies. Also, the long history of neglect (ie. not shipping with a package manager for 14 years from Python 2.0 to Python 3.3) did damage to the community. I describe both below.

Outstanding frustrations

It's important to understand that while experienced users are able to work around these frustrations, they are significant barriers to people new to Python. In fact, the difficulty and general user-unfriendliness is likely to deter many of them.

PyPI website is counter-helpful

Every language with a package manager has an official (or quasi-official) repository for the community to download and publish packages. Python has the Python Package Index, PyPI.

Let's compare its pages with those of RubyGems and Npm (the Node package manager).

  1. RubyGems page for the package rails
  2. Npm page for the package express
  3. PyPI page for the package simplejson

You'll see the RubyGems and Npm pages both begin with a one-line description of the package, then large friendly instructions how to install it.

Meanwhile, woe to any hapless Python user who naively browses to PyPI. On , they'll find no such helpful instructions. There is however, a large green 'Download' link. It's not unreasonable to follow it. Aha, they click! Their browser downloads a .tar.gz file. Many Windows users can't even open it, but if they persevere they may eventually extract it, then run and eventually with the help of Google install. Some will give up and reinvent the wheel..

Of course, all of this is wrong. The easiest way to install a package is with a Pip command. But PyPI didn't even mention Pip. Instead, it led them down an archaic and tedious path.

Error: Unable to find vcvarsall.bat

Numpy is one of Python's most popular libraries. Try to install it with Pip, you get this cryptic error message:

Error: Unable to find vcvarsall.bat

Trying to fix that is one of the most popular questions on Stack Overflow: "error: Unable to find vcvarsall.bat"

Few people succeed.

For comparison, in the same situation, Ruby prints this message, which explains what's going on and how to fix it:

Please update your PATH to include build tools or download the DevKit from and follow the instructions at

Publishing packages is hard

Ruby and Nodejs ship with full-featured package managers, Gem (since 2007) and Npm (since 2011), and have nurtured sharing communities centred around GitHub. Npm makes publishing packages as easy as installing them, it already has 64k packages. RubyGems lists 72k packages. The venerable Python package index lists only 41k.


Flying in the face of its "batteries included" motto, Python shipped without a package manager until 2014.

Until Pip, the de facto standard was a command easy_install. It was woefully inadequate. The was no command to uninstall packages.

Pip was a massive improvement. It had most the features of Ruby's Gem. Unfortunately, Pip was--until recently--ironically difficult to install. In fact, the problem remains a top Python question on Stack Overflow: "How do I install pip on Windows?"

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

Most probably you may have not installed maven correctly. use this to download maven. Download the latest (Binary tar.gz) file.It worked for me.

Getting the IP Address of a Remote Socket Endpoint

You can then call the IPEndPoint..::.Address method to retrieve the remote IPAddress, and the IPEndPoint..::.Port method to retrieve the remote port number.

More from the link (fixed up alot heh):

Socket s;

IPEndPoint remoteIpEndPoint = s.RemoteEndPoint as IPEndPoint;
IPEndPoint localIpEndPoint = s.LocalEndPoint as IPEndPoint;

if (remoteIpEndPoint != null)
    // Using the RemoteEndPoint property.
    Console.WriteLine("I am connected to " + remoteIpEndPoint.Address + "on port number " + remoteIpEndPoint.Port);

if (localIpEndPoint != null)
    // Using the LocalEndPoint property.
    Console.WriteLine("My local IpAddress is :" + localIpEndPoint.Address + "I am connected on port number " + localIpEndPoint.Port);

How to pick just one item from a generator?

generator = myfunct()
while True:
   my_element =

make sure to catch the exception thrown after the last element is taken

Jquery: how to trigger click event on pressing enter key

Jquery: Fire Button click event Using enter Button Press try this::

tabindex="0" onkeypress="return EnterEvent(event)"

 <!--Enter Event Script-->
    <script type="text/javascript">
        function EnterEvent(e) {
            if (e.keyCode == 13) {
                __doPostBack('<%=btnSave.UniqueID%>', "");
    <!--Enter Event Script-->