Programs & Examples On #Mesh

A polygon mesh or unstructured grid is a collection of vertices, edges and faces that defines the shape of a polyhedral object in 3D computer graphics and solid modeling.

How to use bootstrap datepicker

You should include bootstrap-datepicker.js after bootstrap.js and you should bind the datepicker to your control.

      format: 'mm-dd-yyyy'

How to deal with persistent storage (e.g. databases) in Docker

Use Persistent Volume Claim (PVC) from Kubernetes, which is a Docker container management and scheduling tool:

Persistent Volumes

The advantages of using Kubernetes for this purpose are that:

  • You can use any storage like NFS or other storage and even when the node is down, the storage need not be.
  • Moreover the data in such volumes can be configured to be retained even after the container itself is destroyed - so that it can be reclaimed, if necessary, by another container.

CodeIgniter : Unable to load the requested file:

"Unable to load the requested file"

Can be also caused by access permissions under linux , make sure you set the correct read permissions for the directory "views/home"

How to create a custom exception type in Java?

You have to define your exception elsewhere as a new class

public class YourCustomException extends Exception{

//Required inherited methods here

Then you can throw and catch YourCustomException as much as you'd like.

Mythical man month 10 lines per developer day - how close on large projects?

How are other people doing?

I am the only full-time dev at our company and have written 500,000 lines of OCaml and F# code over the past 7 years, which equates to about 200 lines of code per day. However, the vast majority of that code is tutorial examples consisting of hundreds of separate projects each a few hundred lines long. Also, there is a lot of duplication between the OCaml and the F#. We are not maintaining any in-house code bases larger than 50kLOC.

In addition to developing and maintaining our own software, I have also consulted for many clients in industry over the past 7 years. For the first client, I wrote 2,000 lines of OCaml over 3 months which is 20 lines of code per day. For the next client, four of us wrote a compiler that generated millions of lines of C/C++/Python/Java/OCaml code as well as documentation in 6 months which is 2,000 lines of code per day per developer. For another client, I replaced 50kLOC of C++ with 6kLOC of F# in 6 months which is -352 lines of code per day. For yet another client, I am rewriting 15kLOC of OCaml in F# which will be the same size so 0 lines of code per day.

For our current client, I will replace 1,600,000 lines of C++ and Mathematica code with ~160kLOC of F# in 1 year (by writing a bespoke compiler) which will be -6,000 lines of code per day. This will be my most successful project to date and will save our client millions of dollars a year in on-going costs. I think everyone should aim to write -6,000 lines of code per day.

What is the most appropriate way to store user settings in Android application

First of all I think User's data shouldn't be stored on phone, and if it is must to store data somewhere on the phone it should be encrypted with in the apps private data. Security of users credentials should be the priority of the application.

The sensitive data should be stored securely or not at all. In the event of a lost device or malware infection, data stored insecurely can be compromised.

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

You can give like this

public static function getAll()

    return $posts = $this->all()->take(2)->get();


And when you call statically inside your controller function also..

MySQL Query to select data from last week?

If you're looking to retrieve records within the last 7 days, you can use the snippet below:

SELECT date FROM table_name WHERE DATE(date) >= CURDATE() - INTERVAL 7 DAY;

How to automate drag & drop functionality using Selenium WebDriver Java

Try implementing code given below

package com.kagrana;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class DragAndDrop {
    public void test() throws InterruptedException{
        WebDriver driver = new FirefoxDriver();
        driver.findElement(By.cssSelector("#treebox1 > div > table > tbody > tr:nth-child(2) > td:nth-child(2) > table > tbody > tr:nth-child(2) > td:nth-child(2) > table > tbody > tr:nth-child(3) > td:nth-child(2) > table > tbody > tr > td.standartTreeRow > span")).click();
        WebElement elementToMove = driver.findElement(By.cssSelector("#treebox1 > div > table > tbody > tr:nth-child(2) > td:nth-child(2) > table > tbody > tr:nth-child(2) > td:nth-child(2) > table > tbody > tr:nth-child(3) > td:nth-child(2) > table > tbody > tr > td.standartTreeRow > span"));
        WebElement moveToElement = driver.findElement(By.cssSelector("#treebox1 > div > table > tbody > tr:nth-child(2) > td:nth-child(2) > table > tbody > tr:nth-child(2) > td:nth-child(2) > table > tbody > tr:nth-child(2) > td:nth-child(2) > table > tbody > tr:nth-child(1) > td.standartTreeRow > span"));
        Actions dragAndDrop = new Actions(driver);
        Action action = dragAndDrop.dragAndDrop(elementToMove, moveToElement).build();

How do I create a message box with "Yes", "No" choices and a DialogResult?

This should do it:

DialogResult dialogResult = MessageBox.Show("Sure", "Some Title", MessageBoxButtons.YesNo);
if(dialogResult == DialogResult.Yes)
    //do something
else if (dialogResult == DialogResult.No)
    //do something else

SSL certificate is not trusted - on mobile only

The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.

If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)

You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.

How to redirect to logon page when session State time out is completed in mvc

I discover very simple way to redirect Login Page When session end in MVC. I have already tested it and this works without problems.

In short, I catch session end in _Layout 1 minute before and make redirection.

I try to explain everything step by step.

If we want to session end 30 minute after and redirect to loginPage see this steps:

  1. Change the web config like this (set 31 minute):

        <sessionState timeout="31"></sessionState>
  2. Add this JavaScript in _Layout (when session end 1 minute before this code makes redirect, it makes count time after user last action, not first visit on site)

        //session end 
        var sessionTimeoutWarning = @Session.Timeout- 1;
        var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
        setTimeout('SessionEnd()', sTimeout);
        function SessionEnd() {
            window.location = "/Account/LogOff";
  3. Here is my LogOff Action, which makes only LogOff and redirect LoginIn Page

    public ActionResult LogOff()
        Session["User"] = null; //it's my session variable
        FormsAuthentication.SignOut(); //you write this when you use FormsAuthentication
        return RedirectToAction("Login", "Account");

I hope this is a very useful code for you.

Does not contain a definition for and no extension method accepting a first argument of type could be found

There are two cases in which this error is raised.

  1. You didn't declare the variable which is used
  2. You didn't create the instances of the class

CSS full screen div with text in the middle

There is no pure CSS solution to this classical problem.

If you want to achieve this, you have two solutions:

  • Using a table (ugly, non semantic, but the only way to vertically align things that are not a single line of text)
  • Listening to window.resize and absolute positionning

EDIT: when I say that there is no solution, I take as an hypothesis that you don't know in advance the size of the block to center. If you know it, paislee's solution is very good

grep's at sign caught as whitespace

No -P needed; -E is sufficient:

grep -E '(^|\s)abc(\s|$)' 

or even without -E:

grep '\(^\|\s\)abc\(\s\|$\)' 

Can not find module “@angular-devkit/build-angular”

Another issue could be with your dev-dependencies. Please check if they have been installed properly (check if they are availabe in the node_modules folder)

If not then a quick fix would be:

npm i --only=dev

Or check how your npm settings are regarding prod:

npm config get production

In case they are set to true - change them to false:

npm config set -g production false

and setup a new angular project.

Found that hint here: (ken107 and lichunbin814)

Hope that helps.

How to fix the error "Windows SDK version 8.1" was not found?

I installed the 8.1 SDK's version:

It used 1GB (a little more) in the installation.

Update October, 9. There's a https error: the sdksetup link is

"Save link as" should help.

What's the purpose of META-INF?

You have MANIFEST.MF file inside your META-INF folder. You can define optional or external dependencies that you must have access to.


Consider you have deployed your app and your container(at run time) found out that your app requires a newer version of a library which is not inside lib folder, in that case if you have defined the optional newer version in MANIFEST.MF then your app will refer to dependency from there (and will not crash).

Source: Head First Jsp & Servlet

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

Having trouble setting working directory

Maybe it is the case that you have your path in couple of lines, you used enter to make it? If so, then part of you paths might look like that "/\nData/" instead of "/Data/", which causes the problem. Just set it to be in one line and issue is solved!

jQuery: click function exclude children.

Or you can do also:

$('.example').on('click', function(e) { 
   if( != this ) 
       return false;

   // ... //

How do you calculate program run time in python?

You might want to take a look at the timeit module:

or the profile module:

There are some additionally some nice tutorials here:

And the time module also might come in handy, although I prefer the later two recommendations for benchmarking and profiling code performance:

PowerShell equivalent to grep -f

So I found a pretty good answer at this link:

But essentially it is:

Select-String -Path "C:\file\Path\*.txt" -Pattern "^Enter REGEX Here$"

This gives a directory file search (*or you can just specify a file) and a file-content search all in one line of PowerShell, very similar to grep. The output will be similar to:

doc.txt:31: Enter REGEX Here
HelloWorld.txt:13: Enter REGEX Here

How to add items to a spinner in Android?

Add this code after updating the list


The ArrayAdapter<String> variable name is dataAdapter, and the List variable name is keys.

  • dataAdapter.addAll(keys);
  • dataAdapter.notifyDataSetChanged();

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

If you have multiple versions of a package / module, you need to be using virtualenv (emphasis mine):

virtualenv is a tool to create isolated Python environments.

The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.

Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.

Also, what if you can’t install packages into the global site-packages directory? For instance, on a shared host.

In all these cases, virtualenv can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).

That's why people consider insert(0, to be wrong -- it's an incomplete, stopgap solution to the problem of managing multiple environments.

How to get folder path from file path with CMD

In case the accepted answer by Wadih didn't work for you, try echo %CD%

Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."

In the "admin" module of your app package, do register all the databases created in "models" module of the package.

Suppose you have a database class defined in "models" module as:

class myDb1(models.Model):
    someField= models.Charfiled(max_length=100)

so you must register this in the admin module as:

from .models import myDb1

I hope this resolve the error.

How to write super-fast file-streaming code in C#?

The fastest way to do file I/O from C# is to use the Windows ReadFile and WriteFile functions. I have written a C# class that encapsulates this capability as well as a benchmarking program that looks at differnet I/O methods, including BinaryReader and BinaryWriter. See my blog post at:

DateTime.Today.ToString("dd/mm/yyyy") returns invalid DateTime Value

Lower mm means minutes, so







Standard Date and Time Format Strings

Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2)

In python 3 urllib2 was merged into urllib. See also another Stack Overflow question and the urllib PEP 3108.

To make Python 2 code work in Python 3:

    import urllib.request as urllib2
except ImportError:
    import urllib2

How can I tell which button was clicked in a PHP form submit?


<input type="submit" id="btnSubmit" name="btnSubmit" value="Save Changes" />
<input type="submit" id="btnDelete" name="btnDelete" value="Delete" />


if (isset($_POST["btnSubmit"])){
  // "Save Changes" clicked
} else if (isset($_POST["btnDelete"])){
  // "Delete" clicked

How to change a table name using an SQL query?

In Postgress SQL:

Alter table student rename to student_details;

illegal character in path


"C:/Program Files (x86)/test software/myapp/demo.exe"

How to bring view in front of everything?

If you are using a LinearLayout you should call myView.bringToFront() and after you should call parentView.requestLayout() and parentView.invalidate() to force the parent to redraw with the new child order.

How to enable C++11/C++0x support in Eclipse CDT?

Eclipse C/C++ does not recognize the symbol std::unique_ptr even though you have included the C++11 memory header in your file.

Assuming you are using the GNU C++ compiler, this is what I did to fix:

Project -> Properties -> C/C++ General -> Preprocessor Include Paths -> GNU C++ -> CDT User Setting Entries

  1. Click on the "Add..." button

  2. Select "Preprocessor Macro" from the dropdown menu

    Name: __cplusplus     Value:  201103L
  3. Hit Apply, and then OK to go back to your project

  4. Then rebuild you C++ index: Projects -> C/C++ Index -> Rebuild

Should I use <i> tag for icons instead of <span>?

Why are they using <i> tag to display icons ?

Because it is:

  • Short
  • i stands for icon (although not in HTML)

Is it not a bad practice ?

Awful practice. It is a triumph of performance over semantics.

Adb Devices can't find my phone

I have a ZTE Crescent phone (Orange San Francisco II).

When I connect the phone to the USB a disk shows up in OS X named 'ZTE_USB_Driver'.

Running adb devices displays no connected devices. But after I eject the 'ZTE_USB_Driver' disk from OS X, and run adb devices again the phone shows up as connected.

How to get am pm from the date time string using moment js

You are using the wrong format tokens when parsing your input. You should use ddd for an abbreviation of the name of day of the week, DD for day of the month, MMM for an abbreviation of the month's name, YYYY for the year, hh for the 1-12 hour, mm for minutes and A for AM/PM. See moment(String, String) docs.

Here is a working live sample:

console.log( moment('Mon 03-Jul-2017, 11:00 AM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 PM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );
<script src=""></script>

error while loading shared libraries:

If libncurses is not installed then install it and try again. sudo apt-get install libncurses5:i386

or sudo apt-get install libncurses5 for 64 bit binaries

Also install the collection of libraries by using this command sudo apt-get install ia32-libs

Creating InetAddress object in Java

InetAddress.getByName also works for ip address.

From the JavaDoc

The host name can either be a machine name, such as "", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

How to restore SQL Server 2014 backup in SQL Server 2008

If you have both versions you can create a merge replication from new to old. Create a merge publication on your newer sql server and a subscription on the older version. After initializing the subscription you can create a backup of the database with the same structure and the same content but in an older version and restore it on your old target server. You can use this method also with sql server 2016 to target 2014, 2012 or 2008.

Deleting records before a certain date

This is another example using defined column/table names.

DELETE FROM jos_jomres_gdpr_optins WHERE `date_time` < '2020-10-21 08:21:22';

How to convert an array of key-value tuples into an object

use the following way to convert the array to an object easily.

var obj = {};
   obj[e[0]] = e[1]

This will use the first element as the key and the second element as the value for each element.

XML Schema How to Restrict Attribute by Enumeration

The numerical value seems to be missing from your price definition. Try the following:

<xs:simpleType name="curr">
  <xs:restriction base="xs:string">
    <xs:enumeration value="pounds" />
    <xs:enumeration value="euros" />
    <xs:enumeration value="dollars" />

<xs:element name="price">
            <xs:extension base="xs:decimal">
              <xs:attribute name="currency" type="curr"/>

What is the difference between user variables and system variables?

Environment variable (can access anywhere/ dynamic object) is a type of variable. They are of 2 types system environment variables and user environment variables.

System variables having a predefined type and structure. That are used for system function. Values that produced by the system are stored in the system variable. They generally indicated by using capital letters Example: HOME,PATH,USER

User environment variables are the variables that determined by the user,and are represented by using small letters.

python, sort descending dataframe with pandas

New syntax (either):

 test = df.sort_values(['one'], ascending=[False])
 test = df.sort_values(['one'], ascending=[0])

Javascript negative number

How about something as simple as:

function negative(number){
    return number < 0;

The * 1 part is to convert strings to numbers.

Multiple Image Upload PHP form with one input

Multipal image uplode with other taBLE $sql1 = "INSERT INTO event(title) VALUES('$title')";

        $result1 = mysqli_query($connection,$sql1) or die(mysqli_error($connection));
        $lastid= $connection->insert_id;
        foreach ($_FILES["file"]["error"] as $key => $error) {
            if ($error == UPLOAD_ERR_OK ){
                $name = $lastid.$_FILES['file']['name'][$key];
                $target_dir = "photo/";
                $sql2 = "INSERT INTO photos(image,eventid) VALUES ('".$target_dir.$name."','".$lastid."')";
                $result2 = mysqli_query($connection,$sql2) or die(mysqli_error($connection));

And how to fetch

$query = "SELECT * FROM event ";
$result = mysqli_query($connection,$query) or die(mysqli_error());

  if($result->num_rows > 0) {
      while($r = mysqli_fetch_assoc($result)){
        $eventid= $r['id'];
        $sqli="select id,image from photos where eventid='".$eventid."'";
        $image_json_array = array();
        while($row = mysqli_fetch_assoc($resulti)){
            $image_id = $row['id'];
            $image_name = $row['image'];
            $image_json_array[] = array("id"=>$image_id,"name"=>$image_name);
        $msg1[] = array ("imagelist" => $image_json_array);


in ajax $(document).ready(function(){ $('#addCAT').validate({ rules:{name:required:true}submitHandler:function(form){var formurl = $(form).attr('action'); $.ajax({ url: formurl,type: "POST",data: new FormData(form),cache: false,processData: false,contentType: false,success: function(data) {window.location.href="{{ url('admin/listcategory')}}";}}); } })})

Redirect website after certain amount of time

Place the following HTML redirect code between the and tags of your HTML code.

<meta HTTP-EQUIV="REFRESH" content="3; url=">

The above HTML redirect code will redirect your visitors to another web page instantly. The content="3; may be changed to the number of seconds you want the browser to wait before redirecting. 4, 5, 8, 10 or 15 seconds, etc.

What are the differences between a pointer variable and a reference variable in C++?

I feel like there is yet another point that hasn't been covered here.

Unlike the pointers, references are syntactically equivalent to the object they refer to, i.e. any operation that can be applied to an object works for a reference, and with the exact same syntax (the exception is of course the initialization).

While this may appear superficial, I believe this property is crucial for a number of C++ features, for example:

  • Templates. Since template parameters are duck-typed, syntactic properties of a type is all that matters, so often the same template can be used with both T and T&.
    (or std::reference_wrapper<T> which still relies on an implicit cast to T&)
    Templates that cover both T& and T&& are even more common.

  • Lvalues. Consider the statement str[0] = 'X'; Without references it would only work for c-strings (char* str). Returning the character by reference allows user-defined classes to have the same notation.

  • Copy constructors. Syntactically it makes sense to pass objects to copy constructors, and not pointers to objects. But there is just no way for a copy constructor to take an object by value - it would result in a recursive call to the same copy constructor. This leaves references as the only option here.

  • Operator overloads. With references it is possible to introduce indirection to an operator call - say, operator+(const T& a, const T& b) while retaining the same infix notation. This also works for regular overloaded functions.

These points empower a considerable part of C++ and the standard library so this is quite a major property of references.

Write-back vs Write-Through caching?

Write-Back is a more complex one and requires a complicated Cache Coherence Protocol(MOESI) but it is worth it as it makes the system fast and efficient.

The only benefit of Write-Through is that it makes the implementation extremely simple and no complicated cache coherency protocol is required.

How to prevent multiple definitions in C?

The underscore is put there by the compiler and used by the linker. The basic path is:

test.h ---> [compiler] ---> main.o --+
test.c ---> [compiler] ---> test.o --+--> [linker] ---> main.exe

So, your main program should include the header file for the test module which should consist only of declarations, such as the function prototype:

void test(void);

This lets the compiler know that it exists when main.c is being compiled but the actual code is in test.c, then test.o.

It's the linking phase that joins together the two modules.

By including test.c into main.c, you're defining the test() function in main.o. Presumably, you're then linking main.o and test.o, both of which contain the function test().

How to style the UL list to a single line

ul li{
  display: inline;

For more see the basic list options and a basic horizontal list at listamatic. (thanks to Daniel Straight below for the links).

Also, as pointed out in the comments, you probably want styling on the ul and whatever elements go inside the li's and the li's themselves to get things to look nice.

Disable clipboard prompt in Excel VBA on workbook close

proposed solution edit works if you replace the row

Set rDst = ThisWorkbook.Sheets("SomeSheet").Cells("YourCell").Resize(rSrc.Rows.Count, rSrc.Columns.Count)


Set rDst = ThisWorkbook.Sheets("SomeSheet").Range("YourRange").Resize(rSrc.Rows.Count, rSrc.Columns.Count)

What's default HTML/CSS link color?

Default html color code like this:

Red      #FF0000  rgb(255, 0, 0)
Maroon   #800000  rgb(128, 0, 0)
Yellow   #FFFF00  rgb(255, 255, 0)
Olive    #808000  rgb(128, 128, 0)
Blue     #0000FF  rgb(0, 0, 255)
Navy     #000080  rgb(0, 0, 128)
Fuchsia  #FF00FF  rgb(255, 0, 255)
Purple   #800080  rgb(128, 0, 128)

data.frame Group By column

I would recommend having a look at the plyr package. It might not be as fast as data.table or other packages, but it is quite instructive, especially when starting with R and having to do some data manipulation.

> DF <- data.frame(A = c("1", "1", "2", "3", "3"), B = c(2, 3, 3, 5, 6))
> library(plyr)
> DF.sum <- ddply(DF, c("A"), summarize, B = sum(B))
> DF.sum
  A  B
1 1  5
2 2  3
3 3 11

Difference between dates in JavaScript

    // This is for first date
    first = new Date(2010, 03, 08, 15, 30, 10); // Get the first date epoch object
    document.write((first.getTime())/1000); // get the actual epoch values
    second = new Date(2012, 03, 08, 15, 30, 10); // Get the first date epoch object
    document.write((second.getTime())/1000); // get the actual epoch values
    diff= second - first ;
    one_day_epoch = 24*60*60 ;  // calculating one epoch
    if ( diff/ one_day_epoch > 365 ) // check , is it exceei
    alert( 'date is exceeding one year');

How do I generate random integers within a specific range in Java?

I wonder if any of the random number generating methods provided by an Apache Commons Math library would fit the bill.

For example: RandomDataGenerator.nextInt or RandomDataGenerator.nextLong

Serialize Property as Xml Attribute in Element

You will need wrapper classes:

public class SomeIntInfo
    public int Value { get; set; }

public class SomeStringInfo
    public string Value { get; set; }

public class SomeModel
    public SomeStringInfo SomeString { get; set; }

    public SomeIntInfo SomeInfo { get; set; }

or a more generic approach if you prefer:

public class SomeInfo<T>
    public T Value { get; set; }

public class SomeModel
    public SomeInfo<string> SomeString { get; set; }

    public SomeInfo<int> SomeInfo { get; set; }

And then:

class Program
    static void Main()
        var model = new SomeModel
            SomeString = new SomeInfo<string> { Value = "testData" },
            SomeInfo = new SomeInfo<int> { Value = 5 }
        var serializer = new XmlSerializer(model.GetType());
        serializer.Serialize(Console.Out, model);

will produce:

<?xml version="1.0" encoding="ibm850"?>
<SomeModel xmlns:xsi="" xmlns:xsd="">
  <SomeStringElementName Value="testData" />
  <SomeInfoElementName Value="5" />

How to Code Double Quotes via HTML Codes

There is no difference, in browsers that you can find in the wild these days (that is, excluding things like Netscape 1 that you might find in a museum). There is no reason to suspect that any of them would be deprecated ever, especially since they are all valid in XML, in HTML 4.01, and in HTML5 CR.

There is no reason to use any of them, as opposite to using the Ascii quotation mark (") directly, except in the very special case where you have an attribute value enclosed in such marks and you would like to use the mark inside the value (e.g., title="Hello &quot;world&quot;"), and even then, there are almost always better options (like title='Hello "word"' or title="Hello “word”".

If you want to use “smart” quotation marks instead, then it’s a different question, and none of the constructs has anything to do with them. Some people expect notations like &quot; to produce “smart” quotes, but it is easy to see that they don’t; the notations unambiguously denote the Ascii quote ("), as used in computer languages.

Show current assembly instruction in GDB

From within gdb press Ctrl x 2 and the screen will split into 3 parts.

First part will show you the normal code in high level language.

Second will show you the assembly equivalent and corresponding instruction Pointer.

Third will present you the normal gdb prompt to enter commands.

See the screen shot

Push an associative item into an array in JavaScript

JavaScript has associative arrays.

Here is a working snippet.

<script type="text/javascript">
  var myArray = [];
  myArray['thank'] = 'you';
  myArray['no'] = 'problem';

They are simply called objects.

"401 Unauthorized" on a directory

It is likely that you do not have the IUSR_computername permission on that folder. I've just had a quick scan and it looks like you will find the information you need here.

If that isn't the case, are you prompted for your username and password by the browser? If so it may be that IIS is configured to use Integrated authentication only, as described here.

Copy files to network computers on windows command line

Why for? What do you want to iterate? Try this.

call :cpy pc-name-1
call :cpy pc-name-2

net use \\%1\{destfolder} {password} /user:{username}
copy {file} \\%1\{destfolder}
goto :EOF

Finding the indices of matching elements in list in Python

>>> average =  [1,3,2,1,1,0,24,23,7,2,727,2,7,68,7,83,2]
>>> matches = [i for i in range(0,len(average)) if average[i]<2 or average[i]>4]
>>> matches
[0, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15]

Python unittest passing arguments

Unit testing is meant for testing the very basic functionality (the lowest level functions of the application) to be sure that your application building blocks work correctly. There is probably no formal definition of what does that exactly mean, but you should consider other kinds of testing for the bigger functionality -- see Integration testing. The unit testing framework may not be ideal for the purpose.

Java Could not reserve enough space for object heap error

4gb RAM doesn't mean you can use it all for java process. Lots of RAM is needed for system processes. Dont go above 2GB or it will be trouble some.

Before starting jvm just check how much RAM is available and then set memory accordingly.

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

In my case there was problem in URL. I've use - but they ensure 'www.' - so when i switched to everything was ok. The proper header was sent 'Host:'.

You can try make a request in firefox brwoser, persist it and copy as cURL - that how I've found it.

How to check if input date is equal to today's date?

Date.js is a handy library for manipulating and formatting dates. It can help in this situation.

How do I force Kubernetes to re-pull an image?

Apparently now when you run a rolling-update with the --image argument the same as the existing container image, you must also specify an --image-pull-policy. The following command should force a pull of the image when it is the same as the container image:

kubectl rolling-update myapp --image-pull-policy Always

Make an Android button change background on click through XML

public void methodOnClick(View view){



i recommend use button inside LinearLayout for adjust to size of Linear.

Check if option is selected with jQuery, if not select a default

This question is old and has a lot of views, so I'll just throw some stuff out there that will help some people I'm sure.

To check if a select element has any selected items:

if ($('#mySelect option:selected').length > 0) { alert('has a selected item'); }

or to check if a select has nothing selected:

if ($('#mySelect option:selected').length == 0) { alert('nothing selected'); }

or if you're in a loop of some sort and want to check if the current element is selected:

$('#mySelect option').each(function() {
    if ($(this).is(':selected')) { .. }

to check if an element is not selected while in a loop:

$('#mySelect option').each(function() {
    if ($(this).not(':selected')) { .. }

These are some of the ways to do this. jQuery has many different ways of accomplishing the same thing, so you usually just choose which one appears to be the most efficient.

Change text (html) with .animate

The animate(..) function' signature is:

.animate( properties, options );

And it says the following about the parameter properties:

properties A map of CSS properties that the animation will move toward.

text is not a CSS property, this is why the function isn't working as you expected.

Do you want to fade the text out? Do you want to move it? I might be able to provide an alternative.

Have a look at the following fiddle.

What is the preferred Bash shebang?

/bin/sh is usually a link to the system's default shell, which is often bash but on, e.g., Debian systems is the lighter weight dash. Either way, the original Bourne shell is sh, so if your script uses some bash (2nd generation, "Bourne Again sh") specific features ([[ ]] tests, arrays, various sugary things, etc.), then you should be more specific and use the later. This way, on systems where bash is not installed, your script won't run. I understand there may be an exciting trilogy of films about this evolution...but that could be hearsay.

Also note that when evoked as sh, bash to some extent behaves as POSIX standard sh (see also the GNU docs about this).

Remove characters before character "."

You can use the IndexOf method and the Substring method like so:

string output = input.Substring(input.IndexOf('.') + 1);

The above doesn't have error handling, so if a period doesn't exist in the input string, it will present problems.

What's the difference between import java.util.*; and import java.util.Date; ?

but what I got is something like this: Date@124bbbf  
while I change the import to: import java.util.Date;  
the code works perfectly, why? 

What do you mean by "works perfectly"? The output of printing a Date object is the same no matter whether you imported java.util.* or java.util.Date. The output that you get when printing objects is the representation of the object by the toString() method of the corresponding class.

Retrieve data from website in android app

You can use jsoup to parse any kind of web page. Here you can find the jsoup library and full source code.

Here is an example:

To install in Eclipse:

  1. Right Click on project
  2. BuildPath
  3. Add External Archives
  4. select the .jar file

You can parse according to tag/parent/child very comfortably

Filtering JSON array using jQuery grep()

var data = {_x000D_
  "items": [{_x000D_
    "id": 1,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 2,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 3,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 4,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 5,_x000D_
    "category": "cat1"_x000D_
//Filters an array of numbers to include only numbers bigger then zero._x000D_
//Exact Data you want..._x000D_
var returnedData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1" && === 3;_x000D_
}, false);_x000D_
$('#id').text('Id is:-' + returnedData[0].id)_x000D_
$('#category').text('Category is:-' + returnedData[0].category)_x000D_
//Filter an array of numbers to include numbers that are not bigger than zero._x000D_
//Exact Data you don't want..._x000D_
var returnedOppositeData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1";_x000D_
}, true);_x000D_
<script src=""></script>_x000D_
<p id='id'></p>_x000D_
<p id='category'></p>

The $.grep() method eliminates items from an array as necessary so that only remaining items carry a given search. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.

Access item in a list of lists

List1 = [[10,-13,17],[3,5,1],[13,11,12]]

num = 50
for i in List1[0]:num -= i
print num

Right query to get the current number of connections in a PostgreSQL DB

Those two requires aren't equivalent. The equivalent version of the first one would be:

SELECT sum(numbackends) FROM pg_stat_database;

In that case, I would expect that version to be slightly faster than the second one, simply because it has fewer rows to count. But you are not likely going to be able to measure a difference.

Both queries are based on exactly the same data, so they will be equally accurate.

Difference between .dll and .exe?

There are a few more differences regarding the structure you could mention.

  1. Both DLL and EXE share the same file structure - Portable Executable, or PE. To differentiate between the two, one can look in the Characteristics member of IMAGE_FILE_HEADER inside IMAGE_NT_HEADERS. For a DLL, it has the IMAGE_FILE_DLL (0x2000) flag turned on. For a EXE it's the IMAGE_FILE_EXECUTABLE_IMAGE (0x2) flag.
  2. PE files consist of some headers and a number of sections. There's usually a section for code, a section for data, a section listing imported functions and a section for resources. Some sections may contain more than one thing. The header also describes a list of data directories that are located in the sections. Those data directories are what enables Windows to find what it needs in the PE. But one type of data directory that an EXE will never have (unless you're building a frankenstein EXE) is the export directory. This is where DLL files have a list of functions they export and can be used by other EXE or DLL files. On the other side, each DLL and EXE has an import directory where it lists the functions and DLL files it requires to run.
  3. Also in the PE headers (IMAGE_OPTIONAL_HEADER) is the ImageBase member. It specifies the virtual address at which the PE assumes it will be loaded. If it is loaded at another address, some pointers could point to the wrong memory. As EXE files are amongst the first to be loaded into their new address space, the Windows loader can assure a constant load address and that's usually 0x00400000. That luxury doesn't exist for a DLL. Two DLL files loaded into the same process can request the same address. This is why a DLL has another data directory called Base Relocation Directory that usually resides in its own section - .reloc. This directory contains a list of places in the DLL that need to be rebased/patched so they'll point to the right memory. Most EXE files don't have this directory, but some old compilers do generate them.

You can read more on this topic @ MSDN.

Convert a String In C++ To Upper Case

If you are only concerned with 8 bit characters (which all other answers except Milan Babuškov assume as well) you can get the fastest speed by generating a look-up table at compile time using metaprogramming. On this runs 7x faster than the library function and 3x faster than a hand written version ( It is also customizeable through traits with no slow down.

template<int ...Is>
struct IntVector{
using Type = IntVector<Is...>;

template<typename T_Vector, int I_New>
struct PushFront;
template<int ...Is, int I_New>
struct PushFront<IntVector<Is...>,I_New> : IntVector<I_New,Is...>{};

template<int I_Size, typename T_Vector = IntVector<>>
struct Iota : Iota< I_Size-1, typename PushFront<T_Vector,I_Size-1>::Type> {};
template<typename T_Vector>
struct Iota<0,T_Vector> : T_Vector{};

template<char C_In>
struct ToUpperTraits {
    enum { value = (C_In >= 'a' && C_In <='z') ? C_In - ('a'-'A'):C_In };

template<typename T>
struct TableToUpper;
template<int ...Is>
struct TableToUpper<IntVector<Is...>>{
    static char at(const char in){
        static const char table[] = {ToUpperTraits<Is>::value...};
        return table[in];

int tableToUpper(const char c){
    using Table = TableToUpper<typename Iota<256>::Type>;
    return Table::at(c);

with use case:


For an in depth (many page) decription of how it works allow me to shamelessly plug my blog:

How can I use pointers in Java?

As Java has no pointer data types, it is impossible to use pointers in Java. Even the few experts will not be able to use pointers in java.

See also the last point in: The Java Language Environment

Regex for allowing alphanumeric,-,_ and space

Try this regex

*Updated regex


This will allow only single space or - or _ between the text

Ex: this-some abc123_regex

To learn :

*Note: I have updated the regex based on Toto question

What's the difference between Docker Compose vs. Dockerfile

Imagine you are the manager of a software company and you just bought a brand new server. Just the hardware.

Think of Dockerfile as a set of instructions you would tell your system adminstrator what to install on this brand new server. For example:

  • We need a Debian linux
  • add an apache web server
  • we need postgresql as well
  • install midnight commander
  • when all done, copy all *.php, *.jpg, etc. files of our project into the webroot of the webserver (/var/www)

By contrast, think of docker-compose.yml as a set of instructions you would tell your system administrator how the server can interact with the rest of the world. For example,

  • it has access to a shared folder from another computer,
  • it's port 80 is the same as the port 8000 of the host computer,
  • and so on.

(This is not a precise explanation but good enough to start with.)

How to add a delay for a 2 or 3 seconds


Or with using statements:


I prefer this to 1000 * numSeconds (or simply 3000) because it makes it more obvious what is going on to someone who hasn't used Thread.Sleep before. It better documents your intent.

How can I refresh a page with jQuery?

Probably shortest (12 chars) - use history


PHP Undefined Index

if you use isset like the answer posted already by singles, just make sure there is a bracket at the end like so:
$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);

Linear Layout and weight in Android

Substitute wrap_content with fill_parent.


You need to put the CTE first and then combine the INSERT INTO with your select statement. Also, the "AS" keyword following the CTE's name is not optional:

WITH tab AS (
    bla bla
INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (

Please note that the code assumes that the CTE will return exactly four fields and that those fields are matching in order and type with those specified in the INSERT statement. If that is not the case, just replace the "SELECT *" with a specific select of the fields that you require.

As for your question on using a function, I would say "it depends". If you are putting the data in a table just because of performance reasons, and the speed is acceptable when using it through a function, then I'd consider function to be an option. On the other hand, if you need to use the result of the CTE in several different queries, and speed is already an issue, I'd go for a table (either regular, or temp).

WITH common_table_expression (Transact-SQL)

What does (function($) {})(jQuery); mean?

Actually, this example helped me to understand what does (function($) {})(jQuery); mean.

Consider this:

// Clousure declaration (aka anonymous function)
var f = function(x) { return x*x; };
// And use of it
console.log( f(2) ); // Gives: 4

// An inline version (immediately invoked)
console.log( (function(x) { return x*x; })(2) ); // Gives: 4

And now consider this:

  • jQuery is a variable holding jQuery object.
  • $ is a variable name like any other (a, $b, a$b etc.) and it doesn't have any special meaning like in PHP.

Knowing that we can take another look at our example:

var $f = function($) { return $*$; };
var jQuery = 2;
console.log( $f(jQuery) ); // Gives: 4

// An inline version (immediately invoked)
console.log( (function($) { return $*$; })(jQuery) ); // Gives: 4

How can I get a JavaScript stack trace when I throw an exception?

You can access the stack (stacktrace in Opera) properties of an Error instance even if you threw it. The thing is, you need to make sure you use throw new Error(string) (don't forget the new instead of throw string.


try {
} catch (e) {
    var myStackTrace = e.stack || e.stacktrace || "";

Add Bean Programmatically to Spring Web App Context

In Spring 3.0 you can make your bean implement BeanDefinitionRegistryPostProcessor and add new beans via BeanDefinitionRegistry.

In previous versions of Spring you can do the same thing in BeanFactoryPostProcessor (though you need to cast BeanFactory to BeanDefinitionRegistry, which may fail).

Position a div container on the right side

Is this what you wanted? -

Floats on both sides now




<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>

plot is not defined

Change that import to

from matplotlib.pyplot import *

Note that this style of imports (from X import *) is generally discouraged. I would recommend using the following instead:

import matplotlib.pyplot as plt

How to convert webpage into PDF by using Python

You also can use pdfkit:


import pdfkit
pdfkit.from_url('', 'out.pdf')


MacOS: brew install Caskroom/cask/wkhtmltopdf

Debian/Ubuntu: apt-get install wkhtmltopdf

Windows: choco install wkhtmltopdf

See official documentation for MacOS/Ubuntu/other OS:

Can a website detect when you are using Selenium with chromedriver?

Obfuscating JavaScripts result

I have checked the chromedriver source code. That injects some javascript files to the browser.
Every javascript file on this link is injected to the web pages:

So I used reverse engineering and obfuscated the js files by Hex editing. Now i was sure that no more javascript variable, function names and fixed strings were used to uncover selenium activity. But still some sites and reCaptcha detect selenium!
Maybe they check the modifications that are caused by chromedriver js execution :)

Edit 1:

Chrome 'navigator' parameters modification

I discovered there are some parameters in 'navigator' that briefly uncover using of chromedriver. These are the parameters:

  • "navigator.webdriver" On non-automated mode it is 'undefined'. On automated mode it's 'true'.
  • "navigator.plugins" On headless chrome has 0 length. So I added some fake elements to fool the plugin length checking process.
  • "navigator.languages" was set to default chrome value '["en-US", "en", "es"]' .

So what i needed was a chrome extension to run javascript on the web pages. I made an extension with the js code provided in the article and used another article to add the zipped extension to my project. I have successfully changed the values; But still nothing changed!

I didn't find other variables like these but it doesn't mean that they don't exist. Still reCaptcha detects chromedriver, So there should be more variables to change. The next step should be reverse engineering of the detector services that i don't want to do.

Now I'm not sure does it worth to spend more time on this automation process or search for alternative methods!

How do I copy an object in Java?

Use a deep cloning utility:

SomeObjectType copy = new Cloner().deepClone(someObject);

This will deep copy any java object, check it out at

Replace Line Breaks in a String C#

if you want to "clean" the new lines, flamebaud comment using regex @"[\r\n]+" is the best choice.

using System;
using System.Text.RegularExpressions;

class MainClass {
  public static void Main (string[] args) {
    string str = "AAA\r\nBBB\r\n\r\n\r\nCCC\r\r\rDDD\n\n\nEEE";

    Console.WriteLine (str.Replace(System.Environment.NewLine, "-"));
    /* Result:

    Console.WriteLine (Regex.Replace(str, @"\r\n?|\n", "-"));
    // Result:
    // AAA-BBB---CCC---DDD---EEE

    Console.WriteLine (Regex.Replace(str, @"[\r\n]+", "-"));
    // Result:

include antiforgerytoken in ajax post ASP.NET MVC

In Asp.Net MVC when you use @Html.AntiForgeryToken() Razor creates a hidden input field with name __RequestVerificationToken to store tokens. If you want to write an AJAX implementation you have to fetch this token yourself and pass it as a parameter to the server so it can be validated.

Step 1: Get the token

var token = $('input[name="`__RequestVerificationToken`"]').val();

Step 2: Pass the token in the AJAX call

function registerStudent() {

var student = {     
    "FirstName": $('#fName').val(),
    "LastName": $('#lName').val(),
    "Email": $('#email').val(),
    "Phone": $('#phone').val(),

    url: '/Student/RegisterStudent',
    type: 'POST',
    data: { 
     student: student,
    dataType: 'JSON',
    contentType:'application/x-www-form-urlencoded; charset=utf-8',
    success: function (response) {
        if (response.result == "Success") {
            alert('Student Registered Succesfully!')

    error: function (x,h,r) {
        alert('Something went wrong')

Note: The content type should be 'application/x-www-form-urlencoded; charset=utf-8'

I have uploaded the project on Github; you can download and try it.

How do you redirect to a page using the POST verb?

try this one

return Content("<form action='actionname' id='frmTest' method='post'><input type='hidden' name='someValue' value='" + someValue + "' /><input type='hidden' name='anotherValue' value='" + anotherValue + "' /></form><script>document.getElementById('frmTest').submit();</script>");

In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?

1. Final • Final is used to apply restrictions on class, method and variable. • Final class can't be inherited, final method can't be overridden and final variable value can't be changed. • Final variables are initialized at the time of creation except in case of blank final variable which is initialized in Constructor. • Final is a keyword.

2. Finally • Finally is used for exception handling along with try and catch. • It will be executed whether exception is handled or not. • This block is used to close the resources like database connection, I/O resources. • Finally is a block.

3. Finalize • Finalize is called by Garbage collection thread just before collecting eligible objects to perform clean up processing. • This is the last chance for object to perform any clean-up but since it’s not guaranteed that whether finalize () will be called, its bad practice to keep resource till finalize call. • Finalize is a method.

Proper use cases for Android UserManager.isUserAGoat()?

Android R Update:

From Android R, this method always returns false. Google says that this is done "to protect goat privacy":

 * Used to determine whether the user making this call is subject to
 * teleportations.
 * <p>As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can
 * now automatically identify goats using advanced goat recognition technology.</p>
 * <p>As of {@link android.os.Build.VERSION_CODES#R}, this method always returns
 * {@code false} in order to protect goat privacy.</p>
 * @return Returns whether the user making this call is a goat.
public boolean isUserAGoat() {
    if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.R) {
        return false;
    return mContext.getPackageManager()

Previous answer:

From their source, the method used to return false until it was changed in API 21.

 * Used to determine whether the user making this call is subject to
 * teleportations.
 * @return whether the user making this call is a goat 
public boolean isUserAGoat() {
    return false;

It looks like the method has no real use for us as developers. Someone has previously stated that it might be an Easter egg.

In API 21 the implementation was changed to check if there is an installed app with the package com.coffeestainstudios.goatsimulator

 * Used to determine whether the user making this call is subject to
 * teleportations.
 * <p>As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can
 * now automatically identify goats using advanced goat recognition technology.</p>
 * @return Returns true if the user making this call is a goat.
public boolean isUserAGoat() {
    return mContext.getPackageManager()

Here is the source and the change.

Android get image from gallery into ImageView

Here is the code,which worked for me.

Button buttonLoadImage = (Button) findViewById(;
    buttonLoadImage.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent intent = new Intent(Intent.ACTION_PICK,
            intent.putExtra("crop", "true");
            intent.putExtra("scale", true);
            intent.putExtra("outputX", 256);
            intent.putExtra("outputY", 256);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, 1);}});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != RESULT_OK) {

        if (requestCode == RESULT_LOAD_IMAGE && data != null) {
            Uri imageUri = data.getData();
            imageView = (ImageView) findViewById(;

in Manifest file add

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

SQL Server SELECT into existing table

select *
into existing table database..existingtable
from database..othertables....

If you have used select * into tablename from other tablenames already, next time, to append, you say select * into existing table tablename from other tablenames

How can I add an image file into json object?

You're only adding the File object to the JSON object. The File object only contains meta information about the file: Path, name and so on.

You must load the image and read the bytes from it. Then put these bytes into the JSON object.

How to force open links in Chrome not download them?

To make certain file types OPEN on your computer, instead of Chrome Downloading...

You have to download the file type once, then right after that download, look at the status bar at the bottom of the browser. Click the arrow next to that file and choose "always open files of this type". DONE.

Now the file type will always OPEN using your default program.

To reset this feature, go to Settings / Advance Settings and under the "Download.." section, there's a button to reset 'all' Auto Downloads

Hope this helps.. :-)

Visual Instructions found here:

How to make a HTTP PUT request?

How to use PUT method using WebRequest.

    //JsonResultModel class
    public class JsonResultModel
       public string ErrorMessage { get; set; }
       public bool IsSuccess { get; set; }
       public string Results { get; set; }
    // HTTP_PUT Function
    public static JsonResultModel HTTP_PUT(string Url, string Data)
        JsonResultModel model = new JsonResultModel();
        string Out = String.Empty;
        string Error = String.Empty;
        System.Net.WebRequest req = System.Net.WebRequest.Create(Url);

            req.Method = "PUT";
            req.Timeout = 100000;
            req.ContentType = "application/json";
            byte[] sentData = Encoding.UTF8.GetBytes(Data);
            req.ContentLength = sentData.Length;

            using (System.IO.Stream sendStream = req.GetRequestStream())
                sendStream.Write(sentData, 0, sentData.Length);


            System.Net.WebResponse res = req.GetResponse();
            System.IO.Stream ReceiveStream = res.GetResponseStream();
            using (System.IO.StreamReader sr = new 
            System.IO.StreamReader(ReceiveStream, Encoding.UTF8))

                Char[] read = new Char[256];
                int count = sr.Read(read, 0, 256);

                while (count > 0)
                    String str = new String(read, 0, count);
                    Out += str;
                    count = sr.Read(read, 0, 256);
        catch (ArgumentException ex)
            Error = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
        catch (WebException ex)
            Error = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
        catch (Exception ex)
            Error = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);

        model.Results = Out;
        model.ErrorMessage = Error;
        if (!string.IsNullOrWhiteSpace(Out))
            model.IsSuccess = true;
        return model;

Calling a Javascript Function from Console

you can invoke it using window.function_name() or directly function_name()

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

In the SQL Server Management Studio, to find out details of the active transaction, execute following command

DBCC opentran()

You will get the detail of the active transaction, then from the SPID of the active transaction, get the detail about the SPID using following commands

exec sp_who2 <SPID>
exec sp_lock <SPID>

For example, if SPID is 69 then execute the command as

exec sp_who2 69
exec sp_lock 69

Now , you can kill that process using the following command


I hope this helps :)

Git adding files to repo

my problem (git on macOS) was solved by using sudo git instead of just git in all add and commit commands

Prevent RequireJS from Caching Required Scripts

Dynamic solution (without urlArgs)

There is a simple solution for this problem, so that you can load a unique revision number for every module.

You can save the original requirejs.load function, overwrite it with your own function and parse your modified url to the original requirejs.load again:

var load = requirejs.load;
requirejs.load = function (context, moduleId, url) {
    url += "?v=" + oRevision[moduleId];
    load(context, moduleId, url);

In our building process I used "gulp-rev" to build a manifest file with all revision of all modules which are beeing used. Simplified version of my gulp task:

gulp.task('gulp-revision', function() {
    var sManifestFileName = 'revision.js';

    return gulp.src(aGulpPaths)
        .pipe(rev.manifest(sManifestFileName, {
        transformer: {
            stringify: function(a) {
                var oAssetHashes = {};

                for(var k in a) {
                    var key = (k.substr(0, k.length - 3));

                    var sHash = a[k].substr(a[k].indexOf(".") - 10, 10);
                    oAssetHashes[key] = sHash;

                return "define([], function() { return " + JSON.stringify(oAssetHashes) + "; });"

this will generate an AMD-module with revision numbers to moduleNames, which is included as 'oRevision' in the main.js, where you overwrite the requirejs.load function as shown before.

How do I set the default value for an optional argument in Javascript?

You can also do this with ArgueJS:

function (){
  arguments = __({nodebox: undefined, str: [String: "hai"]})

  // and now on, you can access your arguments by
  //   arguments.nodebox and arguments.str

Split files using tar, gz, zip, or bzip2

use tar to split into multiple archives

there are plenty of programs that will work with tar files on windows, including cygwin.

Passing arrays as url parameter

in the received page you can use:

parse_str($str, $array); var_dump($array);

Remove tracking branches no longer on remote

May be this command is what you want.

After run:

git remote prune origin

then run:

diff <(git branch | sed -e 's/*/ /g') <(git branch -r | sed -e 's/origin\///g') | grep '^<'

this will show all branch which not in (git branch -r) but in (git branch)

This method have a problem, it will also show the branch in local which have not pushed before

Using column alias in WHERE clause of MySQL query produces an error

Standard SQL (or MySQL) does not permit the use of column aliases in a WHERE clause because

when the WHERE clause is evaluated, the column value may not yet have been determined.

(from MySQL documentation). What you can do is calculate the column value in the WHERE clause, save the value in a variable, and use it in the field list. For example you could do this:

SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,
@postcode AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
WHERE (@postcode := SUBSTRING(`locations`.`raw`,-6,4)) NOT IN
 SELECT `postcode` FROM `postcodes` WHERE `region` IN

This avoids repeating the expression when it grows complicated, making the code easier to maintain.

Easiest way to pass an AngularJS scope variable from directive to controller?

Wait until angular has evaluated the variable

I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "=" in the scope. Here's three solutions depending on your situation.

Solution #1

I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.

If your variable is changing, or is fetched through a request, you should use $observe or $watch:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // observe changes in attribute - could also be scope.$watch
            attrs.$observe('yourDirective', function (value) {
                if (value) {
                    // pass value to app controller
                    scope.variable = value;
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // observe changes in attribute - could also be scope.$watch
                $attrs.$observe('yourDirective', function (value) {
                    if (value) {
                        // pass value to app controller
                        $scope.variable = value;
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>

Note that you should not set the variable to "=" in the scope, if you are using the $observe function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn) (, or #3 if your variable is not changing).

Solution #2

If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout to wait until the $apply has run. Also we need to use $emit to send it to the parent scope app controller (due to the isolated scope in the directive):

app.directive('yourDirective', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        // NB: isolated scope!!
        scope: {
            yourDirective: '='
        link: function (scope, element, attrs) {
            // wait until after $apply
                // use scope.$emit to pass it to controller
                scope.$emit('notification', scope.yourDirective);
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: [ '$scope', function ($scope) {
            // wait until after $apply
                // use $scope.$emit to pass it to controller
                $scope.$emit('notification', scope.yourDirective);
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$on('notification', function (evt, value) {
        $scope.variable = value;

And here's the html (no brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="someObject.someVariable"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>

Solution #3

If your variable is not changing and you need to evaluate it in your directive, you can use the $eval function:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // executes the expression on the current scope returning the result
            // and adds it to the scope
            scope.variable = scope.$eval(attrs.yourDirective);

        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // executes the expression on the current scope returning the result
                // and adds it to the scope
                scope.variable = scope.$eval($attrs.yourDirective);
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>

Also, have a look at this answer:

Reference for FOUC (flash of unstyled content) issue:

For the interested: here's an article on the angular life cycle

Checking the form field values before submitting that page

Don't know for sure, but it sounds like it is still submitting. I quick solution would be to change your (guessing at your code here):

<input type="submit" value="Submit" onclick="checkform()">

to a button:

<input type="button" value="Submit" onclick="checkform()">

That way your form still gets submitted (from the else part of your checkform()) and it shouldn't be reloading the page.

There are other, perhaps better, ways of handling it but this works in the mean time.

Adding a simple UIAlertView

UIAlertView *alert = [[UIAlertView alloc]
 delegate:nil //or self

 [alert show];
 [alert autorelease];

moment.js, how to get day of week number

If you are specifically looking for the 1-7 approach...

This is the ISO weekday number. moment.js has also taken this into account. Use isoWeekday()

console.log(moment().isoWeekday()); // returns 1-7 where 1 is Monday and 7 is Sunday
<script src=""></script>

Seeing as I wrote this answer on a Tuesday, today this gives me a 2.

How do you create a hidden div that doesn't create a line break or horizontal space?

Since you should focus on usability and generalities in CSS, rather than use an id to point to a specific layout element (which results in huge or multiple css files) you should probably instead use a true class in your linked .css file:

.hidden {
visibility: hidden;
display: none;

or for the minimalist:

.hidden {
display: none;

Now you can simply apply it via:

<div class="hidden"> content </div>

load json into variable

code bit should read:

var my_json;
$.getJSON(my_url, function(json) {
  my_json = json;

How to do ToString for a possibly null object?

string.Format("{0}", myObj);

string.Format will format null as an empty string and call ToString() on non-null objects. As I understand it, this is what you were looking for.

Python 2.7 getting user input and manipulating as string without quotations

We can use the raw_input() function in Python 2 and the input() function in Python 3. By default the input function takes an input in string format. For other data type you have to cast the user input.

In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting

x = raw_input("Enter a number: ") #String input

x = int(raw_input("Enter a number: ")) #integer input

x = float(raw_input("Enter a float number: ")) #float input

x = eval(raw_input("Enter a float number: ")) #eval input

In Python 3 we use the input() function which returns a user input value.

x = input("Enter a number: ") #String input

If you enter a string, int, float, eval it will take as string input

x = int(input("Enter a number: ")) #integer input

If you enter a string for int cast ValueError: invalid literal for int() with base 10:

x = float(input("Enter a float number: ")) #float input

If you enter a string for float cast ValueError: could not convert string to float

x = eval(input("Enter a float number: ")) #eval input

If you enter a string for eval cast NameError: name ' ' is not defined Those error also applicable for Python 2.

How do I pass a value from a child back to the parent form?

I think the easiest way is to use the Tag property in your FormOptions class set the Tag = value you need to pass and after the ShowDialog method read it as

myvalue x=(myvalue)formoptions.Tag;

How to declare a constant in Java

  1. You can use an enum type in Java 5 and onwards for the purpose you have described. It is type safe.
  2. A is an instance variable. (If it has the static modifier, then it becomes a static variable.) Constants just means the value doesn't change.
  3. Instance variables are data members belonging to the object and not the class. Instance variable = Instance field.

If you are talking about the difference between instance variable and class variable, instance variable exist per object created. While class variable has only one copy per class loader regardless of the number of objects created.

Java 5 and up enum type

public enum Color{
 RED("Red"), GREEN("Green");

 private Color(String color){
    this.color = color;

  private String color;

  public String getColor(){
    return this.color;

  public String toString(){
    return this.color;

If you wish to change the value of the enum you have created, provide a mutator method.

public enum Color{
 RED("Red"), GREEN("Green");

 private Color(String color){
    this.color = color;

  private String color;

  public String getColor(){
    return this.color;

  public void setColor(String color){
    this.color = color;

  public String toString(){
    return this.color;

Example of accessing:

public static void main(String args[]){

  // or


CSS hexadecimal RGBA?

I found the answer after posting the enhancement to the question. Sorry!

MS Excel helped!

simply add the Hex prefix to the hex colour value to add an alpha that has the equivalent opacity as the % value.

(in rbga the percentage opacity is expressed as a decimal as mentioned above)

Opacity %   255 Step        2 digit HEX prefix
0%          0.00            00
5%          12.75           0C
10%         25.50           19
15%         38.25           26
20%         51.00           33
25%         63.75           3F
30%         76.50           4C
35%         89.25           59
40%         102.00          66
45%         114.75          72
50%         127.50          7F
55%         140.25          8C
60%         153.00          99
65%         165.75          A5
70%         178.50          B2
75%         191.25          BF
80%         204.00          CC
85%         216.75          D8
90%         229.50          E5
95%         242.25          F2
100%        255.00          FF

C# version of java's synchronized keyword?

static object Lock = new object();

lock (Lock) 
// do stuff

PHP: Count a stdClass object

The object doesn't have 30 properties. It has one, which is an array that has 30 elements. You need the number of elements in that array.

Extracting the last n characters from a string in R

I used the following code to get the last character of a string.

    substr(output, nchar(stringOfInterest), nchar(stringOfInterest))

You can play with the nchar(stringOfInterest) to figure out how to get last few characters.

Reverse of JSON.stringify?

how about this partial solution?

I wanna store (using a Config node) a global bigobj, with data + methods (as an alternative to importing an external library), used in many function nodes on my flow:

Strange but it works: The global variable 'bigobj':

some[]more[]{dx:"here"} , // array of objects with  array of objects. The 'Config' node requires JSON.
 "get_dx": "function( d,p) {  return this.some[d].more[p].dx; }"  // test function

i.e. a JSON version of a function.... (all in one line :( )

USE: Inside a function node:

var bigO = global.get("bigobj");

function callJSONMethod(obj, fname, a, b, c, d){
    // see:
var wrap = s => "{ return " + obj[fname] + " };" //return the block having function expression
var func = new Function(wrap(obj[fname]));
return null ).call( obj, a, b, c, d); //invoke the function using arguments

msg.payload =callJSONMethod(bigO, "get_dx", 2, 2); 
return msg:

returns "here", unbelieve!

i.e I must add the function callJSONMethod() to any function block using bigobj..... maybe acceptable.

Best regards

Which keycode for escape key with jQuery

I have always used keyup and e.which to catch escape key.

Can't import javax.servlet.annotation.WebServlet

Simply add the below to your maven project pom.xml flie:


How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

Check if a string contains a string in C++

Use std::string::find as follows:

if (s1.find(s2) != std::string::npos) {
    std::cout << "found!" << '\n';

Note: "found!" will be printed if s2 is a substring of s1, both s1 and s2 are of type std::string.

Controlling mouse with Python

Another alternative would be mouse library, I personally use it as it is relatively simple and cross-platform.

Here is how you can use it:

import mouse
# move 100 right and 100 down with a duration of 0.5 seconds
mouse.move(100, 100, absolute=False, duration=0.5)
# left click'left')
# right click'right')

Here is the source: How to Control your Mouse in Python

How to capture the browser window close event?

Maybe just unbind the beforeunload event handler within the form's submit event handler:

jQuery('form').submit(function() {

Best practices for Storyboard login screen, handling clearing of data upon logout

EDIT: Add logout action.

enter image description here

1. First of all prepare the app delegate file


#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (nonatomic) BOOL authenticated;



#import "AppDelegate.h"
#import "User.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    User *userObj = [[User alloc] init];
    self.authenticated = [userObj userAuthenticated];

    return YES;

2. Create a class named User.


#import <Foundation/Foundation.h>

@interface User : NSObject

- (void)loginWithUsername:(NSString *)username andPassword:(NSString *)password;
- (void)logout;
- (BOOL)userAuthenticated;



#import "User.h"

@implementation User

- (void)loginWithUsername:(NSString *)username andPassword:(NSString *)password{

    // Validate user here with your implementation
    // and notify the root controller
    [[NSNotificationCenter defaultCenter] postNotificationName:@"loginActionFinished" object:self userInfo:nil];

- (void)logout{
    // Here you can delete the account

- (BOOL)userAuthenticated {

    // This variable is only for testing
    // Here you have to implement a mechanism to manipulate this
    BOOL auth = NO;

    if (auth) {
        return YES;

    return NO;

3. Create a new controller RootViewController and connected with the first view, where login button live. Add also a Storyboard ID: "initialView".


#import <UIKit/UIKit.h>
#import "LoginViewController.h"

@protocol LoginViewProtocol <NSObject>

- (void)dismissAndLoginView;


@interface RootViewController : UIViewController

@property (nonatomic, weak) id <LoginViewProtocol> delegate;
@property (nonatomic, retain) LoginViewController *loginView;



#import "RootViewController.h"

@interface RootViewController ()


@implementation RootViewController

@synthesize loginView;

- (void)viewDidLoad
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

- (void)didReceiveMemoryWarning
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.

- (IBAction)loginBtnPressed:(id)sender {

    [[NSNotificationCenter defaultCenter] addObserver:self


#pragma mark - Dismissing Delegate Methods

-(void) loginActionFinished:(NSNotification*)notification {

    AppDelegate *authObj = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    authObj.authenticated = YES;

    [self dismissLoginAndShowProfile];

- (void)dismissLoginAndShowProfile {
    [self dismissViewControllerAnimated:NO completion:^{
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UITabBarController *tabView = [storyboard instantiateViewControllerWithIdentifier:@"profileView"];
        [self presentViewController:tabView animated:YES completion:nil];



4. Create a new controller LoginViewController and connected with the login view.


#import <UIKit/UIKit.h>
#import "User.h"

@interface LoginViewController : UIViewController


#import "LoginViewController.h"
#import "AppDelegate.h"

- (void)viewDidLoad
    [super viewDidLoad];

- (IBAction)submitBtnPressed:(id)sender {
    User *userObj = [[User alloc] init];

    // Here you can get the data from login form
    // and proceed to authenticate process
    NSString *username = @"username retrieved through login form";
    NSString *password = @"password retrieved through login form";
    [userObj loginWithUsername:username andPassword:password];


5. At the end add a new controller ProfileViewController and connected with the profile view in the tabViewController.


#import <UIKit/UIKit.h>

@interface ProfileViewController : UIViewController



#import "ProfileViewController.h"
#import "RootViewController.h"
#import "AppDelegate.h"
#import "User.h"

@interface ProfileViewController ()


@implementation ProfileViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    return self;

- (void)viewDidLoad
    [super viewDidLoad];


- (void) viewWillAppear:(BOOL)animated
    [super viewWillAppear:animated];

    if(![(AppDelegate*)[[UIApplication sharedApplication] delegate] authenticated]) {

        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

        RootViewController *initView =  (RootViewController*)[storyboard instantiateViewControllerWithIdentifier:@"initialView"];
        [initView setModalPresentationStyle:UIModalPresentationFullScreen];
        [self presentViewController:initView animated:NO completion:nil];
    } else{
        // proceed with the profile view

- (void)didReceiveMemoryWarning
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.

- (IBAction)logoutAction:(id)sender {

   User *userObj = [[User alloc] init];
   [userObj logout];

   AppDelegate *authObj = (AppDelegate*)[[UIApplication sharedApplication] delegate];
   authObj.authenticated = NO;

   UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

   RootViewController *initView =  (RootViewController*)[storyboard instantiateViewControllerWithIdentifier:@"initialView"];
   [initView setModalPresentationStyle:UIModalPresentationFullScreen];
   [self presentViewController:initView animated:NO completion:nil];



LoginExample is a sample project for extra help.

ASP.NET Identity reset password


This was the original answer. It does work, but has a problem. What if AddPassword fails? The user is left without a password.

The original answer: we can use three lines of code:

UserManager<IdentityUser> userManager = 
    new UserManager<IdentityUser>(new UserStore<IdentityUser>());


userManager.AddPassword(userId, newPassword);

See also:

Now Recommended

It's probably better to use the answer that EdwardBrey proposed and then DanielWright later elaborated with a code sample.

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

You can try this:

Select To_date ('15/2/2007 00:00:00', 'DD/MM/YYYY HH24:MI:SS'),
       To_date ('28/2/2007 10:12', 'DD/MM/YYYY HH24:MI:SS')
  From DUAL;


PHP calculate age

  function dob ($birthday){
    list($day,$month,$year) = explode("/",$birthday);
    $year_diff  = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff   = date("d") - $day;
    if ($day_diff < 0 || $month_diff < 0)
    return $year_diff;

How to check file MIME type with javascript before upload?

This is what you have to do

var fileVariable =document.getElementsById('fileId').files[0];

If you want to check for image file types then

 alert('its an image');

Triggering a checkbox value changed event in DataGridView

Working with an unbound control (ie I manage the content programmatically), without the EndEdit() it only called the CurrentCellDirtyStateChanged once and then never again; but I found that with the EndEdit() CurrentCellDirtyStateChanged was called twice (the second probably caused by the EndEdit() but I didn't check), so I did the following, which worked best for me:

    bool myGridView_DoCheck = false;
    private void myGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        if (!myGridView_DoCheck)
            myGridView_DoCheck = true;
            // do something here
            myGridView_DoCheck = false;

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Host", "");
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.flush ();
printout.close ();

The rest of the thing you can do it.

Singular matrix issue with Numpy

The matrix you pasted

[[   1,    8,   50],
 [   8,   64,  400],
 [  50,  400, 2500]]

Has a determinant of zero. This is the definition of a Singular matrix (one for which an inverse does not exist)

How to convert a pymongo.cursor.Cursor into a dict?

I suggest create a list and append dictionary into it.

x   = []
cur = db.dbname.find()
for i in cur:

Now x is a list of dictionary, you can manipulate the same in usual python way.

How to subtract days from a plain Date?

Without using the second variable, you can replace 7 for with your back x days:

let d=new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000))

Specify sudo password for Ansible

Above solution by @toast38coza worked for me; just that sudo: yes is deprecated in Ansible now. Use become and become_user instead.

 - name: Restart apache service
   service: name=apache2 state=restarted
   become: yes
   become_user: root

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host


Though the conclusion is correct, the identification of the problem is better described here

How do I launch the Android emulator from the command line?

For one-click (BATCH file) launch, this is what I've done:

  • got the name of AVD from Android Studio -> Tools -> AVD Manager -> Click on Arrow Down and choose View Details ( for me it's Pixel_2_API_28, so change accordingly below)
  • create an start.bat file and put the following inside:
 cd C:\Program Files (x86)\Android\android-sdk\emulator\ 
 emulator -avd Pixel_2_API_28


  • First line: for me was necessary because I am launching it from d:
  • Second line: for me was not working the tools\emulator
  • Third line: make sure you change the name of the AVD with yours (here Pixel_2_API_28)


  • launch start.bat from command line

How to change active class while click to another link in bootstrap use jquery?

I had the same issue before. Try this answer here, it works on my site.

  var current_page_URL = location.href;
  $( "a" ).each(function() {
     if ($(this).attr("href") !== "#") {
       var target_URL = $(this).prop("href");
       if (target_URL == current_page_URL) {
          $('nav a').parents('li, ul').removeClass('active');
          return false;

Source: It was original posted here how to set active class to nav menu from twitter bootstrap

check if command was successful in a batch file

I don't know if javaw will write to the %errorlevel% variable, but it might.

echo %errorlevel% after you run it directly to see.

Other than that, you can pipe the output of javaw to a file, then use find to see what the results were. Without knowing the output of it, I can't really help you with that.

Thymeleaf using path variables to th:href

try this one is a very easy method if you are in list of model foreach (var item in Modal) loop




Exit single-user mode

Not sure if this helps anyone, but I had the same issue and could not find the process that was holding me up. I closed SSMS and stopped all the services hitting the local instance. Then once I went back in and ran the exec sp_who2, it showed me the culprit. I killed the process and was able to get the Multi_User to work, then restart the services. We had IIS hitting it every few minutes/seconds looking for certain packages.

How to reset a select element with jQuery

I believe:

$("select option:first-child").attr("selected", "selected");

Excel VBA - read cell value from code

I think you need this ..

Dim n as Integer   

For n = 5 to 17
  msgbox cells(n,3) '--> sched waste
  msgbox cells(n,4) '--> type of treatm
  msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
  msgbox cells(n,6) '--> email col

How to check if datetime happens to be Saturday or Sunday in SQL Server 2008

Many ways to do this, you can use DATENAME and check for the actual strings 'Saturday' or 'Sunday'


Or use the day of the week and check for 1 (Sunday) or 7 (Saturday)


How to set the context path of a web application in Tomcat 7.0

This little code worked for me, using virtual hosts

<Host name="" >
   <Context path="" docBase="/path/to/myapp.war"/>

Make a phone call programmatically

In Swift 3.0,

static func callToNumber(number:String) {

        let phoneFallback = "telprompt://\(number)"
        let fallbackURl = URL(string:phoneFallback)!

        let phone = "tel://\(number)"
        let url = URL(string:phone)!

        let shared = UIApplication.shared

        }else if (shared.canOpenURL(url)){
            print("unable to open url for call")


How to pass ArrayList<CustomeObject> from one activity to another?

Use this code to pass arraylist<customobj> to anthother Activity

firstly serialize our contact bean

public class ContactBean implements Serializable {
      //do intialization here

Now pass your arraylist

 Intent intent = new Intent(this,name of activity.class);

How to set java_home on Windows 7?

Run Eclipse as Administrator.

That solved my problem. I'm still digging for the logic behind it.

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

Use these following commands, this will solve the error:

sudo apt-get install postgresql

then fire:

sudo apt-get install python-psycopg2

and last:

sudo apt-get install libpq-dev

Creating CSS Global Variables : Stylesheet theme management

Latest Update: 16/01/2020

CSS Custom Properties (Variables) have arrived!

It's 2020 and time to officially roll out this feature in your new applications.

Preprocessor "NOT" required!

There is a lot of repetition in CSS. A single color may be used in several places.

For some CSS declarations, it is possible to declare this higher in the cascade and let CSS inheritance solve this problem naturally.

For non-trivial projects, this is not always possible. By declaring a variable on the :root pseudo-element, a CSS author can halt some instances of repetition by using the variable.

How it works

Set your variable at the top of your stylesheet:


Create a root class:

:root {

Create variables (-- [String] : [value])

:root {
  --red: #b00;
  --blue: #00b;
  --fullwidth: 100%;

Set your variables anywhere in your CSS document:

h1 {
  color: var(--red);
#MyText {
  color: var(--blue);
  width: var(--fullwidth);


See for current compatability.

![supported browsers

Firefox: Version 31+ (Enabled by default)

Supported since 2014 (Leading the way as usual.)

More info from Mozilla

Chrome: Version 49+ (Enabled by default).

Supported since 2016

Safari/IOS Safari: Version 9.1/9.3 (Enabled by default).

Supported since 2016

Opera: Version 39+ (Enabled by default).

Supported since 2016

Android: Version 52+ (Enabled by default).

Supported since 2016

Edge: Version 15+ (Enabled by default).

Supported since 2017

CSS Custom Properties landed in Windows Insider Preview build 14986

IE: When pigs fly.

It's time to finally let this ship sink. No one enjoyed riding her anyway. ?


Full specification for upcoming CSS variables

Read more


A fiddle and snippet are attached below for testing:

(It will only work with supported browsers.)


:root {
  --red: #b00;
  --blue: #4679bd;
  --grey: #ddd;
  --W200: 200px;
  --Lft: left;
.Bx4 {
  float: var(--Lft);
  width: var(--W200);
  height: var(--W200);
  margin: 10px;
  padding: 10px;
  border: 1px solid var(--red);
.Bx1 {
  color: var(--red);
  background: var(--grey);
.Bx2 {
  color: var(--grey);
  background: black;
.Bx3 {
  color: var(--grey);
  background: var(--blue);
.Bx4 {
  color: var(--grey);
  background: var(--red);
<p>If you see four square boxes then variables are working as expected.</p>

<div class="Bx1">I should be red text on grey background.</div>
<div class="Bx2">I should be grey text on black background.</div>
<div class="Bx3">I should be grey text on blue background.</div>
<div class="Bx4">I should be grey text on red background.</div>

What are .iml files in Android Studio?

Add .idea and *.iml to .gitignore, you don't need those files to successfully import and compile the project.

Parse rfc3339 date strings in Python?

You should have a look at moment which is a python port of the excellent js lib momentjs.

One advantage of it is the support of ISO 8601 strings formats, as well as a generic "% format" :

import moment

m =, '%Y-%m-%dT%H:%M:%SZ')
print m.format('YYYY-M-D H:M')
print m.weekday


2012-10-09 19:10

How to print third column to last column?

awk '{for(i=3;i<=NF;++i)print $i}' 

How to send POST request?

Your data dictionary conteines names of form input fields, you just keep on right their values to find results. form view Header configures browser to retrieve type of data you declare. With requests library it's easy to send POST:

import requests

url = ""
data = {'@number': 12524, '@type': 'issue', '@action': 'show'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept":"text/plain"}
response =, data=data, headers=headers)


More about Request object:

How to rename with prefix/suffix?

I know there is great answers here but I found no reference to handle filename extensions when adding suffix.

I needed to add '_en' suffix to all wav files in a folder before the file extension.

The magic is here: %.*

for filename in *.wav; do mv $filename ${filename%.*}_en.wav; done;

If you need to handle different file extensions, check this answer. A bit less intuitive.

How can I get the last character in a string?

Use the charAt method. This function accepts one argument: The index of the character.

var lastCHar = myString.charAt(myString.length-1);

How to view/delete local storage in Firefox?

As 'localStorage' is just another object, you can: create, view, and edit it in the 'Console'. Simply enter 'localStorage' as a command and press enter, it'll display a string containing the key-value pairs of localStorage (Tip: Click on that string for formatted output, i.e. to display each key-value pair in each line).

Best way to check if an PowerShell Object exist?

I had the same Problem. This solution works for me.

$Word = $null
$Word = [System.Runtime.InteropServices.Marshal]::GetActiveObject('word.application')
if ($Word -eq $null)
    $Word = new-object -ComObject word.application

bool to int conversion

There seems to be no problem since the int to bool cast is done implicitly. This works in Microsoft Visual C++, GCC and Intel C++ compiler. No problem in either C or C++.

Measuring function execution time in R

As Andrie said, system.time() works fine. For short function I prefer to put replicate() in it:

system.time( replicate(10000, myfunction(with,arguments) ) )

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

Online PHP syntax checker / validator

To expand on my comment.

You can validate on the command line using php -l [filename], which does a syntax check only (lint). This will depend on your php.ini error settings, so you can edit you php.ini or set the error_reporting in the script.

Here's an example of the output when run on a file containing:

echo no quotes or semicolon

Results in:

PHP Parse error:  syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2

Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2

Errors parsing badfile.php

I suggested you build your own validator.

A simple page that allows you to upload a php file. It takes the uploaded file runs it through php -l and echos the output.

Note: this is not a security risk it does not execute the file, just checks for syntax errors.

Here's a really basic example of creating your own:

if (isset($_FILES['file'])) {
    echo '<pre>';
    passthru('php -l '.$_FILES['file']['tmp_name']);
    echo '</pre>';
<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit"/>

Swift - How to convert String to Double

What also works:

// Init default Double variable
var scanned: Double()

let scanner = NSScanner(string: "String to Scan")

// scanned has now the scanned value if something was found.

How to retrieve unique count of a field using Kibana + Elastic Search

Unique counts of field values are achieved by using facets. See ES documentation for the full story, but the gist is that you will create a query and then ask ES to prepare facets on the results for counting values found in fields. It's up to you to customize the fields used and even describe how you want the values returned. The most basic of facet types is just to group by terms, which would be like an IP address above. You can get pretty complex with these, even requiring a query within your facet!

    "query": {
        "match_all": {}
    "facets": {
        "terms": {
            "field": "ip_address"

AngularJs: How to set radio button checked based on model

Just do something like this,<input type="radio" ng-disabled="loading" name="dateRange" ng-model="filter.DateRange" value="1" ng-checked="(filter.DateRange == 1)"/>

TSQL select into Temp table from dynamic sql

How I did it with a pivot in dynamic sql (#AccPurch was created prior to this)

DECLARE @sql AS nvarchar(MAX)
declare @Month Nvarchar(1000)

--DROP TABLE #temp
select distinct YYYYMM into #temp from #AccPurch AS ap
SELECT  @Month = COALESCE(@Month, '') + '[' + CAST(YYYYMM AS VarChar(8)) + '],' FROM    #temp

SELECT   @Month= LEFT(@Month,len(@Month)-1)

SET @sql = N'SELECT UserID, '+ @Month + N' into ##final_Donovan_12345 FROM (
Select ap.AccPurch ,
       ap.YYYYMM ,
       ap.UserID ,
FROM #AccPurch AS ap 
) p
Pivot (SUM(AccPurch) FOR YYYYMM IN ('+@Month+ N')) as pvt'

EXEC sp_executesql @sql

Select * INTO #final From ##final_Donovan_12345

DROP TABLE  ##final_Donovan_12345

Select * From #final AS f

Sublime Text 2 Code Formatting

Maybe this answer is not quite what you're looking for, but it will fomat any language with the same keyboard shortcut. The solution are language specific keyboard shortcuts.

For every language you want to format, you must find and download a plugin for that, for example a html formatter and a C# formatter. And then you map the command for every plugin to the same key, but with a differnt context (see the link).


Plotting power spectrum in python

Numpy has a convenience function, np.fft.fftfreq to compute the frequencies associated with FFT components:

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(301) - 0.5
ps = np.abs(np.fft.fft(data))**2

time_step = 1 / 30
freqs = np.fft.fftfreq(data.size, time_step)
idx = np.argsort(freqs)

plt.plot(freqs[idx], ps[idx])

enter image description here

Note that the largest frequency you see in your case is not 30 Hz, but

In [7]: max(freqs)
Out[7]: 14.950166112956811

You never see the sampling frequency in a power spectrum. If you had had an even number of samples, then you would have reached the Nyquist frequency, 15 Hz in your case (although numpy would have calculated it as -15).

JavaScript single line 'if' statement - best syntax, this alternative?

can use this,

lemons ? alert("please give me a lemonade") : alert("then give me a beer");

explanation: if lemons is true then alert("please give me a lemonade"), if not, alert("then give me a beer")

Git push won't do anything (everything up-to-date)

This happened to me when my SourceTree application crashed during staging. And on the command line, it seemed like the previous git add had been corrupted. If this is the case, try:

git init
git add -A
git commit -m 'Fix bad repo'
git push

On the last command, you might need to set the branch.

git push --all origin master

Bear in mind that this is enough if you haven't done any branching or any of that sort. In that case, make sure you push to the correct branch like git push origin develop.

Angularjs prevent form submission when input validation fails

Just to add to the answers above,

I was having a 2 regular buttons as shown below. (No type="submit"anywhere)

<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>

No matter how much i tried, pressing enter once the form was valid, the "Clear Form" button was called, clearing the entire form.

As a workaround,

I had to add a dummy submit button which was disabled and hidden. And This dummy button had to be on top of all the other buttons as shown below.

<button type="submit" ng-hide="true" ng-disabled="true">Dummy</button>

<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>

<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>

Well, my intention was never to submit on Enter, so the above given hack just works fine.

How to hide soft keyboard on android after clicking outside EditText?

You may easily override the onKey() event in activity and fragments to hide the keyboard.

public boolean onKey(View v, int keyCode, KeyEvent event) {

    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        if (keyCode == event.KEYCODE_ENTER) {

            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    .getWindowToken(), 0);

            return true;
    return false;

Using Gulp to Concatenate and Uglify files

Solution using gulp-uglify, gulp-concat and gulp-sourcemaps. This is from a project I'm working on.

gulp.task('scripts', function () {
    return gulp.src(scripts, {base: '.'})
            loadMaps: false,
            debug: debug,
        .pipe(gulpif(debug, wrapper({
            header: fileHeader,
        .pipe(concat('all_the_things.js', {
            newLine:'\n;' // the newline is needed in case the file ends with a line comment, the semi-colon is needed if the last statement wasn't terminated
            output: { //
                beautify: debug,
                comments: debug ? true : /^!|\b(copyright|license)\b|@(preserve|license|cc_on)\b/i,
            compress: { //,
                sequences: !debug,
                booleans: !debug,
                conditionals: !debug,
                hoist_funs: false,
                hoist_vars: debug,
                warnings: debug,
            mangle: !debug,
            outSourceMap: true,
            basePath: 'www',
            sourceRoot: '/'
        .pipe(sourcemaps.write('.', {
            includeContent: true,
            sourceRoot: '/',

This combines and compresses all your scripts, puts them into a file called all_the_things.js. The file will end with a special line


Which tells your browser to look for that map file, which it also writes out.

Invalid Host Header when ngrok tries to connect to React dev server

I used this set up in a react app that works. I created a config file named configstrp.js that contains the following:

module.exports = {
ngrok: {
// use the local frontend port to connect
enabled: process.env.NODE_ENV !== 'production',
port: process.env.PORT || 3000,
subdomain: process.env.NGROK_SUBDOMAIN,
authtoken: process.env.NGROK_AUTHTOKEN
},   }

Require the file in the server.

const configstrp      = require('./config/configstrp.js');
const ngrok = configstrp.ngrok.enabled ? require('ngrok') : null;

and connect as such

if (ngrok) {
console.log('If nGronk')
    addr: configstrp.ngrok.port,
    subdomain: configstrp.ngrok.subdomain,
    authtoken: configstrp.ngrok.authtoken,
  (err, url) => {
    if (err) {

    } else {


Do not pass a subdomain if you do not have a custom domain

How to make connection to Postgres via Node.js

Here is an example I used to connect node.js to my Postgres database.

The interface in node.js that I used can be found here

var pg = require('pg');
var conString = "postgres://YourUserName:YourPassword@localhost:5432/YourDatabase";

var client = new pg.Client(conString);

//queries are queued and executed one after another once the connection becomes available
var x = 1000;

while (x > 0) {
    client.query("INSERT INTO junk(name, a_number) values('Ted',12)");
    client.query("INSERT INTO junk(name, a_number) values($1, $2)", ['John', x]);
    x = x - 1;

var query = client.query("SELECT * FROM junk");
//fired after last row is emitted

query.on('row', function(row) {

query.on('end', function() {

//queries can be executed either via text/parameter values passed as individual arguments
//or by passing an options object containing text, (optional) parameter values, and (optional) query name
    name: 'insert beatle',
    text: "INSERT INTO beatles(name, height, birthday) values($1, $2, $3)",
    values: ['George', 70, new Date(1946, 02, 14)]

//subsequent queries with the same name will be executed without re-parsing the query plan by postgres
    name: 'insert beatle',
    values: ['Paul', 63, new Date(1945, 04, 03)]
var query = client.query("SELECT * FROM beatles WHERE name = $1", ['john']);

//can stream row results back 1 at a time
query.on('row', function(row) {
    console.log("Beatle name: %s",; //Beatle name: John
    console.log("Beatle birth year: %d", row.birthday.getYear()); //dates are returned as javascript dates
    console.log("Beatle height: %d' %d\"", Math.floor(row.height / 12), row.height % 12); //integers are returned as javascript ints

//fired after last row is emitted
query.on('end', function() {

UPDATE:- THE query.on function is now deprecated and hence the above code will not work as intended. As a solution for this look at:- query.on is not a function

VBA Date as integer

Just use CLng(Date).

Note that you need to use Long not Integer for this as the value for the current date is > 32767

Sieve of Eratosthenes - Finding Primes Python

import math
def sieve(n):
    primes = [True]*n
    primes[0] = False
    primes[1] = False
    for i in range(2,int(math.sqrt(n))+1):
            j = i*i
            while j < n:
                    primes[j] = False
                    j = j+i
    return [x for x in range(n) if primes[x] == True]

Copying files from one directory to another in Java

The example below from Java Tips is rather straight forward. I have since switched to Groovy for operations dealing with the file system - much easier and elegant. But here is the Java Tips one I used in the past. It lacks the robust exception handling that is required to make it fool-proof.

 public void copyDirectory(File sourceLocation , File targetLocation)
    throws IOException {

        if (sourceLocation.isDirectory()) {
            if (!targetLocation.exists()) {

            String[] children = sourceLocation.list();
            for (int i=0; i<children.length; i++) {
                copyDirectory(new File(sourceLocation, children[i]),
                        new File(targetLocation, children[i]));
        } else {

            InputStream in = new FileInputStream(sourceLocation);
            OutputStream out = new FileOutputStream(targetLocation);

            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;
            while ((len = > 0) {
                out.write(buf, 0, len);

Spring JPA selecting specific columns

In my case i created a separate entity class without the fields that are not required (only with the fields that are required).

Map the entity to the same table. Now when all the columns are required i use the old entity, when only some columns are required, i use the lite entity.


@Table(name = "user")
Class User{
         @Column(name = "id", unique=true, nullable=false)
         int id;
         @Column(name = "name", nullable=false)
         String name;
         @Column(name = "address", nullable=false)
         Address address;

You can create something like :

@Table(name = "user")
Class UserLite{
         @Column(name = "id", unique=true, nullable=false)
         int id;
         @Column(name = "name", nullable=false)
         String name;

This works when you know the columns to fetch (and this is not going to change).

won't work if you need to dynamically decide the columns.

Find length (size) of an array in jquery


$.each(obj, function (key, value) {
    console.log(key+ ' : ' + value); //push the object value

for (var i in obj) {
    nameList += "" + obj[i] + "";//display the object value

$("id/class").html($(nameList).length);//display the length of object.

Scroll to bottom of div with Vue.js

I tried the accepted solution and it didn't work for me. I use the browser debugger and found out the actual height that should be used is the clientHeight BUT you have to put this into the updated() hook for the whole solution to work.

return {
  conversation: [
 EventBus.$on('msg-ctr--push-msg-in-conversation', textMsg => {
  // Didn't work doing scroll here
updated(){              <=== PUT IT HERE !!
  var elem = this.$el
  elem.scrollTop = elem.clientHeight;

Converting newline formatting from Mac to Windows

Here's a really simple approach, worked well for me, courtesy Davy Schmeits's Weblog:

cat foo | col -b > foo2

Where foo is the file that has the Control+M characters at the end of the line, and foo2 the new file you are creating.