Programs & Examples On #Editortemplates

Html attributes for EditorFor() in ASP.NET MVC

Update MVC 5.1 now supports the below approach directly, so it works for built in editor too. (It's either a case of Great mind thinking alike or they read my answer :)

End Update

If your using your own editor template or with MVC 5.1 which now supports the below approach directly for built in editors.

@Html.EditorFor(modelItem => item.YourProperty, 
  new { htmlAttributes = new { @class="verificationStatusSelect", style = "Width:50px"  } })

then in your template (not required for simple types in MVC 5.1)

@Html.TextBoxFor(m => m, ViewData["htmlAttributes"])

How to convert JSON string into List of Java object?

You are asking Jackson to parse a StudentList. Tell it to parse a List (of students) instead. Since List is generic you will typically use a TypeReference

List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});

Get the last non-empty cell in a column in Google Sheets

To find the last non-empty cell you can use INDEX and MATCH functions like this:

=DAYS360(A2; INDEX(A:A; MATCH(99^99;A:A; 1)))

I think this is a little bit faster and easier.

Turn off warnings and errors on PHP and MySQL

PHP error_reporting reference:

// Turn off all error reporting

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

// Report all PHP errors (see changelog)

// Report all PHP errors

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

How to make the Facebook Like Box responsive?

None of the css trick worked for me (in my case the fb-like box was pulled right with "float:right"). However, what worked without any additional tricks is an IFRAME version of the button code. I.e.:

<iframe src="//" 
        scrolling="no" frameborder="0" 
        style="border:none; overflow:hidden; width:71px; height:21px;" 

(Note custom width in style, and no need to include additional javascript.)

How do I plot in real-time in a while loop using matplotlib?

An example use-case to plot CPU usage in real-time.

import time
import psutil
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

i = 0
x, y = [], []

while True:

    ax.plot(x, y, color='b')


    ax.set_xlim(left=max(0, i - 50), right=i + 50)
    i += 1

hasNext in Python iterators?

No. The most similar concept is most likely a StopIteration exception.

What's the u prefix in a Python string?

It's Unicode.

Just put the variable between str(), and it will work fine.

But in case you have two lists like the following:

a = ['co32','co36']
b = [u'co32',u'co36']

If you check set(a)==set(b), it will come as False, but if you do as follows:

b = str(b)

Now, the result will be True.

Fatal error: Class 'PHPMailer' not found

This is just namespacing. Look at the examples for reference - you need to either use the namespaced class or reference it absolutely, for example:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//Load composer's autoloader
require 'vendor/autoload.php';

Python's time.clock() vs. time.time() accuracy?

clock() -> floating point number

Return the CPU time or real time since the start of the process or since the first call to clock(). This has as much precision as the system records.

time() -> floating point number

Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them.

Usually time() is more precise, because operating systems do not store the process running time with the precision they store the system time (ie, actual time)

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

You do not need to use ORDER BY in inner query after WHERE clause because you have already used it in ROW_NUMBER() OVER (ORDER BY VRDATE DESC).

        item.description as item_description, as party_name, 
    FROM StockMain 
    INNER JOIN StockDetail 
        ON StockMain.stid = StockDetail.stid 
    INNER JOIN party 
        ON party.party_id = stockmain.party_id 
    INNER JOIN item 
        ON item.item_id = stockdetail.item_id 
    WHERE stockmain.etype='purchase' 
) AS MyDerivedTable
    MyDerivedTable.RowNum BETWEEN 1 and 5 

jQuery datepicker set selected date, on the fly

setDate only seems to be an issue with an inline datepicker used in jquery UI, the specific error is InternalError: too much recursion.

TCPDF not render all CSS properties

TCPDF 5.9.010 (2010-10-27) - Support for CSS properties 'border-spacing' and 'padding' for tables were added.

ITextSharp insert text to an existing pdf

This worked for me and includes using OutputStream:

PdfReader reader = new PdfReader(new RandomAccessFileOrArray(Request.MapPath("Template.pdf")), null);
    Rectangle size = reader.GetPageSizeWithRotation(1);
    using (Stream outStream = Response.OutputStream)
        Document document = new Document(size);
        PdfWriter writer = PdfWriter.GetInstance(document, outStream);

            PdfContentByte cb = writer.DirectContent;

                cb.SetFontAndSize(BaseFont.CreateFont(), 12);
                cb.SetTextMatrix(110, 110);

                PdfImportedPage page = writer.GetImportedPage(reader, 1);
                cb.AddTemplate(page, 0, 0);


How to check if a text field is empty or not in swift

It's too late and its working fine in Xcode 7.3.1

if _txtfield1.text!.isEmpty || _txtfield2.text!.isEmpty {
        //is empty

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

I had the same problem and resolved it adding this dependency.


I am using hibernate 3.6 version.

Regex matching in a Bash if statement

In case someone wanted an example using variables...


# Only continue for 'develop' or 'release/*' branches

if [[ $BRANCH =~ $BRANCH_REGEX ]];

Add custom message to thrown exception while maintaining stack trace in Java

There is an Exception constructor that takes also the cause argument: Exception(String message, Throwable t).

You can use it to propagate the stacktrace:

}catch(Exception E){
        throw new Exception("transaction: " + transNbr, E); 

what is the size of an enum type data in C++?

It depends. The standard only demands that it is large enough to hold all values, so formally an enum like enum foo { zero, one, two }; needs to only be one byte large. However most implementations make those enums as large as ints (that's faster on modern hardware; moreover it's needed for compatibility with C where enums are basically glorified ints). Note however that C++ allows enums with initializers outside of the int range, and for those enums the size will of course also be larger. For example, if you have enum bar { a, b = 1LL << 35 }; then your enum will be larger than 32 bits (most likely 64 bits) even on a system with 32 bit ints (note that in C that enum would not be allowed).

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

When you want to copy a sheet named "mySheet" and use .Copy After:=, Excel first names the copied sheet exactly the same and simply adds ' (2)' so that its final name is "mySheet (2)".

Hidden or Not, doesn't matter. It rocks with 2 lines of code, adding the copied sheet at the end of the Workbook!!!


Sheets("mySheet").Copy After:=Sheets(ThisWorkbook.Sheets.count)
Sheets("mySheet (2)").name = "TheNameYouWant"

Simple no!

Using VBA code, how to export Excel worksheets as image in Excel 2003?

do you want to try the below code I found on the internet somewhere many moons ago and used.

It uses the Export function of the Chart object along with the CopyPicture method of the Range object.


REST response code for invalid data

It is amusing to return 418 I'm a teapot to requests that are obviously crafted or malicious and "can't happen", such as failing CSRF check or missing request properties.

2.3.2 418 I'm a teapot

Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.

To keep it reasonably serious, I restrict usage of funny error codes to RESTful endpoints that are not directly exposed to the user.

What does %w(array) mean?

There is also %s that allows you to create any symbols, for example:

%s|some words|          #Same as :'some words'
%s[other words]         #Same as :'other words'
%s_last example_        #Same as :'last example'

Since Ruby 2.0.0 you also have:

%i( a b c )   # => [ :a, :b, :c ]
%i[ a b c ]   # => [ :a, :b, :c ]
%i_ a b c _   # => [ :a, :b, :c ]
# etc...

How to compile python script to binary executable

I recommend PyInstaller, a simple python script can be converted to an exe with the following commands:

utils/ [--onefile]

which creates a yourprogram.spec file which is a configuration for building the final exe. Next command builds the exe from the configuration file:

utils/ oldlogs.spec

More can be found here

C/C++ NaN constant (literal)?

Is this possible to assign a NaN to a double or float in C ...?

Yes, since C99, (C++11) <math.h> offers the below functions:

#include <math.h>
double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(const char *tagp);

which are like their strtod("NAN(n-char-sequence)",0) counterparts and NAN for assignments.

// Sample C code
uint64_t u64;
double x;
x = nan("0x12345");
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
x = -strtod("NAN(6789A)",0);
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
x = NAN;
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);

Sample output: (Implementation dependent)


What is the difference between AF_INET and PF_INET in socket programming?

AF_INET = Address Format, Internet = IP Addresses

PF_INET = Packet Format, Internet = IP, TCP/IP or UDP/IP

AF_INET is the address family that is used for the socket you're creating (in this case an Internet Protocol address). The Linux kernel, for example, supports 29 other address families such as UNIX sockets and IPX, and also communications with IRDA and Bluetooth (AF_IRDA and AF_BLUETOOTH, but it is doubtful you'll use these at such a low level).

For the most part sticking with AF_INET for socket programming over a network is the safest option.

Meaning, AF_INET refers to addresses from the internet, IP addresses specifically.

PF_INET refers to anything in the protocol, usually sockets/ports.

DataTables: Cannot read property 'length' of undefined

Try as follows the return must be d, not

 ajax: {
      "url": "xx/xxx/xxx",
      "type": "GET",
      "error": function (e) {
      "dataSrc": function (d) {
         return d

Check if all checkboxes are selected

$('.abc[checked!=true]').length == 0

The backend version is not supported to design database diagrams or tables

I ran into this problem when SQL Server 2014 standard was installed on a server where SQL Server Express was also installed. I had opened SSMS from a desktop shortcut, not realizing right away that it was SSMS for SQL Server Express, not for 2014. SSMS for Express returned the error, but SQL Server 2014 did not.

Automated testing for REST Api

Runscope is a cloud based service that can monitor Web APIs using a set of tests. Tests can be , scheduled and/or run via parameterized web hooks. Tests can also be executed from data centers around the world to ensure response times are acceptable to global client base.

The free tier of Runscope supports up to 10K requests per month.

Disclaimer: I am a developer advocate for Runscope.

How do I remove background-image in css?

Doesn't this work:

background-image: none;

Might have problems on older browsers...

Casting a number to a string in TypeScript

"Casting" is different than conversion. In this case, window.location.hash will auto-convert a number to a string. But to avoid a TypeScript compile error, you can do the string conversion yourself:

window.location.hash = ""+page_number; 
window.location.hash = String(page_number); 

These conversions are ideal if you don't want an error to be thrown when page_number is null or undefined. Whereas page_number.toString() and page_number.toLocaleString() will throw when page_number is null or undefined.

When you only need to cast, not convert, this is how to cast to a string in TypeScript:

window.location.hash = <string>page_number; 
// or 
window.location.hash = page_number as string;

The <string> or as string cast annotations tell the TypeScript compiler to treat page_number as a string at compile time; it doesn't convert at run time.

However, the compiler will complain that you can't assign a number to a string. You would have to first cast to <any>, then to <string>:

window.location.hash = <string><any>page_number;
// or
window.location.hash = page_number as any as string;

So it's easier to just convert, which handles the type at run time and compile time:

window.location.hash = String(page_number); 

(Thanks to @RuslanPolutsygan for catching the string-number casting issue.)

Verifying a specific parameter with Moq

I've been verifying calls in the same manner - I believe it is the right way to do it.

mockSomething.Verify(ms => ms.Method(
    It.Is<MyObject>(mo => mo.Id == 5 && mo.description == "test")
  ), Times.Once());

If your lambda expression becomes unwieldy, you could create a function that takes MyObject as input and outputs true/false...

mockSomething.Verify(ms => ms.Method(
    It.Is<MyObject>(mo => MyObjectFunc(mo))
  ), Times.Once());

private bool MyObjectFunc(MyObject myObject)
  return myObject.Id == 5 && myObject.description == "test";

Also, be aware of a bug with Mock where the error message states that the method was called multiple times when it wasn't called at all. They might have fixed it by now - but if you see that message you might consider verifying that the method was actually called.

EDIT: Here is an example of calling verify multiple times for those scenarios where you want to verify that you call a function for each object in a list (for example).

foreach (var item in myList)
  mockRepository.Verify(mr => mr.Update(
    It.Is<MyObject>(i => i.Id == item.Id && i.LastUpdated == item.LastUpdated),

Same approach for setup...

foreach (var item in myList) {
  var stuff = ... // some result specific to the item
    .Setup(mr => mr.GetStuff(item.itemId))

So each time GetStuff is called for that itemId, it will return stuff specific to that item. Alternatively, you could use a function that takes itemId as input and returns stuff.

    .Setup(mr => mr.GetStuff(It.IsAny<int>()))
    .Returns((int id) => SomeFunctionThatReturnsStuff(id));

One other method I saw on a blog some time back (Phil Haack perhaps?) had setup returning from some kind of dequeue object - each time the function was called it would pull an item from a queue.

How to select bottom most rows?


Where ID is the primary key of the TABLE1.

What are these attributes: `aria-labelledby` and `aria-hidden`

The primary consumers of these properties are user agents such as screen readers for blind people. So in the case with a Bootstrap modal, the modal's div has role="dialog". When the screen reader notices that a div becomes visible which has this role, it'll speak the label for that div.

There are lots of ways to label things (and a few new ones with ARIA), but in some cases it is appropriate to use an existing element as a label (semantic) without using the <label> HTML tag. With HTML modals the label is usually a <h> header. So in the Bootstrap modal case, you add aria-labelledby=[IDofModalHeader], and the screen reader will speak that header when the modal appears.

Generally speaking a screen reader is going to notice whenever DOM elements become visible or invisible, so the aria-hidden property is frequently redundant and can probably be skipped in most cases.

Java Timer vs ExecutorService?

If it's available to you, then it's difficult to think of a reason not to use the Java 5 executor framework. Calling:

ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();

will give you a ScheduledExecutorService with similar functionality to Timer (i.e. it will be single-threaded) but whose access may be slightly more scalable (under the hood, it uses concurrent structures rather than complete synchronization as with the Timer class). Using a ScheduledExecutorService also gives you advantages such as:

  • You can customize it if need be (see the newScheduledThreadPoolExecutor() or the ScheduledThreadPoolExecutor class)
  • The 'one off' executions can return results

About the only reasons for sticking to Timer I can think of are:

  • It is available pre Java 5
  • A similar class is provided in J2ME, which could make porting your application easier (but it wouldn't be terribly difficult to add a common layer of abstraction in this case)

Multipart File Upload Using Spring Rest Template + Spring Web MVC

The Multipart File Upload worked after following code modification to Upload using RestTemplate

LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new ClassPathResource(file));
HttpHeaders headers = new HttpHeaders();

HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new    HttpEntity<LinkedMultiValueMap<String, Object>>(
                    map, headers);
ResponseEntity<String> result = template.get().exchange(
                    contextPath.get() + path, HttpMethod.POST, requestEntity,

And adding MultipartFilter to web.xml


How to redirect a URL path in IIS?

Format the redirect URL in the following way:$S$Q

The $S will say that any path must be applied to the new URL. $Q says that any parameter variables must be passed to the new URL.

In IIS 7.0, you must enable the option Redirect to exact destination. I believe there must be an option like this in IIS 6.0 too.

Angular ng-click with call to a controller function not working

You should probably use the ngHref directive along with the ngClick:

 <a ng-href='#here' ng-click='go()' >click me</a>

Here is an example:

<body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <a ng-href='#here' ng-click='go()' >click me</a>
    <div style='height:1000px'>

      <a id='here'></a>


var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $ = 'World';

  $scope.go = function() {

    $scope.msg = 'clicked';

I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.

** Update **

Here is a demo of the set and get working fine with a service.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, sharedProperties) {
  $ = 'World';

  $scope.go = function(item) {


  $scope.getItem = function() {

    $scope.msg = sharedProperties.getListName();

app.service('sharedProperties', function () {
    var list_name = '';

    return {

        getListName: function() {
            return list_name;
        setListName: function(name) {
            list_name = name;


* Edit *

Please review which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.

Subtract two dates in SQL and get days of the result

How about

Select I.Fee
From Item I
WHERE  (days(GETDATE()) - days(I.DateCreated) < 365)

Finding three elements in an array whose sum is closest to a given number

This can be solved efficiently in O(n log (n)) as following. I am giving solution which tells if sum of any three numbers equal a given number.

import java.util.*;
public class MainClass {
        public static void main(String[] args) {
        int[] a = {-1, 0, 1, 2, 3, 5, -4, 6};
        System.out.println(((Object) isThreeSumEqualsTarget(a, 11)).toString());

public static boolean isThreeSumEqualsTarget(int[] array, int targetNumber) {

    //O(n log (n))

    int leftIndex = 0;
    int rightIndex = array.length - 1;

    while (leftIndex + 1 < rightIndex - 1) {
        //take sum of two corners
        int sum = array[leftIndex] + array[rightIndex];
        //find if the number matches exactly. Or get the closest match.
        //here i am not storing closest matches. You can do it for yourself.
        //O(log (n)) complexity
        int binarySearchClosestIndex = binarySearch(leftIndex + 1, rightIndex - 1, targetNumber - sum, array);
        //if exact match is found, we already got the answer
        if (-1 == binarySearchClosestIndex) {
            System.out.println(("combo is " + array[leftIndex] + ", " + array[rightIndex] + ", " + (targetNumber - sum)));
            return true;
        //if exact match is not found, we have to decide which pointer, left or right to move inwards
        //we are here means , either we are on left end or on right end
        else {

            //we ended up searching towards start of array,i.e. we need a lesser sum , lets move inwards from right
            //we need to have a lower sum, lets decrease right index
            if (binarySearchClosestIndex == leftIndex + 1) {
            } else if (binarySearchClosestIndex == rightIndex - 1) {
                //we need to have a higher sum, lets decrease right index
    return false;

public static int binarySearch(int start, int end, int elem, int[] array) {
    int mid = 0;
    while (start <= end) {
        mid = (start + end) >>> 1;
        if (elem < array[mid]) {
            end = mid - 1;
        } else if (elem > array[mid]) {
            start = mid + 1;
        } else {
            //exact match case
            //Suits more for this particular case to return -1
            return -1;
    return mid;

Subversion stuck due to "previous operation has not finished"?

follow below steps.

1) Go to the directory where you are not able to successfully clean up via svn.(Root folder or child folder).

2) Select .svn folder in the directory, cut that folder and paste it in the separate drive or separate location (out of svn directory)

3) Now, go back to the directory - right click and select TortoiseSVN -->Repo-browser

4) Checkout the folder(it will not perform fresh checkout).

5) All your items will be versioned again, and it will repair the internal issue of svn, and problem should be solved.

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

Use JSON_UNESCAPED_UNICODE inside json_encode() if your php version >=5.4.

How do I do an initial push to a remote repository with Git?

You can try this:

on Server:

adding new group to /etc/group like (example)


create new git repository:

mkdir /srv/git
cd /srv/git
mkdir project_dir
cd project_dir
git --bare init (initial git repository )
chgrp -R mygroup objects/ refs/ (change owner of directory )
chmod -R g+w objects/ refs/ (give permission write)

on Client:

mkdir my_project
cd my_project
touch .gitignore
git init
git add .
git commit -m "Initial commit"
git remote add origin [email protected]:/path/to/my_project.git
git push origin master

(Thanks Josh Lindsey for client side)

after Client, do on Server this commands:

cd /srv/git/project_dir
chmod -R g+w objects/ refs/

If got this error after git pull:

There is no tracking information for the current branch. Please specify which branch you want to merge with. See git-pull(1) for details

git pull <remote> <branch>
If you wish to set tracking information for this branch you can do so with:

git branch --set-upstream new origin/<branch>


git push -u origin master

It will help.

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

In my case this error appeared when I asigned to both dynamic created controls (combobox), same created control from other class.

//dynamic created controls
ComboBox combobox1 = ManagerControls.myCombobox1;
...some events

ComboBox combobox2 = ManagerControl.myComboBox2;
...some events


//method in constructor
public static void InitializeDynamicControls()
     ComboBox cb = new ComboBox();
     cb.Background = new SolidColorBrush(Colors.Blue);
     cb.Width = 100;
     cb.Text = "Select window";
     ManagerControls.myCombobox1 = cb;
     ManagerControls.myComboBox2 = cb; // <-- error here

Solution: create another ComboBox cb2 and assign it to ManagerControls.myComboBox2.

I hope I helped someone.

Can a table row expand and close?

To answer your question, no. That would be possible with div though. THe only question is would cause a hazzle if the functionality were done with div rather than tables.

How do I add my bot to a channel?

Are you using the right chat_id and including your bot's token after "bot" in the address? (

This page explains a few things about sending (down in "sendMessage" section) - basic stuff, but I often forget the basics.

To quote:

In order to use the sendMessage method we need to use the proper chat_id.

First things first let's send the /start command to our bot via a Telegram client.

After sent this command let's perform a getUpdates commands.

curl -s \
-X POST \<token>/getUpdates \ | jq .

The response will be like the following

{   "result": [
       "message": {
        "text": "/start",
         "date": 1435176541,
         "chat": {
           "username": "yourusername",
           "first_name": "yourfirstname",
           "id": 65535
         "from": {
           "username": "yourusername",
           "first_name": "yourfirstname",
           "id": 65535
         "message_id": 1
       "update_id": 714636917
     }    ],   "ok": true }

We are interested in the property result.message[0], save this information elsewhere.

Please note that this is only an example, you may want to set up some automatism to handle those informations Now how we can send a message ? It's simple let's check out this snippet.

curl -s \
-X POST \<token>/sendMessage \
-d text="A message from your bot" \
-d chat_id=65535 \ | jq .

Where chat_id is the piece of information saved before.

I hope that helps.

String.Format not work in TypeScript

String Interpolation

Note: As of TypeScript 1.4, string interpolation is available in TypeScript:

var a = "Hello";
var b = "World";

var text = `${a} ${b}`

This will compile to:

var a = "Hello";
var b = "World";
var text = a + " " + b;

String Format

The JavaScript String object doesn't have a format function. TypeScript doesn't add to the native objects, so it also doesn't have a String.format function.

For TypeScript, you need to extend the String interface and then you need to supply an implementation:

interface String {
    format(...replacements: string[]): string;

if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match

You can then use the feature:

var myStr = 'This is an {0} for {0} purposes: {1}';

alert(myStr.format('example', 'end'));

You could also consider string interpolation (a feature of Template Strings), which is an ECMAScript 6 feature - although to use it for the String.format use case, you would still need to wrap it in a function in order to supply a raw string containing the format and then positional arguments. It is more typically used inline with the variables that are being interpolated, so you'd need to map using arguments to make it work for this use case.

For example, format strings are normally defined to be used later... which doesn't work:

// Works
var myFormatString = 'This is an {0} for {0} purposes: {1}';

// Compiler warnings (a and b not yet defines)
var myTemplateString = `This is an ${a} for ${a} purposes: ${b}`;

So to use string interpolation, rather than a format string, you would need to use:

function myTemplate(a: string, b: string) {
    var myTemplateString = `This is an ${a} for ${a} purposes: ${b}`;

alert(myTemplate('example', 'end'));

The other common use case for format strings is that they are used as a resource that is shared. I haven't yet discovered a way to load a template string from a data source without using eval.

What is the difference between == and equals() in Java?

Just remember that .equals(...) has to be implemented by the class you are trying to compare. Otherwise, there isn't much of a point; the version of the method for the Object class does the same thing as the comparison operation: Object#equals.

The only time you really want to use the comparison operator for objects is wen you are comparing Enums. This is because there is only one instance of an Enum value at a time. For instance, given the enum

enum FooEnum {A, B, C}

You will never have more than one instance of A at a time, and the same for B and C. This means that you can actually write a method like so:

public boolean compareFoos(FooEnum x, FooEnum y)
    return (x == y);

And you will have no problems whatsoever.

Eclipse/Maven error: "No compiler is provided in this environment"

I also faced similar error when I was working with Jdk1.8_92. For me, I found tools.jar was missing in my jdk folder. Since I was running in console, I couldn't try the options of eclipse suggested by others..

I installed jdk-8u92-windows-x64. After I tried all options, I observed that tools.jar was missing in jdk1.8.0_92/lib folder. I copied tools.jar from my older version of java. Then It was able to compile.

Rounded Corners Image in Flutter

This is the code that I have used.

      width: 200.0,
      height: 200.0,
      decoration: BoxDecoration(
        image: DecorationImage(
         image: NetworkImage('Network_Image_Link')),
   borderRadius: BorderRadius.all(Radius.circular(25.0)),

Thank you!!!

Android emulator: could not get wglGetExtensionsStringARB error

I ran into this issue running Android Studio 1.4. In the Android Virtual Device (AVD) Manager, I had checked the 'Use Host GPU' box, thinking this would give me some sort of boost in the emulator's speed.
Android Studio will let you choose a device that's configured that way, and it will show you the command it used to start the virtual device: Android Studio 'Run' window output

but for some reason, it doesn't warn you that the program crashed, and it doesn't show you the stderr message that you would see had you run it from the command line yourself: Output as run on the command line

When I ran it from Android Studio, I didn't see the dialog box in the screenshot above, though it shows up just fine when you run the command from the command line, so I just sat there patiently for a few minutes while nothing happened.
As pointed out elsewhere, the drivers needed for the Use Host GPU option are not yet available. Reading through that post, it appears that this setting can be used with some Intel CPUs but not the ARM chip I chose (see CPU/ABI setting below).

My solution was to just uncheck the "Use Host GPU" box which is near the bottom of the window opened through the 'edit' option after choosing the virtual device in the Android Virtual Devices tab in the AVD Manager. You can get to the AVD manager directly in Windows at
%ANDROID_HOME%\AVD Manager.exe
where in my Windows 8 install, %ANDROID_HOME% resolved to

I don't have it running on Linux at the moment, but I'd assume it's in a similar path there, i.e.:

After unchecking the 'Use Host GPU' box, I opted to check the 'Snapshot' box next to it (as I understand, that stores a copy of the already-built vm so it doesn't need to get rebuilt every time, which should save some startup time for future instances). Here are the full settings I used:
Edit Android Virtual Device (AVD) window screenshot

Cannot open output file, permission denied

I just had the same issue. And i experienced that it always happens when i run the programm and change some code without finishing the programm still running. After that the "cannot open ..." message appears.

However i got rid of it by clicking the "Terminate" button at the very top-right side of the console window (red button) and after that "remove all terminated launches" (two x'es right next to the terminate button). This seems to close the running programm and everything works fine after :) hope this may help anyone

Running a script inside a docker container using shell script

If you want to run the same command on multiple instances you can do this :

for i in c1 dm1 dm2 ds1 ds2 gtm_m gtm_sl; do docker exec -it $i /bin/bash -c "service sshd start"; done

What's the difference between unit, functional, acceptance, and integration tests?

This is very simple.

  1. Unit testing: This is the testing actually done by developers that have coding knowledge. This testing is done at the coding phase and it is a part of white box testing. When a software comes for development, it is developed into the piece of code or slices of code known as a unit. And individual testing of these units called unit testing done by developers to find out some kind of human mistakes like missing of statement coverage etc..

  2. Functional testing: This testing is done at testing (QA) phase and it is a part of black box testing. The actual execution of the previously written test cases. This testing is actually done by testers, they find the actual result of any functionality in the site and compare this result to the expected result. If they found any disparity then this is a bug.

  3. Acceptance testing: know as UAT. And this actually done by the tester as well as developers, management team, author, writers, and all who are involved in this project. To ensure the project is finally ready to be delivered with bugs free.

  4. Integration testing: The units of code (explained in point 1) are integrated with each other to complete the project. These units of codes may be written in different coding technology or may these are of different version so this testing is done by developers to ensure that all units of the code are compatible with other and there is no any issue of integration.

What does ^M character mean in Vim?

Unix uses 0xA for a newline character. Windows uses a combination of two characters: 0xD 0xA. 0xD is the carriage return character. ^M happens to be the way vim displays 0xD (0x0D = 13, M is the 13th letter in the English alphabet).

You can remove all the ^M characters by running the following:


Where ^M is entered by holding down Ctrl and typing v followed by m, and then releasing Ctrl. This is sometimes abbreviated as ^V^M, but note that you must enter it as described in the previous sentence, rather than typing it out literally.

This expression will replace all occurrences of ^M with the empty string (i.e. nothing). I use this to get rid of ^M in files copied from Windows to Unix (Solaris, Linux, OSX).

Reminder - \r\n or \n\r?

In any .NET langauge, Environment.NewLine would be preferable.

Strings in C, how to get subString

You can treat C strings like pointers. So when you declare:

char str[10];

str can be used as a pointer. So if you want to copy just a portion of the string you can use:

char str1[24] = "This is a simple string.";
char str2[6];
strncpy(str1 + 10, str2,6);

This will copy 6 characters from the str1 array into str2 starting at the 11th element.

Example of a strong and weak entity types

Strong entity

It can exist without any other entity.


Customer(customerid, name, surname)

Weak entity

It depends on a dominant entity, and it cannot exist without a strong entity.


Adress(addressid, adressName, customerid)

Response Content type as CSV

In MVC, you can use a FileContentResult and the File method:

public FileContentResult DownloadManifest() {
    byte[] csvData = getCsvData();
    return File(csvData, "text/csv", "filename.csv");

"android.view.WindowManager$BadTokenException: Unable to add window" on

I got this error, but mine was coming from the Toasts, not a Dialog.

I have Activity and Fragments in my layout. Code for the Toast was in the Activity class. Fragments gets loaded before the Activity.

I think the Toast code was hit before the Context/Activity finished initializing. I think it was the getApplicationContext() in the command Toast.makeText(getApplicationContext(), "onMenutItemActionCollapse called", Toast.LENGTH_SHORT).show();

Add a dependency in Maven

You can also specify a dependency not in a maven repository. Could be usefull when no central maven repository for your team exist or if you have a CI server


Why is python saying invalid command 'bdist_wheel' on Travis CI?

Using Ubuntu 18.04 this problem can be resolved by installing the python3-wheelpackage.

Usually this is installed as a dependency on any Python package. But especially when building container images you often work with --no-install-recommends and therefore it is often missing and has to be installed manually first.

Radio button validation in javascript

In addition to the Javascript solutions above, you can also use an HTML 5 solution by marking the radio buttons as required in the markup. This will eliminate the need for any Javascript and let the browser do the work for you.

See HTML5: How to use the "required" attribute with a "radio" input field for more information on how to do this well.

Differences between Oracle JDK and OpenJDK

For Java 7, nothing crucial. The OpenJDK project is mostly based on HotSpot source code donated by Sun.

Moreover, OpenJDK was selected to be the reference implementation for Java 7 and is maintained by Oracle engineers.

There's a more detailed answer from 2012 on difference between JVM, JDK, JRE & OpenJDK, which links to an Oracle blog post:

Q: What is the difference between the source code found in the OpenJDK repository, and the code you use to build the Oracle JDK?

A: It is very close - our build process for Oracle JDK releases builds on OpenJDK 7 by adding just a couple of pieces, like the deployment code, which includes Oracle's implementation of the Java Plugin and Java WebStart, as well as some closed source third party components like a graphics rasterizer, some open source third party components, like Rhino, and a few bits and pieces here and there, like additional documentation or third party fonts. Moving forward, our intent is to open source all pieces of the Oracle JDK except those that we consider commercial features such as JRockit Mission Control (not yet available in Oracle JDK), and replace encumbered third party components with open source alternatives to achieve closer parity between the code bases.

How to compare LocalDate instances Java 8

Using equals() LocalDate does override equals:

int compareTo0(LocalDate otherDate) {
    int cmp = (year - otherDate.year);
    if (cmp == 0) {
        cmp = (month - otherDate.month);
        if (cmp == 0) {
            cmp = (day -;
    return cmp;

If you are not happy with the result of equals(), you are good using the predefined methods of LocalDate.

Notice that all of those method are using the compareTo0() method and just check the cmp value. if you are still getting weird result (which you shouldn't), please attach an example of input and output

How to send email from MySQL 5.1

If you have an SMTP service running, you can outfile to the drop directory. If you have high volume, you may result with duplicate file names, but there are ways to avoid that.

Otherwise, you will need to create a UDF.

Here's a sample trigger solution:

CREATE TRIGGER test.autosendfromdrop BEFORE INSERT ON test.emaildrop
      SELECT  concat("To: ",NEW.To),
              concat("From: ",NEW.From),
              concat("Subject: ",NEW.Subject),
          INTO OUTFILE 
              FIELDS TERMINATED by '\r\n' ESCAPED BY '';            

To markup the message body you will need something like this...

CREATE FUNCTION `HTMLBody`(Msg varchar(8192)) 
    RETURNS varchar(17408) CHARSET latin1 DETERMINISTIC
  declare tmpMsg varchar(17408);
  set tmpMsg = cast(concat(
      'Date: ',date_format(NOW(),'%e %b %Y %H:%i:%S -0600'),'\r\n',
      'MIME-Version: 1.0','\r\n',
      'Content-Type: multipart/alternative;','\r\n',
      ' boundary=\"----=_NextPart_000_0000_01CA4B3F.8C263EE0\"','\r\n',
      'Content-Class: urn:content-classes:message','\r\n',
      'Importance: normal','\r\n',
      'Priority: normal','\r\n','','\r\n','','\r\n',
      'This is a multi-part message in MIME format.','\r\n','','\r\n',
      'Content-Type: text/plain;','\r\n',
      '  charset=\"iso-8859-1\"','\r\n',
      'Content-Transfer-Encoding: 7bit','\r\n','','\r\n','','\r\n',
      'Content-Type: text/html','\r\n',
      'Content-Transfer-Encoding: 7bit','\r\n','','\r\n',
      ) as char);
  RETURN tmpMsg;

Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?

An IDE is an integrated development environment - a suped-up text editor with additional support for developing (such as forms designers, resource editors, etc), compiling and debugging applications. e.g Eclipse, Visual Studio.

A Library is a chunk of code that you can call from your own code, to help you do things more quickly/easily. For example, a Bitmap Processing library will provide facilities for loading and manipulating bitmap images, saving you having to write all that code for yourself. Typically a library will only offer one area of functionality (processing images or operating on zip files)

An API (application programming interface) is a term meaning the functions/methods in a library that you can call to ask it to do things for you - the interface to the library.

An SDK (software development kit) is a library or group of libraries (often with extra tool applications, data files and sample code) that aid you in developing code that uses a particular system (e.g. extension code for using features of an operating system (Windows SDK), drawing 3D graphics via a particular system (DirectX SDK), writing add-ins to extend other applications (Office SDK), or writing code to make a device like an Arduino or a mobile phone do what you want). An SDK will still usually have a single focus.

A toolkit is like an SDK - it's a group of tools (and often code libraries) that you can use to make it easier to access a device or system... Though perhaps with more focus on providing tools and applications than on just code libraries.

A framework is a big library or group of libraries that provides many services (rather than perhaps only one focussed ability as most libraries/SDKs do). For example, .NET provides an application framework - it makes it easier to use most (if not all) of the disparate services you need (e.g. Windows, graphics, printing, communications, etc) to write a vast range of applications - so one "library" provides support for pretty much everything you need to do. Often a framework supplies a complete base on which you build your own code, rather than you building an application that consumes library code to do parts of its work.

There are of course many examples in the wild that won't exactly match these descriptions though.

How to name an object within a PowerPoint slide?

Click Insert ->Object->Create from file ->Browse.

Once the file is selected choose the "Change icon" option and you will be able to rename the file and change the icon if you wish.

Hope this helps!

Set Focus on EditText

 private void requestFocus(View view) {
        if (view.requestFocus()) {

//Function Call

fork and exec in bash

Use the ampersand just like you would from the shell.

function_to_fork() {

function_to_fork &
# ... execution continues in parent process ...

How to update a claim in ASP.NET Identity?

To remove claim details from database we can use below code. Also, we need to sign in again to update the cookie values

 // create a new identity 
            var identity = new ClaimsIdentity(User.Identity);

            // Remove the existing claim value of current user from database
                await UserManager.RemoveClaimAsync(applicationUser.Id, identity.FindFirst("NameOfUser"));

            // Update customized claim 
            await UserManager.AddClaimAsync(applicationUser.Id, new Claim("NameOfUser", applicationUser.Name));

            // the claim has been updates, We need to change the cookie value for getting the updated claim
            await SignInManager.SignInAsync(Userprofile, isPersistent: false, rememberBrowser: false);

            return RedirectToAction("Index", "Home");

What is lazy loading in Hibernate?

Lazy setting decides whether to load child objects while loading the Parent Object.You need to do this setting respective hibernate mapping file of the parent class.Lazy = true (means not to load child)By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object.But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.Exampleslazy=true (default)Address child of User class can be made lazy if it is not required frequently.lazy=falseBut you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

Use component scanning as given below, if com.project.action.PasswordHintAction is annotated with stereotype annotations

<context:component-scan base-package="com.project.action"/>


I see your problem, in PasswordHintActionTest you are autowiring PasswordHintAction. But you did not create bean configuration for PasswordHintAction to autowire. Add one of stereotype annotation(@Component, @Service, @Controller) to PasswordHintAction like

public class PasswordHintAction extends BaseAction {
    private static final long serialVersionUID = -4037514607101222025L;
    private String username;

or create xml configuration in applicationcontext.xml like

<bean id="passwordHintAction" class="com.project.action.PasswordHintAction" />

Git log out user from command line

I was not able to clone a repository due to have logged on with other credentials.

To switch to another user, I >>desperate<< did:

git config --global --unset
git config --global --unset
git config --global --unset credential.helper

after, instead using ssh link, I used HTTPS link. It asked for credentials and it worked fine FOR ME!

How do you Make A Repeat-Until Loop in C++?

Repeat is supposed to be a simple loop n times loop... a conditionless version of a loop.

#define repeat(n) for (int i = 0; i < n; i++) 

repeat(10) {
    //do stuff

you can also also add an extra barce to isolate the i variable even more

#define repeat(n) { for (int i = 0; i < n; i++) 
#define endrepeat }

repeat(10) {
    //do stuff
} endrepeat;

[edit] Someone posted a concern about passing a something other than a value, such as an expression. just change to loop to run backwards, causing the expression to be evaluated only once

#define repeat(n) { for (int i = (n); i > 0; --i)

using jquery $.ajax to call a PHP function

You can't call a PHP function with Javascript, in the same way you can't call arbitrary PHP functions when you load a page (just think of the security implications).

If you need to wrap your code in a function for whatever reason, why don't you either put a function call under the function definition, eg:

function test() {
    // function code


Or, use a PHP include:

include 'functions.php'; // functions.php has the test function

Uploading files to file server using webclient class

when you manually open the IP address (via the RUN command or mapping a network drive), your PC will send your credentials over the pipe and the file server will receive authorization from the DC.

When ASP.Net tries, then it is going to try to use the IIS worker user (unless impersonation is turned on which will list a few other issues). Traditionally, the IIS worker user does not have authorization to work across servers (or even in other folders on the web server).

How to create a directory in Java?

You can try FileUtils#forceMkdir


This library have a lot of useful functions.

What is a "web service" in plain English?

An operating system provides a GUI (and CLI) that you can interact with. It also provides an API that you can interact with programmatically.

Similarly, a website provides HTML pages that you can interact with and may also provide an API that offers the same information and operations programmatically. Or those services may only be available via an API with no associated user interface.

How make background image on newsletter in outlook?

I had exactly this problem a couple of months ago while working on a WYSIWYG email editor for my company. Outlook only supports background images if they're applied to the <body> tag - any other element and it'll fail.

In the end, the only workaround I found was to use <div> element for text input, then during the content submission process I fired an AJAX request with the <div>'s content to a PHP script which wrote the text onto a blank version of our header image, saved the file and returned its (uniquely generated) name. I then used Javascript to remove the <div> and add an <img> tag using the returned filename in the src attribute.

You can get all the info/methodology from the imagecreatefrompng() page on the PHP Docs site.

Using numpy to build an array of all combinations of two arrays

It looks like you want a grid to evaluate your function, in which case you can use numpy.ogrid (open) or numpy.mgrid (fleshed out):

import numpy
my_grid = numpy.mgrid[[slice(0,1,0.1)]*6]

Pie chart with jQuery

There is a new player in the field, offering advanced Navigation Charts that are using Canvas for super-smooth animations and performance:

Example of charts:

interactive pie chart


What is cool about this lib:

  • Others slice can be expanded
  • Pie offers drill down for hierarchical structures (see example)
  • write your own data source controller easily, or provide simple json file
  • export high res images out of box
  • full touch support, works smoothly on iPad, iPhone, android, etc.

enter image description here

Charts are free for non-commercial use, commercial licenses and technical support available as well.

Also interactive Time charts and Net Charts are there for you to use. enter image description here

enter image description here

Charts come with extensive API and Settings, so you can control every aspect of the charts.

Serialize an object to XML

Here's a basic code that will help serializing the C# objects into xml:

using System;

public class clsPerson
  public  string FirstName;
  public  string MI;
  public  string LastName;

class class1
   static void Main(string[] args)
      clsPerson p=new clsPerson();
      p.FirstName = "Jeff";
      p.MI = "A";
      p.LastName = "Price";
      System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
      x.Serialize(Console.Out, p);

Convert list of ASCII codes to string (byte array) in Python

Shorter version of previous using map() function (works for python 2.7):

"".join(map(chr, myList))

What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?

An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.

There are different types of joins available in SQL:

INNER JOIN: returns rows when there is a match in both tables.

LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.

RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.

FULL JOIN: It combines the results of both left and right outer joins.

The joined table will contain all records from both the tables and fill in NULLs for missing matches on either side.

SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.

CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables.

WE can take each first four joins in Details :

We have two tables with the following values.


id  firstName                  lastName
1   arun                        prasanth                 
2   ann                         antony                   
3   sruthy                      abc                      
6   new                         abc                                           


id2 age Place
1   24  kerala
2   24  usa
3   25  ekm
5   24  chennai



Note :it gives the intersection of the two tables, i.e. rows they have common in TableA and TableB


SELECT table1.column1, table2.column2...
  FROM table1
 INNER JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
    ON = TableB.id2;

Result Will Be

firstName       lastName       age  Place
arun            prasanth        24  kerala
ann             antony          24  usa
sruthy          abc             25  ekm


Note : will give all selected rows in TableA, plus any common selected rows in TableB.


SELECT table1.column1, table2.column2...
  FROM table1
  LEFT JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
    ON = TableB.id2;


firstName                   lastName                    age   Place
arun                        prasanth                    24    kerala
ann                         antony                      24    usa
sruthy                      abc                         25    ekm
new                         abc                         NULL  NULL


Note : will give all selected rows in TableB, plus any common selected rows in TableA.


SELECT table1.column1, table2.column2...
  FROM table1
 RIGHT JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
    ON = TableB.id2;


firstName                   lastName                    age     Place
arun                        prasanth                    24     kerala
ann                         antony                      24     usa
sruthy                      abc                         25     ekm
NULL                        NULL                        24     chennai


Note :It will return all selected values from both tables.


SELECT table1.column1, table2.column2...
  FROM table1
  FULL JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
    ON = TableB.id2;


firstName                   lastName                    age    Place
arun                        prasanth                    24    kerala
ann                         antony                      24    usa
sruthy                      abc                         25    ekm
new                         abc                         NULL  NULL
NULL                        NULL                        24    chennai

Interesting Fact

For INNER joins the order doesn't matter

For (LEFT, RIGHT or FULL) OUTER joins,the order matter

Better to go check this Link it will give you interesting details about join order

How to sort an array of objects in Java?

You can try something like this:

List<Book> books = new ArrayList<Book>();

Collections.sort(books, new Comparator<Book>(){

  public int compare(Book o1, Book o2)


The CAST() function does not support the "official" data type "INT" in MySQL, it's not in the list of supported types. With MySQL, "SIGNED" (or "UNSIGNED") could be used instead:

CAST(columnName AS SIGNED)

However, this seems to be MySQL-specific (not standardized), so it may not work with other databases. At least this document (Second Informal Review Draft) ISO/IEC 9075:1992, Database does not list "SIGNED"/"UNSIGNED" in section 4.4 Numbers.

But DECIMAL is both standardized and supported by MySQL, so the following should work for MySQL (tested) and other databases:

CAST(columnName AS DECIMAL(0))

According to the MySQL docs:

If the scale is 0, DECIMAL values contain no decimal point or fractional part.

Validate email with a regex in jQuery

Email: {
                      group: '.col-sm-3',
                      enabled: false,
                      validators: {
                          //emailAddress: {
                          //    message: 'Email not Valid'
                          regexp: {
                              regexp: '^[^@\\s]+@([^@\\s]+\\.)+[^@\\s]+$',
                              message: 'Email not Valid'

Android 8: Cleartext HTTP traffic not permitted

This is done for security reasons, you should always prefer to use HTTPS (HTTP Secure) where possible.
You can read more about it here

There are multiple solutions for this issue depending on your condition.

If you are trying to communicate with a first party service, IE: your own web server

Server side: You should add HTTPS support to that server and use HTTPS instead of HTTP. These days you can even do it for free using services like LetsEncrypt and others
Client side: If you are using the HttpURLConnection from the package you can switch to HttpsURLConnection of the package, it has a similar if not identical API, so the switch should be effortless.

If you are using a third party service, like Google, Facebook, a weather service, etc.

In case that the service you are communicating with supports HTTPS (which it most likely does) you can just change your request URL from to

As a last resort, if the third party service that you want to communicate with does not support HTTPS or any other form of secure communication, you can use this answer, but again, this is not recommended as it defeats the purpose of this much needed security feature.

How do I compare 2 rows from the same table (SQL Server)?

I had a situation where I needed to compare each row of a table with the next row to it, (next here is relative to my problem specification) in the example next row is specified using the order by clause inside the row_number() function.

so I wrote this:

DECLARE @T TABLE (col1 nvarchar(50));

insert into @T VALUES ('A'),('B'),('C'),('D'),('E')

select I1.col1 Instance_One_Col, I2.col1 Instance_Two_Col  from (
 select col1,row_number() over (order by col1) as row_num
) AS I1
left join (
 select col1,row_number() over (order by col1) as row_num
) AS I2 on I1.row_num = I2.row_num - 1

after that I can compare each row to the next one as I need

How do I programmatically get the GUID of an application in .NET 2.0

You should be able to read the GUID attribute of the assembly via reflection. This will get the GUID for the current assembly

Assembly asm = Assembly.GetExecutingAssembly();
var attribs = (asm.GetCustomAttributes(typeof(GuidAttribute), true));
Console.WriteLine((attribs[0] as GuidAttribute).Value);

You can replace the GuidAttribute with other attributes as well, if you want to read things like AssemblyTitle, AssemblyVersion, etc.

You can also load another assembly (Assembly.LoadFrom and all) instead of getting the current assembly - if you need to read these attributes of external assemblies (for example, when loading a plugin).

Custom format for time command

Use the bash built-in variable SECONDS. Each time you reference the variable it will return the elapsed time since the script invocation.


echo "Start $SECONDS"
sleep 10
echo "Middle $SECONDS"
sleep 10
echo "End $SECONDS"


Start 0
Middle 10
End 20

jQuery - How to dynamically add a validation rule

You need to call .validate() before you can add rules this way, like this:

$("#myForm").validate(); //sets up the validator
$("input[id*=Hours]").rules("add", "required");

The .validate() documentation is a good guide, here's the blurb about .rules("add", option):

Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is, $("form").validate() is called first.

Updating address bar with new URL without hash or reloading the page

You can now do this in most "modern" browsers!

Here is the original article I read (posted July 10, 2010): HTML5: Changing the browser-URL without refreshing page.

For a more in-depth look into pushState/replaceState/popstate (aka the HTML5 History API) see the MDN docs.

TL;DR, you can do this:

window.history.pushState("object or string", "Title", "/new-url");

See my answer to Modify the URL without reloading the page for a basic how-to.

Scrollable Menu with Bootstrap - Menu expanding its container when it should not

I think you can simplify this by just adding the necessary CSS properties to your special scrollable menu class..


.scrollable-menu {
    height: auto;
    max-height: 200px;
    overflow-x: hidden;


       <ul class="dropdown-menu scrollable-menu" role="menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li><a href="#">Action</a></li>
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>

Working example:

Bootstrap 4

Another example for Bootstrap 4 using flexbox

jQuery: how to trigger anchor link's click event

$(":button").click(function () {                
  1. First, find the button by type(using ":") if id is not given.
  2. Second,find the anchor tag by id or in some other tag like div and $("#anchor_google")[0] returns the DOM object.

Contains case insensitive

There are a couple of approaches here.

If you want to perform a case-insensitive check for just this instance, do something like the following.

if (referrer.toLowerCase().indexOf("Ral".toLowerCase()) == -1) {

Alternatively, if you're performing this check regularly, you can add a new indexOf()-like method to String, but make it case insensitive.

String.prototype.indexOfInsensitive = function (s, b) {
    return this.toLowerCase().indexOf(s.toLowerCase(), b);

// Then invoke it
if (referrer.indexOfInsensitive("Ral") == -1) { ...

JPA Hibernate One-to-One relationship

I'm not sure you can use a relationship as an Id/PrimaryKey in Hibernate.

WHERE statement after a UNION in SQL?

You probably need to wrap the UNION in a sub-SELECT and apply the WHERE clause afterward:

    SELECT * FROM Table1 WHERE Field1 = Value1
    SELECT * FROM Table2 WHERE Field1 = Value2
) AS t WHERE Field2 = Value3

Basically, the UNION is looking for two complete SELECT statements to combine, and the WHERE clause is part of the SELECT statement.

It may make more sense to apply the outer WHERE clause to both of the inner queries. You'll probably want to benchmark the performance of both approaches and see which works better for you.

How can you program if you're blind?

I am a totally blind college student who’s had several programming internships so my answer will be based off these. I use windows xp as my operating system and Jaws to read what appears on the screen to me in synthetic speech. For java programming I use eclipse, since it’s a fully featured IDE that is accessible.

In my experience as a general rule java programs that use SWT as the GUI toolkit are more accessible then programs that use Swing which is why I stay away from netbeans. For any .net programming I use visual studio 2005 since it was the standard version used at my internship and is very accessible using Jaws and a set of scripts that were developed to make things such as the form designer more accessible.

For C and C++ programming I use cygwin with gcc as my compiler and emacs or vim as my editor depending on what I need to do. A lot of my internship involved programming for Z/OS. I used an rlogin session through Cygwin to access the USS subsystem on the mainframe and C3270 as my 3270 emulator to access the ISPF portion of the mainframe.

I usually rely on synthetic speech but do have a Braille display. I find I usually work faster with speech but use the Braille display in situations where punctuation matters and gets complicated. Examples of this are if statements with lots of nested parenthesis’s and JCL where punctuation is incredibly important.


I'm playing with Emacspeak under cygwin I'm not sure if this will be usable as a programming editor since it appears to be somewhat unresponsive but I haven't looked at any of the configuration options yet.

Effect of NOLOCK hint in SELECT statements

1) Yes, a select with NOLOCK will complete faster than a normal select.

2) Yes, a select with NOLOCK will allow other queries against the effected table to complete faster than a normal select.

Why would this be?

NOLOCK typically (depending on your DB engine) means give me your data, and I don't care what state it is in, and don't bother holding it still while you read from it. It is all at once faster, less resource-intensive, and very very dangerous.

You should be warned to never do an update from or perform anything system critical, or where absolute correctness is required using data that originated from a NOLOCK read. It is absolutely possible that this data contains rows that were deleted during the query's run or that have been deleted in other sessions that have yet to be finalized. It is possible that this data includes rows that have been partially updated. It is possible that this data contains records that violate foreign key constraints. It is possible that this data excludes rows that have been added to the table but have yet to be committed.

You really have no way to know what the state of the data is.

If you're trying to get things like a Row Count or other summary data where some margin of error is acceptable, then NOLOCK is a good way to boost performance for these queries and avoid having them negatively impact database performance.

Always use the NOLOCK hint with great caution and treat any data it returns suspiciously.

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

For me, I go to \eclipse\configuration.settings\ set the property systemProxiesEnabled to true manually and restart eclipse.

Get DOS path instead of Windows path

run cmd.exe and do the following:

> cd "long path name"
> command

Then will come up and display only short paths.


Java 8 Lambda Stream forEach with multiple statements

In the first case alternatively to multiline forEach you can use the peek stream operation:
         .peek(entry -> entry.setTempId(tempId))
         .forEach(updatedEntries.add(entityManager.update(entry, entry.getId())));

In the second case I'd suggest to extract the loop body to the separate method and use method reference to call it via forEach. Even without lambdas it would make your code more clear as the loop body is independent algorithm which processes the single entry so it might be useful in other places as well and can be tested separately.

Update after question editing. if you have checked exceptions then you have two options: either change them to unchecked ones or don't use lambdas/streams at this piece of code at all.

IntelliJ IDEA generating serialVersionUID

Easiest modern method: Alt+Enter on

private static final long serialVersionUID = ;

IntelliJ will underline the space after the =. put your cursor on it and hit alt+Enter (Option+Enter on Mac). You'll get a popover that says "Randomly Change serialVersionUID Initializer". Just hit enter, and it'll populate that space with a random long.

Return string Input with parse.string

You don't need to parse the string, it's defined as a string already.

Just do:

    private static String getStringInput (String prompt) {
     String input = EZJ.getUserInput(prompt);
     return input;

Select count(*) from multiple tables

As additional information, to accomplish same thing in SQL Server, you just need to remove the "FROM dual" part of the query.

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

You can't show dialog box ON SERVER from ASP.NET application, well of course tehnically you can do that but it makes no sense since your user is using browser and it can't see messages raised on server. You have to understand how web sites work, server side code (ASP.NET in your case) produces html, javascript etc on server and then browser loads that content and displays it to the user, so in order to present modal message box to the user you have to use Javascript, for example alert function.

Here is the example for :

Setting ANDROID_HOME enviromental variable on Mac OS X

To set ANDROID_HOME, variable, you need to know how you installed android dev setup.

If you don't know you can check if the following paths exist in your machine. Add the following to .bashrc, .zshrc, or .profile depending on what you use

If you installed with homebrew,

export ANDROID_HOME=/usr/local/opt/android-sdk

Check if this path exists:

If you installed android studio following the website,

export ANDROID_HOME=~/Library/Android/sdk

Finally add it to path:

export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

If you're too lazy to open an editor do this:

echo "export ANDROID_HOME=~/Library/Android/sdk" >> ~/.bashrc
echo "export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools" >> ~/.bashrc

Is there a Java equivalent or methodology for the typedef keyword in C++?

Really, the only use of typedef that carries over to Javaland is aliasing- that is, giving the same class multiple names. That is, you've got a class "A" and you want "B" to refer to the same thing. In C++, you'd be doing "typedef B A;"

Unfortunately, they just don't support it. However, if you control all the types involved you CAN pull a nasty hack at the library level- you either extend B from A or have B implement A.

Iterating over arrays in Python 3

While iterating over a list or array with this method:

ar = [10, 11, 12]
for i in ar:
    theSum = theSum + ar[i]

You are actually getting the values of list or array sequentially in i variable. If you print the variable i inside the for loop. You will get following output:


However, in your code you are confusing i variable with index value of array. Therefore, while doing ar[i] will mean ar[10] for the first iteration. Which is of course index out of range throwing IndexError

Edit You can read this for better understanding of different methods of iterating over array or list in Python

How to read all files in a folder from Java?

All of the answers on this topic that make use of the new Java 8 functions are neglecting to close the stream. The example in the accepted answer should be:

try (Stream<Path> filePathStream=Files.walk(Paths.get("/home/you/Desktop"))) {
    filePathStream.forEach(filePath -> {
        if (Files.isRegularFile(filePath)) {

From the javadoc of the Files.walk method:

The returned stream encapsulates one or more DirectoryStreams. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed.


OPTIONS tells you things such as "What methods are allowed for this resource".

HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.

Get the first element of an array

$myArray = array (4 => 'apple', 7 => 'orange', 13 => 'plum');
$arrayKeys = array_keys($myArray);

// The first element of your array is:
echo $myArray[$arrayKeys[0]];

What is for?

There are 2 main reasons for

  1. For convenience: the other users will not need to know your functions' exact location in your package hierarchy.

    # in
    from file1 import *
    from file2 import *
    from fileN import *
    # in
    def add():

    then others can call add() by

    from your_package import add

    without knowing file1, like

    from your_package.file1 import add
  2. If you want something to be initialized; for example, logging (which should be put in the top level):

    import logging.config

Representational state transfer (REST) and Simple Object Access Protocol (SOAP)


I understand the main idea of REST is extremely simple. We have used web browsers for years and we have seen how easy, flexible, performing, etc web sites are. HTML sites use hyperlinks and forms as the primary means of user interaction. Their main goal is to allow us, clients, to know only those links that we can use in the current state. And REST simply says 'why not use the same principles to drive computer rather than human clients through our application?' Combine this with the power of the WWW infrastructure and you'll get a killer tool for building great distributed applications.

Another possible explanation is for mathematically thinking people. Each application is basically a state machine with business logic actions being state transitions. The idea of REST is to map each transition onto some request to a resource and provide clients with links representing transitions available in the current state. Thus it models the state machine via representations and links. This is why it's called REpresentational State Transfer.

It's quite surprising that all answers seem to focus either on message format, or on HTTP verbs usage. In fact, the message format doesn't matter at all, REST can use any one provided that the service developer documents it. HTTP verbs only make a service a CRUD service, but not yet RESTful. What really turns a service into a REST service are hyperlinks (aka hypermedia controls) embedded into server responses together with data, and their amount must be enough for any client to choose the next action from those links.

Unfortunately, it's rather difficult to find correct info on REST on the Web, except for the Roy Fielding's thesis. (He's the one who derived REST). I would recommend the 'REST in Practice' book as it gives a comprehensive step-by-step tutorial on how to evolve from SOAP to REST.


This is one of the possible forms of RPC (remote procedure call) architecture style. In essence, it's just a technology that allows clients call methods of server via service boundaries (network, processes, etc) as if they were calling local methods. Of course, it actually differs from calling local methods in speed, reliability and so on, but the idea is that simple.


The details like transport protocols, message formats, xsd, wsdl, etc. don't matter when comparing any form of RPC to REST. The main difference is that an RPC service reinvents bicycle by designing it's own application protocol in the RPC API with the semantics that only it knows. Therefore, all clients have to understand this protocol prior to using the service, and no generic infrastructure like caches can be built because of proprietary semantics of all requests. Furthermore, RPC APIs do not suggest what actions are allowed in the current state, this has to be derived from additional documentation. REST on the other hand implies using uniform interfaces to allow various clients to have some understanding of API semantics, and hypermedia controls (links) to highlight available options in each state. Thus, it allows for caching responses to scale services and making correct API usage easily discoverable without additional documentation.

In a way, SOAP (as any other RPC) is an attempt to tunnel through a service boundary treating the connecting media as a black box capable of transmitting messages only. REST is a decision to acknowledge that the Web is a huge distributed information system, to accept the world as is and learn to master it instead of fighting against it.

SOAP seems to be great for internal network APIs, when you control both the server and the clients, and while the interactions are not too complex. It's more natural for developers to use it. However, for a public API that is used by many independent parties, is complex and big, REST should fit better. But this last comparison is very fuzzy.


My experience has unexpectedly shown REST development to be more difficult than SOAP. At least for .NET. While there are great frameworks like ASP.NET Web API, there's no tooling that would automatically generate client-side proxy. Nothing like 'Add Web Service Reference' or 'Add WCF Service Reference'. One has to write all serialization and service querying code by hand. And man, that's lots of boilerplate code. I think REST development needs something similar to WSDL and tooling implementation for each development platform. In fact, there seems to be a good ground: WADL or WSDL 2.0, but neither of the standards seems to be well-supported.

Update (Jan 2016)

Turns out there is now a wide variety of tools for REST API definition. My personal preference is currently RAML.

How Web Services work

Well, this is a too broad question, because it depends on the architecture and technology used in the specific web service. But in general, a web service is simply some application in the Web that can accept requests from clients and return responses. It's exposed to the Web, thus it's a web service, and it's typically available 24/7, that's why it's a service. Of course, it solves some problem (otherwise why would someone ever use a web service) for its clients.

Get the latest record from mongodb collection

This is a rehash of the previous answer but it's more likely to work on different mongodb versions.


How do I set an absolute include path in PHP?

What I do is put a config.php file in my root directory. This file is included by all PHP files in my project. In that config.php file, I then do the following;

define( 'ROOT_DIR', dirname(__FILE__) );

Then in all files, I know what the root of my project is and can do stuff like this

require_once( ROOT_DIR.'/include/functions.php' );

Sorry, no bonus points for getting outside of the public directory ;) This also has the unfortunate side affect that you still need a relative path for finding config.php, but it makes the rest of your includes much easier.

JavaScript DOM remove element

Seems I don't have enough rep to post a comment, so another answer will have to do.

When you unlink a node using removeChild() or by setting the innerHTML property on the parent, you also need to make sure that there is nothing else referencing it otherwise it won't actually be destroyed and will lead to a memory leak. There are lots of ways in which you could have taken a reference to the node before calling removeChild() and you have to make sure those references that have not gone out of scope are explicitly removed.

Doug Crockford writes here that event handlers are known a cause of circular references in IE and suggests removing them explicitly as follows before calling removeChild()

function purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        for (i = a.length - 1; i >= 0; i -= 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {

And even if you take a lot of precautions you can still get memory leaks in IE as described by Jens-Ingo Farley here.

And finally, don't fall into the trap of thinking that Javascript delete is the answer. It seems to be suggested by many, but won't do the job. Here is a great reference on understanding delete by Kangax.

Using Bootstrap Tooltip with AngularJS

install the dependencies:

npm install jquery --save
npm install tether --save
npm install bootstrap@version --save;

next, add scripts in your angular-cli.json

"scripts": [

then, create a script.js


now restart your server.

How to add new activity to existing project in Android Studio?

I think natually do it is straightforward, whether Intellij IDEA or Android Studio, I always click new Java class menu, and then typing the class name, press Enter to create. after that, I manually typing "extends Activity" in the class file, and then import the class by shortcut key. finally, I also manually override the onCreate() method and invoke the setContentView() method.

Make multiple-select to adjust its height to fit options without scroll bar

To adjust the size (height) of all multiple selects to the number of options, use jQuery:

$('select[multiple = multiple]').each(function() {
    $(this).attr('size', $(this).find('option').length)

How do you parse and process HTML/XML in PHP?

This is commonly referred to as screen scraping, by the way. The library I have used for this is Simple HTML Dom Parser.

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (

You can try to set the proxy settings:

File -> Settings -> Appearance -> System Settings -> Http proxy -> Auto Detect

And then provide the proxy URL.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

I just added an @ symbol and it started working. Like this: @$product->save();

How to make vim paste from (and copy to) system's clipboard?

You can copy into vim by gnome-terminal's shortcut for paste. Make the file in insert mode and use


Remember beforehand to

 :set paste 

to avoid messing with the indentation.

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")

How to get the current plugin directory in WordPress?

Try this:

function PluginUrl() {

        //Try to use WP API if possible, introduced in WP 2.6
        if (function_exists('plugins_url')) return trailingslashit(plugins_url(basename(dirname(__FILE__))));

        //Try to find manually... can't work if wp-content was renamed or is redirected
        $path = dirname(__FILE__);
        $path = str_replace("\\","/",$path);
        $path = trailingslashit(get_bloginfo('wpurl')) . trailingslashit(substr($path,strpos($path,"wp-content/")));
        return $path;

echo PluginUrl(); will return the current plugin url.

Ternary operator (?:) in Bash

ternary operator ? : is just short form of if/else

case "$b" in
 5) a=$c ;;
 *) a=$d ;;


 [[ $b = 5 ]] && a="$c" || a="$d"

Keyboard shortcut to change font size in Eclipse?

Oddly, working on a .js file and Ctrl, Shift, += works to zoom in (and Ctrl - works to zoom out but you have to select 1 or 2 after Ctrl -). This only works when I'm in the js file but the zoom applies to all my open tabs. Using Eclipse Juno on Ubuntu.

How to set breakpoints in inline Javascript in Google Chrome?

You also can give a name to your script:

<script> ... (your code here) //# sourceURL=somename.js </script>

ofcourse replace "somename" by some name ;) and then you will see it in the chrome debugger at "Sources > top > (no domain) > somename.js" as a normal script and you will be able to debug it like other scripts

How to convert list of numpy arrays into single numpy array?

I checked some of the methods for speed performance and find that there is no difference! The only difference is that using some methods you must carefully check dimension.


|            | shape (10000)  |  shape (1,10000)  |
| np.concat  |    0.18280     |      0.17960      |
|  np.stack  |    0.21501     |      0.16465      |
| np.vstack  |    0.21501     |      0.17181      |
|  np.array  |    0.21656     |      0.16833      |

As you can see I tried 2 experiments - using np.random.rand(10000) and np.random.rand(1, 10000) And if we use 2d arrays than np.stack and np.array create additional dimension - result.shape is (1,10000,10000) and (10000,1,10000) so they need additional actions to avoid this.


from time import perf_counter
from tqdm import tqdm_notebook
import numpy as np
l = []
for i in tqdm_notebook(range(10000)):
    new_np = np.random.rand(10000)

start = perf_counter()
stack = np.stack(l, axis=0 )
print(f'np.stack: {perf_counter() - start:.5f}')

start = perf_counter()
vstack = np.vstack(l)
print(f'np.vstack: {perf_counter() - start:.5f}')

start = perf_counter()
wrap = np.array(l)
print(f'np.array: {perf_counter() - start:.5f}')

start = perf_counter()
l = [el.reshape(1,-1) for el in l]
conc = np.concatenate(l, axis=0 )
print(f'np.concatenate: {perf_counter() - start:.5f}')

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

In my maven project this error occurs, after i closed my projects and reopens them. The dependencys wasn´t build correctly at that time. So for me the solution was just to update the Maven Dependencies of the projects!

Find non-ASCII characters in varchar columns using SQL Server

running the various solutions on some real world data - 12M rows varchar length ~30, around 9k dodgy rows, no full text index in play, the patIndex solution is the fastest, and it also selects the most rows.

(pre-ran km. to set the cache to a known state, ran the 3 processes, and finally ran km again - the last 2 runs of km gave times within 2 seconds)

patindex solution by Gerhard Weiss -- Runtime 0:38, returns 9144 rows

select dodgyColumn from myTable fcc
WHERE  patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,dodgyColumn ) >0

the substring-numbers solution by MT. -- Runtime 1:16, returned 8996 rows

select dodgyColumn from myTable fcc
INNER JOIN dbo.Numbers32k dn ON dn.number<(len(fcc.dodgyColumn ))
WHERE ASCII(SUBSTRING(fcc.dodgyColumn , dn.Number, 1))<32 
    OR ASCII(SUBSTRING(fcc.dodgyColumn , dn.Number, 1))>127

udf solution by Deon Robertson -- Runtime 3:47, returns 7316 rows

select dodgyColumn 
from myTable 
where dbo.udf_test_ContainsNonASCIIChars(dodgyColumn , 1) = 1

How can I submit a POST form using the <a href="..."> tag?

You need to use javascript for this.

<form id="form1" action="showMessage.jsp" method="post">
    <a href="javascript:;" onclick="document.getElementById('form1').submit();"><%=n%></a>
    <input type="hidden" name="mess" value=<%=n%>/>

Using ConfigurationManager to load config from an arbitrary location

For ASP.NET use WebConfigurationManager:

var config = WebConfigurationManager.OpenWebConfiguration("~/Sites/" + requestDomain + "/");

What's the difference between Sender, From and Return-Path?

The official RFC which defines this specification could be found here: (look at paragraph 2.1.2. and the following)

2.1.2. Header Field: From

    Mailbox of message author  
Related information:
    Specifies the author(s) of the message; that is, the mailbox(es)
    of the person(s) or system(s) responsible for the writing of the
    message. Defined as standard by RFC 822.

2.1.3. Header Field: Sender

    Mailbox of message sender  
Related information:
    Specifies the mailbox of the agent responsible for the actual
    transmission of the message.  Defined as standard by RFC 822.

2.1.22. Header Field: Return-Path

    Message return path
Related information:
    Return path for message response diagnostics. See also RFC 2821
    [17]. Defined as standard by RFC 822.

ASP.NET 4.5 has not been registered on the Web server

run visual studio in admin rights and execute following "commandaspnet_regiis -i"

UICollectionView Self Sizing Cells with Auto Layout

I tried using estimatedItemSize but there were a bunch of bugs when inserting and deleting cells if the estimatedItemSize was not exactly equal to the cell's height. i stopped setting estimatedItemSize and implemented dynamic cell's by using a prototype cell. here's how that's done:

create this protocol:

protocol SizeableCollectionViewCell {
    func fittedSize(forConstrainedSize size: CGSize)->CGSize

implement this protocol in your custom UICollectionViewCell:

class YourCustomCollectionViewCell: UICollectionViewCell, SizeableCollectionViewCell {

    @IBOutlet private var mTitle: UILabel!
    @IBOutlet private var mDescription: UILabel!
    @IBOutlet private var mContentView: UIView!
    @IBOutlet private var mTitleTopConstraint: NSLayoutConstraint!
    @IBOutlet private var mDesciptionBottomConstraint: NSLayoutConstraint!

    func fittedSize(forConstrainedSize size: CGSize)->CGSize {

        let fittedSize: CGSize!

        //if height is greatest value, then it's dynamic, so it must be calculated
        if size.height == CGFLoat.greatestFiniteMagnitude {

            var height: CGFloat = 0

            /*now here's where you want to add all the heights up of your views.
              apple provides a method called sizeThatFits(size:), but it's not 
              implemented by default; except for some concrete subclasses such 
              as UILabel, UIButton, etc. search to see if the classes you use implement 
              it. here's how it would be used:
            height += mTitle.sizeThatFits(size).height
            height += mDescription.sizeThatFits(size).height
            height += mCustomView.sizeThatFits(size).height    //you'll have to implement this in your custom view

            //anything that takes up height in the cell has to be included, including top/bottom margin constraints
            height += mTitleTopConstraint.constant
            height += mDescriptionBottomConstraint.constant

            fittedSize = CGSize(width: size.width, height: height)
        //else width is greatest value, if not, you did something wrong
        else {
            //do the same thing that's done for height but with width, remember to include leading/trailing margins in calculations

        return fittedSize

now make your controller conform to UICollectionViewDelegateFlowLayout, and in it, have this field:

class YourViewController: UIViewController, UICollectionViewDelegateFlowLayout {
    private var mCustomCellPrototype = UINib(nibName: <name of the nib file for your custom collectionviewcell>, bundle: nil).instantiate(withOwner: nil, options: nil).first as! SizeableCollectionViewCell

it will be used as a prototype cell to bind data to and then determine how that data affected the dimension that you want to be dynamic

finally, the UICollectionViewDelegateFlowLayout's collectionView(:layout:sizeForItemAt:) has to be implemented:

class YourViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

    private var mDataSource: [CustomModel]

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath)->CGSize {

        //bind the prototype cell with the data that corresponds to this index path
        mCustomCellPrototype.bind(model: mDataSource[indexPath.row])    //this is the same method you would use to reconfigure the cells that you dequeue in collectionView(:cellForItemAt:). i'm calling it bind

        //define the dimension you want constrained
        let width = UIScreen.main.bounds.size.width - 20    //the width you want your cells to be
        let height = CGFloat.greatestFiniteMagnitude    //height has the greatest finite magnitude, so in this code, that means it will be dynamic
        let constrainedSize = CGSize(width: width, height: height)

        //determine the size the cell will be given this data and return it
        return mCustomCellPrototype.fittedSize(forConstrainedSize: constrainedSize)

and that's it. Returning the cell's size in collectionView(:layout:sizeForItemAt:) in this way preventing me from having to use estimatedItemSize, and inserting and deleting cells works perfectly.

permission denied - php unlink

in addition to all the answers that other friends have , if somebody who is looking this post is looking for a way to delete a "Folder" not a "file" , should take care that Folders must delete by php rmdir() function and if u want to delete a "Folder" by unlink() , u will encounter with a wrong Warning message that says "permission denied"

however u can make folders & files by mkdir() but the way u delete folders (rmdir()) is different from the way you delete files(unlink())

eventually as a fact:

in many programming languages, any permission related error may not directly means an actual permission issue

for example, if you want to readSync a file that doesn't exist with node fs module you will encounter a wrong EPERM error

How do I check if a C++ string is an int?

Another version...

Use strtol, wrapping it inside a simple function to hide its complexity :

inline bool isInteger(const std::string & s)
   if(s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false;

   char * p;
   strtol(s.c_str(), &p, 10);

   return (*p == 0);

Why strtol ?

As far as I love C++, sometimes the C API is the best answer as far as I am concerned:

  • using exceptions is overkill for a test that is authorized to fail
  • the temporary stream object creation by the lexical cast is overkill and over-inefficient when the C standard library has a little known dedicated function that does the job.

How does it work ?

strtol seems quite raw at first glance, so an explanation will make the code simpler to read :

strtol will parse the string, stopping at the first character that cannot be considered part of an integer. If you provide p (as I did above), it sets p right at this first non-integer character.

My reasoning is that if p is not set to the end of the string (the 0 character), then there is a non-integer character in the string s, meaning s is not a correct integer.

The first tests are there to eliminate corner cases (leading spaces, empty string, etc.).

This function should be, of course, customized to your needs (are leading spaces an error? etc.).

Sources :

See the description of strtol at:

See, too, the description of strtol's sister functions (strtod, strtoul, etc.).

How To fix white screen on app Start up?

Put this in a custom style and it solves all the problems. Using the hacky translucent fix will make your task bar and nav bar translucent and make the splashscreen or main screen look like spaghetti.

<item name="android:windowDisablePreview">true</item>

How to force DNS refresh for a website?

So if the issue is you just created a website and your clients or any given ISP DNS is cached and doesn't show new site yet. Yes all the other stuff applies ipconfig reset browser etc. BUT here's an Idea and something I do from time to time. You can set an alternate network ISP's DNS in the tcpip properties on the NIC properties. So if your ISP is say telstra and it hasn't propagated or updated you can specify an alternate service providers dns there. if that isp dns is updated before your native one hey presto you will see new site.But there is lots of other tricks you can do to determine propagation and get mail to work prior to the DNS updating. drop me a line if any one wants to chat.

Generate a random point within a circle (uniformly)

Let ? (radius) and f (azimuth) be two random variables corresponding to polar coordinates of an arbitrary point inside the circle. If the points are uniformly distributed then what is the disribution function of ? and f?

For any r: 0 < r < R the probability of radius coordinate ? to be less then r is

P[? < r] = P[point is within a circle of radius r] = S1 / S0 =(r/R)2

Where S1 and S0 are the areas of circle of radius r and R respectively. So the CDF can be given as:

          0          if r<=0
  CDF =   (r/R)**2   if 0 < r <= R
          1          if r > R

And PDF:

PDF = d/dr(CDF) = 2 * (r/R**2) (0 < r <= R).

Note that for R=1 random variable sqrt(X) where X is uniform on [0, 1) has this exact CDF (because P[sqrt(X) < y] = P[x < y**2] = y**2 for 0 < y <= 1).

The distribution of f is obviously uniform from 0 to 2*p. Now you can create random polar coordinates and convert them to Cartesian using trigonometric equations:

x = ? * cos(f)
y = ? * sin(f)

Can't resist to post python code for R=1.

from matplotlib import pyplot as plt
import numpy as np

rho = np.sqrt(np.random.uniform(0, 1, 5000))
phi = np.random.uniform(0, 2*np.pi, 5000)

x = rho * np.cos(phi)
y = rho * np.sin(phi)

plt.scatter(x, y, s = 4)

You will get

enter image description here

How to evaluate http response codes from bash/shell script?

Another variation:

       status=$(curl -sS  -I  2> /dev/null | head -n 1 | cut -d' ' -f2)
status_w_desc=$(curl -sS  -I  2> /dev/null | head -n 1 | cut -d' ' -f2-)

Android Google Maps v2 - set zoom level for myLocation

mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentPlace,15)); This is will not have animation effect.

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

I'm surprised no one here has mentioned the html cell magic option. from the docs (IPython, but same for Jupyter)


Render the cell as a block of HTML

How to set margin of ImageView using code, not xml

Answer from 2020 year :

dependencies {
    implementation "androidx.core:core-ktx:1.2.0"

and cal it simply in your code

view.updateLayoutParams<ViewGroup.MarginLayoutParams> {

Get all files and directories in specific path fast

You can use this to get all directories and sub-directories. Then simply loop through to process the files.

string[] folders = System.IO.Directory.GetDirectories(@"C:\My Sample Path\","*", System.IO.SearchOption.AllDirectories);

foreach(string f in folders)
   //call some function to get all files in folder

How does Google calculate my location on a desktop?

Rejecting the WiFi networks idea!

Sorry folks... I don't see it. Using WiFi networks around you seems to be a highly inaccurate and ineffective method of collecting data. WiFi networks these days simply don't stay long in one place.

Think about it, the WiFi networks change every day. Not to mention MiFi and Adhoc networks which are "designed" to be mobile and travel with the users. Equipment breaks, network settings change, people move... Relying on "WiFi Networks" in your area seems highly inaccurate and in the end may not even offer a significant improvement in granularity over IP lookup.

I think the idea that iPhone users are "scanning and sending" the WiFi survey data back to google, and the wardriving, perhaps in conjunction with the Google Maps "Street View" mapping might seem like a very possible method of collecting this data however, in practicality, it does not work as a business model.

Oh and btw, I forgot to mention in my prior post... when I originally pulled my location the time I was pinpointed "precisely" on the map I was connecting to a router from my desktop over an ethernet connection. I don't have a WiFi card on my desktop.

So if that "nearby WiFi networks" theory was true... then I shouldn't have been able to pinpoint my location with such precision.

I'll call my ISP, SKyrim, and ask them as to whether they share their network topology to enable geolocation on their networks.

Drop default constraint on a column in TSQL

I would like to refer a previous question, Because I have faced same problem and solved by this solution. First of all a constraint is always built with a Hash value in it's name. So problem is this HASH is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4 here 6AB17FE4 is the hash value(8 bit). So I am referring a single script which will be fruitful to all

     declare @table_name nvarchar(256)
     declare @col_name nvarchar(256)
     set @table_name = N'ProcedureAlerts'
     set @col_name = N'EmailSent'

     select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select
         sys.tables t
         join sys.default_constraints d on d.parent_object_id = t.object_id
         join sys.columns c on c.object_id = t.object_id
                               and c.column_id = d.parent_column_id
     where  = @table_name
         and = @col_name) + ']'

    --print @Command
    exec sp_executesql @Command

It will drop your default constraint. However if you want to create it again you can simply try this

ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]

Finally, just simply run a DROP command to drop the column.

git replace local version with remote version

My understanding is that, for example, you wrongly saved a file you had updated for testing purposes only. Then, when you run "git status" the file appears as "Modified" and you say some bad words. You just want the old version back and continue to work normally.

In that scenario you can just run the following command:

git checkout -- path/filename

Change size of text in text input tag?

I would say to set up the font size change in your CSS stylesheet file.

I'm pretty sure that you want all text at the same size for all your form fields. Adding inline styles in your HTML will add to many lines at the end... plus you would need to add it to the other types of form fields such as <select>.


<div id="cForm">
    <form method="post">
        <input type="text" name="name" placeholder="Name" data-required="true">
        <option value="" selected="selected" >Choose Category...</option>


input, select {
    font-size: 18px;

JQuery - Storing ajax response into global variable

        function getJson(url) {
            return JSON.parse($.ajax({
                type: 'GET',
                url: url,
                dataType: 'json',
                global: false,
                async: false,
                success: function (data) {
                    return data;

        var myJsonObj = getJson('/api/current');

This works!!!

Codeigniter's `where` and `or_where`

You can use : Query grouping allows you to create groups of WHERE clauses by enclosing them in parentheses. This will allow you to create queries with complex WHERE clauses. Nested groups are supported. Example:

                ->where('a', 'a')
                        ->where('b', 'b')
                        ->where('c', 'c')
        ->where('d', 'd')

Select first 4 rows of a data.frame in R

Use head:

dnow <- data.frame(x=rnorm(100), y=runif(100))
head(dnow,4) ## default is 6

How do I set up access control in SVN?

You can use svn+ssh:, and then it's based on access control to the repository at the given location.

This is how I host a project group repository at my uni, where I can't set up anything else. Just having a directory that the group owns, and running svn-admin (or whatever it was) in there means that I didn't need to do any configuration.

Convert an image to grayscale in HTML/CSS

Support for CSS filters has landed in Webkit. So we now have a cross-browser solution.

img {_x000D_
  filter: gray; /* IE6-9 */_x000D_
  -webkit-filter: grayscale(1); /* Google Chrome, Safari 6+ & Opera 15+ */_x000D_
  filter: grayscale(1); /* Microsoft Edge and Firefox 35+ */_x000D_
/* Disable grayscale on hover */_x000D_
img:hover {_x000D_
  -webkit-filter: grayscale(0);_x000D_
  filter: none;_x000D_
<img src="">

What about Internet Explorer 10?

You can use a polyfill like gray.

Java: Simplest way to get last word in a string

String test =  "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);

convert string array to string

    string ConvertStringArrayToString(string[] array)
        // Concatenate all the elements into a StringBuilder.
        StringBuilder strinbuilder = new StringBuilder();
        foreach (string value in array)
            strinbuilder.Append(' ');
        return strinbuilder.ToString();

Where is body in a nodejs http.get response?

The data event is fired multiple times with 'chunks' of the body as they are downloaded and an end event when all chunks have been downloaded.

With Node supporting Promises now, I created a simple wrapper to return the concatenated chunks through a Promise:

const httpGet = url => {
  return new Promise((resolve, reject) => {
    http.get(url, res => {
      let body = ''; 
      res.on('data', chunk => body += chunk);
      res.on('end', () => resolve(body));
    }).on('error', reject);

You can call it from an async function with:

const body = await httpGet('');

How do I calculate the MD5 checksum of a file in Python?

You can calculate the checksum of a file by reading the binary data and using hashlib.md5().hexdigest(). A function to do this would look like the following:

def File_Checksum_Dis(dirname):
    if not os.path.exists(dirname):
        print(dirname+" directory is not existing");
    for fname in os.listdir(dirname):
        if not fname.endswith('~'):
            fnaav = os.path.join(dirname, fname);
            fd = open(fnaav, 'rb');
            data =;
            print("File Name is: ",fname);          

Java Comparator class to sort arrays

Just tried this solution, we don't have to even write int.

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };
Arrays.sort(twoDim, (a1,a2) -> a2[0] - a1[0]);

This thing will also work, it automatically detects the type of string.

(grep) Regex to match non-ASCII characters?

This turned out to be very flexible and extensible. $field =~ s/[^\x00-\x7F]//g ; # thus all non ASCII or specific items in question could be cleaned. Very nice either in selection or pre-processing of items that will eventually become hash keys.

JavaScript: Object Rename Key

While this does not exactly give a better solution to renaming a key, it provides a quick and easy ES6 way to rename all keys in an object while not mutating the data they contain.

let b = {a: ["1"], b:["2"]};
Object.keys(b).map(id => {
  b[`root_${id}`] = [...b[id]];
  delete b[id];

How to change option menu icon in the action bar?

The following lines should be updated in app -> main -> res -> values -> Styles.xml

 <!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    <item name="android:actionOverflowButtonStyle">@style/MyActionButtonOverflow</item>

<!-- Style to replace actionbar overflow icon. set item 'android:actionOverflowButtonStyle' in AppTheme -->
<style name="MyActionButtonOverflow" parent="android:style/Widget.Holo.Light.ActionButton.Overflow">
    <item name="android:src">@drawable/ic_launcher</item>
    <item name="android:background">?android:attr/actionBarItemBackground</item>
    <item name="android:contentDescription">"Lala"</item>

This is how it can be done. If you want to change the overflow icon in action bar

CASE IN statement with multiple values

Yes. You need to use the "Searched" form rather than the "Simple" form of the CASE expression

         WHEN c.Number IN ( '1121231', '31242323' ) THEN 1
         WHEN c.Number IN ( '234523', '2342423' ) THEN 2
       END AS Test
FROM   tblClient c  

getting the screen density programmatically in android?

This should help on your activity ...

void printSecreenInfo(){

    Display display = getWindowManager().getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();

    Log.i(TAG, "density :" +  metrics.density);

    // density interms of dpi
    Log.i(TAG, "D density :" +  metrics.densityDpi);

    // horizontal pixel resolution
    Log.i(TAG, "width pix :" +  metrics.widthPixels);

     // actual horizontal dpi
    Log.i(TAG, "xdpi :" +  metrics.xdpi);

    // actual vertical dpi
    Log.i(TAG, "ydpi :" +  metrics.ydpi);



I/test( 1044): density :1.0

I/test( 1044): D density :160

I/test( 1044): width pix :800

I/test( 1044): xdpi :160.0

I/test( 1044): ydpi :160.42105

AngularJS : Factory and Service?

  • If you use a service you will get the instance of a function ("this" keyword).
  • If you use a factory you will get the value that is returned by invoking the function reference (the return statement in factory)

Factory and Service are the most commonly used recipes. The only difference between them is that Service recipe works better for objects of custom type, while Factory can produce JavaScript primitives and functions.


How can I find the number of years between two dates?


    LocalDate.of( 2010 , 1 , 1 ) , ZoneId.of( "America/Montreal" ) ) 


The old date-time classes really are bad, so bad that both Sun & Oracle agreed to supplant them with the java.time classes. If you do any significant work at all with date-time values, adding a library to your project is worthwhile. The Joda-Time library was highly successful and recommended, but is now in maintenance mode. The team advises migration to the java.time classes.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

LocalDate start = LocalDate.of( 2010 , 1 , 1 ) ;
LocalDate stop = ZoneId.of( "America/Montreal" ) );
long years = java.time.temporal.ChronoUnit.YEARS.between( start , stop );

Dump to console.

System.out.println( "start: " + start + " | stop: " + stop + " | years: " + years ) ;

start: 2010-01-01 | stop: 2016-09-06 | years: 6

Table of all date-time types in Java, both modern and legacy

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

break statement in "if else" - java

The "break" command does not work within an "if" statement.

If you remove the "break" command from your code and then test the code, you should find that the code works exactly the same without a "break" command as with one.

"Break" is designed for use inside loops (for, while, do-while, enhanced for and switch).

Styling every 3rd item of a list using CSS?

Yes, you can use what's known as :nth-child selectors.

In this case you would use:

li:nth-child(3n) {
// Styling for every third element here.


3(0) = 0
3(1) = 3
3(2) = 6
3(3) = 9
3(4) = 12

:nth-child() is compatible in Chrome, Firefox, and IE9+.

For a work around to use :nth-child() amongst other pseudo-classes/attribute selectors in IE6 through to IE8, see this link.

How to output JavaScript with PHP

You need to escape your quotes.

You can do this:

echo "<script type=\"text/javascript\">";

or this:

echo "<script type='text/javascript'>";

or this:

echo '<script type="text/javascript">';

Or just stay out of php

<script type="text/javascript">

Exporting results of a Mysql query to excel?

Use the below query:

 SELECT * FROM document INTO OUTFILE 'c:/order-1.csv' FIELDS TERMINATED BY ','  

SVN - Checksum mismatch while updating

My solution was:

  1. Execute svn cleanup from file system
  2. Switch to another branch
  3. Solve conflicts
  4. Switch to the "problematic" branch
  5. Execute cleanup from Spring Tool Suite
  6. Execute Project Update

Python Write bytes to file

If you want to write bytes then you should open the file in binary mode.

f = open('/tmp/output', 'wb')

CSS display: inline vs inline-block

Inline elements:

  1. respect left & right margins and padding, but not top & bottom
  2. cannot have a width and height set
  3. allow other elements to sit to their left and right.
  4. see very important side notes on this here.

Block elements:

  1. respect all of those
  2. force a line break after the block element
  3. acquires full-width if width not defined

Inline-block elements:

  1. allow other elements to sit to their left and right
  2. respect top & bottom margins and padding
  3. respect height and width

From W3Schools:

  • An inline element has no line break before or after it, and it tolerates HTML elements next to it.

  • A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.

  • An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.

When you visualize this, it looks like this:

CSS block vs inline vs inline-block

The image is taken from this page, which also talks some more about this subject.

Mapping a JDBC ResultSet to an object

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONObject;

public class ObjectMapper {

//generic method to convert JDBC resultSet into respective DTo class
public static Object mapValue(List<Map<String, Object>> rows,Class<?> className) throws Exception

        List<Object> response=new ArrayList<>(); 
        Gson gson=new Gson();

        for(Map<String, Object> row:rows){
        org.json.simple.JSONObject jsonObject = new JSONObject();
        String json=jsonObject.toJSONString();
        Object actualObject=gson.fromJson(json, className);
        return response;


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

        List<Map<String, Object>> rows=new ArrayList<Map<String, Object>>(); 

        //Hardcoded data for testing
        Map<String, Object> row1=new HashMap<String, Object>();
        row1.put("name", "Raja");
        row1.put("age", 22);
        row1.put("location", "India");

        Map<String, Object> row2=new HashMap<String, Object>();
        row2.put("name", "Rani");
        row2.put("age", 20);
        row2.put("location", "India");


        List<Dto> res=(List<Dto>) mapValue(rows, Dto.class);



    public class Dto {

    private String name;
    private Integer age;
    private String location;

    //getters and setters


Try the above code .This can be used as a generic method to map JDBC result to respective DTO class.

Stop setInterval

Use a variable and call clearInterval to stop it.

var interval;

  interval = setInterval(updateDiv,3000);

  function updateDiv(){
      url: 'getContent.php',
      success: function(data){
      error: function(){
        $('.square').html('<span style="color:red">Connection problems</span>');
        // I want to stop it here

Make the console wait for a user input to close

In Java this would be

How can you search Google Programmatically Java API

Indeed there is an API to search google programmatically. The API is called google custom search. For using this API, you will need an Google Developer API key and a cx key. A simple procedure for accessing google search from java program is explained in my blog.

Now dead, here is the Wayback Machine link.

Sort tuples based on second parameter

And if you are using python 3.X, you may apply the sorted function on the mylist. This is just an addition to the answer that @Sven Marnach has given above.

# using *sort method*
mylist.sort(lambda x: x[1]) 

# using *sorted function*
sorted(mylist, key = lambda x: x[1]) 

Find Process Name by its Process ID

The basic one, ask tasklist to filter its output and only show the indicated process id information

tasklist /fi "pid eq 4444" 

To only get the process name, the line must be splitted

for /f "delims=," %%a in ('
    tasklist /fi "pid eq 4444" /nh /fo:csv
') do echo %%~a

In this case, the list of processes is retrieved without headers (/nh) in csv format (/fo:csv). The commas are used as token delimiters and the first token in the line is the image name

note: In some windows versions (one of them, my case, is the spanish windows xp version), the pid filter in the tasklist does not work. In this case, the filter over the list of processes must be done out of the command

for /f "delims=," %%a in ('
    tasklist /fo:csv /nh ^| findstr /b /r /c:"[^,]*,\"4444\","
') do echo %%~a

This will generate the task list and filter it searching for the process id in the second column of the csv output.

edited: alternatively, you can suppose what has been made by the team that translated the OS to spanish. I don't know what can happen in other locales.

tasklist /fi "idp eq 4444" 

Normalize data in pandas

Slightly modified from: Python Pandas Dataframe: Normalize data between 0.01 and 0.99? but from some of the comments thought it was relevant (sorry if considered a repost though...)

I wanted customized normalization in that regular percentile of datum or z-score was not adequate. Sometimes I knew what the feasible max and min of the population were, and therefore wanted to define it other than my sample, or a different midpoint, or whatever! This can often be useful for rescaling and normalizing data for neural nets where you may want all inputs between 0 and 1, but some of your data may need to be scaled in a more customized way... because percentiles and stdevs assumes your sample covers the population, but sometimes we know this isn't true. It was also very useful for me when visualizing data in heatmaps. So i built a custom function (used extra steps in the code here to make it as readable as possible):

def NormData(s,low='min',center='mid',hi='max',insideout=False,shrinkfactor=0.):    
    if low=='min':
    elif low=='abs':
    if hi=='max':
    elif hi=='abs':

    if center=='mid':
    elif center=='avg':
    elif center=='median':

    s2=[x-center for x in s]


    for x in s2:
        if x<low:
        elif x>hi:
            if x>=center:

    if insideout==True:
        ir=[(1.-abs(z-0.5)*2.) for z in r]

    rr =[x-(x-0.5)*shrinkfactor for x in r]    
    return rr

This will take in a pandas series, or even just a list and normalize it to your specified low, center, and high points. also there is a shrink factor! to allow you to scale down the data away from endpoints 0 and 1 (I had to do this when combining colormaps in matplotlib:Single pcolormesh with more than one colormap using Matplotlib) So you can likely see how the code works, but basically say you have values [-5,1,10] in a sample, but want to normalize based on a range of -7 to 7 (so anything above 7, our "10" is treated as a 7 effectively) with a midpoint of 2, but shrink it to fit a 256 RGB colormap:

[0.1279296875, 0.5826822916666667, 0.99609375]

It can also turn your data inside out... this may seem odd, but I found it useful for heatmapping. Say you want a darker color for values closer to 0 rather than hi/low. You could heatmap based on normalized data where insideout=True:

[0.251953125, 0.8307291666666666, 0.00390625]

So now "2" which is closest to the center, defined as "1" is the highest value.

Anyways, I thought my application was relevant if you're looking to rescale data in other ways that could have useful applications to you.

How do I get the absolute directory of a file in bash?

echo "$(cd "$(dirname "$1")"; pwd -P)"

Some explanations:

  1. This script get relative path as argument "$1"
  2. Then we get dirname part of that path (you can pass either dir or file to this script): dirname "$1"
  3. Then we cd "$(dirname "$1"); into this relative dir
  4. pwd -P and get absolute path. The -P option will avoid symlinks
  5. As final step we echo it

Then run your script: your_file.txt

Real mouse position in canvas

The Simple 1:1 Scenario

For situations where the canvas element is 1:1 compared to the bitmap size, you can get the mouse positions by using this snippet:

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
      x: evt.clientX - rect.left,
      y: evt.clientY -

Just call it from your event with the event and canvas as arguments. It returns an object with x and y for the mouse positions.

As the mouse position you are getting is relative to the client window you'll have to subtract the position of the canvas element to convert it relative to the element itself.

Example of integration in your code:

//put this outside the event loop..
var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");

function draw(evt) {
    var pos = getMousePos(canvas, evt);

    context.fillStyle = "#000000";
    context.fillRect (pos.x, pos.y, 4, 4);

Note: borders and padding will affect position if applied directly to the canvas element so these needs to be considered via getComputedStyle() - or apply those styles to a parent div instead.

When Element and Bitmap are of different sizes

When there is the situation of having the element at a different size than the bitmap itself, for example, the element is scaled using CSS or there is pixel-aspect ratio etc. you will have to address this.


function  getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect(), // abs. size of element
      scaleX = canvas.width / rect.width,    // relationship bitmap vs. element for X
      scaleY = canvas.height / rect.height;  // relationship bitmap vs. element for Y

  return {
    x: (evt.clientX - rect.left) * scaleX,   // scale mouse coordinates after they have
    y: (evt.clientY - * scaleY     // been adjusted to be relative to element

With transformations applied to context (scale, rotation etc.)

Then there is the more complicated case where you have applied transformation to the context such as rotation, skew/shear, scale, translate etc. To deal with this you can calculate the inverse matrix of the current matrix.

Newer browsers let you read the current matrix via the currentTransform property and Firefox (current alpha) even provide a inverted matrix through the mozCurrentTransformInverted. Firefox however, via mozCurrentTransform, will return an Array and not DOMMatrix as it should. Neither Chrome, when enabled via experimental flags, will return a DOMMatrix but a SVGMatrix.

In most cases however you will have to implement a custom matrix solution of your own (such as my own solution here - free/MIT project) until this get full support.

When you eventually have obtained the matrix regardless of path you take to obtain one, you'll need to invert it and apply it to your mouse coordinates. The coordinates are then passed to the canvas which will use its matrix to convert it to back wherever it is at the moment.

This way the point will be in the correct position relative to the mouse. Also here you need to adjust the coordinates (before applying the inverse matrix to them) to be relative to the element.

An example just showing the matrix steps

function draw(evt) {
    var pos = getMousePos(canvas, evt);        // get adjusted coordinates as above
    var imatrix = matrix.inverse();            // get inverted matrix somehow
    pos = imatrix.applyToPoint(pos.x, pos.y);  // apply to adjusted coordinate

    context.fillStyle = "#000000";
    context.fillRect(pos.x-1, pos.y-1, 2, 2);

An example of using currentTransform when implemented would be:

    var pos = getMousePos(canvas, e);          // get adjusted coordinates as above
    var matrix = ctx.currentTransform;         // W3C (future)
    var imatrix = matrix.invertSelf();         // invert

    // apply to point:
    var x = pos.x * imatrix.a + pos.y * imatrix.c + imatrix.e;
    var y = pos.x * imatrix.b + pos.y * imatrix.d + imatrix.f;

Update I made a free solution (MIT) to embed all these steps into a single easy-to-use object that can be found here and also takes care of a few other nitty-gritty things most ignore.

Why do I get PLS-00302: component must be declared when it exists?

I came here because I had the same problem.
What was the problem for me was that the procedure was defined in the package body, but not in the package header.
I was executing my function with a lose BEGIN END statement.

How to check if $_GET is empty?

if (!$_GET) echo "empty";

why do you need such a checking?

you guys too direct-minded.
don't take as offense but sometimes not-minded at all
$_GET is very special variable, not like others.
it is supposed to be always set. no need to treat it as other variables. when $_GET is not set and it's expected - it is emergency case and that's what "Undefined variable" notice invented for

How to create a pulse effect using -webkit-animation - outward rings

Or if you want a ripple pulse effect, you could use this:

.gps_ring {
     border: 2px solid #fff;
     -webkit-border-radius: 50%;
     height: 18px;
     width: 18px;
     position: absolute;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    opacity: 0.0;
.gps_ring:before {
    border: 2px solid #fff;
    -webkit-border-radius: 50%;
    height: 30px;
    width: 30px;
    position: absolute;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-delay: 0.1s;
    opacity: 0.0;
.gps_ring:after {
    border:2px solid #fff;
    -webkit-border-radius: 50%;
    height: 50px;
    width: 50px;
    position: absolute;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-delay: 0.2s;
    opacity: 0.0;
@-webkit-keyframes pulsate {
    0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
    50% {opacity: 1.0;}
    100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}

How to use pip with Python 3.x alongside Python 2.x

This worked for me on OS X: (I say this because sometimes is a pain that mac has "its own" version of every open source tool, and you cannot remove it because "its improvements" make it unique for other apple stuff to work, and if you remove it things start falling appart)

I followed the steps provided by @Lennart Regebro to get pip for python 3, nevertheless pip for python 2 was still first on the path, so... what I did is to create a symbolic link to python 3 inside /usr/bin (in deed I did the same to have my 2 pythons running in peace):

ln -s /Library/Frameworks/Python.framework/Versions/3.4/bin/pip /usr/bin/pip3

Notice that I added a 3 at the end, so basically what you have to do is to use pip3 instead of just pip.

The post is old but I hope this helps someone someday. this should theoretically work for any LINUX system.

How to make php display \t \n as tab and new line instead of characters

You can use HTML,

echo $data1 . '&nbsp' . $data2 . '&nbsp' . $data3 . '<br/>';

Using a list as a data source for DataGridView

this Func may help you . it add every list object to grid view

private void show_data()
            BindingSource Source = new BindingSource();

            for (int i = 0; i < CC.Contects.Count; i++)

            Data_View.DataSource = Source;


I write this for simple database app

How to call a PHP file from HTML or Javascript

You just need to post the form data to the insert php file function, see below :)

class DbConnect
// Database login vars
private $dbHostname = '';
private $dbDatabase = '';
private $dbUsername = '';
private $dbPassword = '';
public $db = null;

public function connect()

        $this->db = new PDO("mysql:host=".$this->dbHostname.";dbname=".$this->dbDatabase, $this->dbUsername, $this->dbPassword);
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    catch(PDOException $e)
        echo "It seems there was an error.  Please refresh your browser and try again. ".$e->getMessage();

public function store($email)
    $stm = $this->db->prepare('INSERT INTO subscribers (email) VALUES ?');
    $stm->bindValue(1, $email);

    return $stm->execute();

Angular 2 Show and Hide an element

We can do it by using the below code snippet..

Angular Code:

 export class AppComponent {  
    toggleShowHide: string = "visible";  

HTML Template:

  Enter text to hide or show item in bellow: 
  <input type="text" [(ngModel)]="toggleShowHide">
  Toggle Show/hide:
  <div [style.visibility]="toggleShowHide">   
     Final Release Angular 2!

Remove accents/diacritics in a string in JavaScript

Here is a very fast script based on the Unicode standard, taken from here:

var Latinise={};Latinise.latin_map={"Á":"A","A":"A","?":"A","?":"A","?":"A","?":"A","?":"A","A":"A","Â":"A","?":"A","?":"A","?":"A","?":"A","?":"A","Ä":"A","A":"A","?":"A","?":"A","?":"A","?":"A","À":"A","?":"A","?":"A","A":"A","A":"A","Å":"A","?":"A","?":"A","?":"A","Ã":"A","?":"AA","Æ":"AE","?":"AE","?":"AE","?":"AO","?":"AU","?":"AV","?":"AV","?":"AY","?":"B","?":"B","?":"B","?":"B","?":"B","?":"B","C":"C","C":"C","Ç":"C","?":"C","C":"C","C":"C","?":"C","?":"C","D":"D","?":"D","?":"D","?":"D","?":"D","?":"D","?":"D","?":"D","?":"D","Ð":"D","?":"D","?":"DZ","?":"DZ","É":"E","E":"E","E":"E","?":"E","?":"E","Ê":"E","?":"E","?":"E","?":"E","?":"E","?":"E","?":"E","Ë":"E","E":"E","?":"E","?":"E","È":"E","?":"E","?":"E","E":"E","?":"E","?":"E","E":"E","?":"E","?":"E","?":"E","?":"ET","?":"F","ƒ":"F","?":"G","G":"G","G":"G","G":"G","G":"G","G":"G","?":"G","?":"G","G":"G","?":"H","?":"H","?":"H","H":"H","?":"H","?":"H","?":"H","?":"H","H":"H","Í":"I","I":"I","I":"I","Î":"I","Ï":"I","?":"I","I":"I","?":"I","?":"I","Ì":"I","?":"I","?":"I","I":"I","I":"I","I":"I","I":"I","?":"I","?":"D","?":"F","?":"G","?":"R","?":"S","?":"T","?":"IS","J":"J","?":"J","?":"K","K":"K","K":"K","?":"K","?":"K","?":"K","?":"K","?":"K","?":"K","?":"K","L":"L","?":"L","L":"L","L":"L","?":"L","?":"L","?":"L","?":"L","?":"L","?":"L","?":"L","?":"L","?":"L","L":"L","?":"LJ","?":"M","?":"M","?":"M","?":"M","N":"N","N":"N","N":"N","?":"N","?":"N","?":"N","?":"N","?":"N","?":"N","?":"N","?":"N","Ñ":"N","?":"NJ","Ó":"O","O":"O","O":"O","Ô":"O","?":"O","?":"O","?":"O","?":"O","?":"O","Ö":"O","?":"O","?":"O","?":"O","?":"O","O":"O","?":"O","Ò":"O","?":"O","O":"O","?":"O","?":"O","?":"O","?":"O","?":"O","?":"O","?":"O","?":"O","O":"O","?":"O","?":"O","O":"O","O":"O","O":"O","Ø":"O","?":"O","Õ":"O","?":"O","?":"O","?":"O","?":"OI","?":"OO","?":"E","?":"O","?":"OU","?":"P","?":"P","?":"P","?":"P","?":"P","?":"P","?":"P","?":"Q","?":"Q","R":"R","R":"R","R":"R","?":"R","?":"R","?":"R","?":"R","?":"R","?":"R","?":"R","?":"R","?":"C","?":"E","S":"S","?":"S","Š":"S","?":"S","S":"S","S":"S","?":"S","?":"S","?":"S","?":"S","T":"T","T":"T","?":"T","?":"T","?":"T","?":"T","?":"T","?":"T","?":"T","T":"T","T":"T","?":"A","?":"L","?":"M","?":"V","?":"TZ","Ú":"U","U":"U","U":"U","Û":"U","?":"U","Ü":"U","U":"U","U":"U","U":"U","U":"U","?":"U","?":"U","U":"U","?":"U","Ù":"U","?":"U","U":"U","?":"U","?":"U","?":"U","?":"U","?":"U","?":"U","U":"U","?":"U","U":"U","U":"U","U":"U","?":"U","?":"U","?":"V","?":"V","?":"V","?":"V","?":"VY","?":"W","W":"W","?":"W","?":"W","?":"W","?":"W","?":"W","?":"X","?":"X","Ý":"Y","Y":"Y","Ÿ":"Y","?":"Y","?":"Y","?":"Y","?":"Y","?":"Y","?":"Y","?":"Y","?":"Y","?":"Y","Z":"Z","Ž":"Z","?":"Z","?":"Z","Z":"Z","?":"Z","?":"Z","?":"Z","?":"Z","?":"IJ","Œ":"OE","?":"A","?":"AE","?":"B","?":"B","?":"C","?":"D","?":"E","?":"F","?":"G","?":"G","?":"H","?":"I","?":"R","?":"J","?":"K","?":"L","?":"L","?":"M","?":"N","?":"O","?":"OE","?":"O","?":"OU","?":"P","?":"R","?":"N","?":"R","?":"S","?":"T","?":"E","?":"R","?":"U","?":"V","?":"W","?":"Y","?":"Z","á":"a","a":"a","?":"a","?":"a","?":"a","?":"a","?":"a","a":"a","â":"a","?":"a","?":"a","?":"a","?":"a","?":"a","ä":"a","a":"a","?":"a","?":"a","?":"a","?":"a","à":"a","?":"a","?":"a","a":"a","a":"a","?":"a","?":"a","å":"a","?":"a","?":"a","?":"a","ã":"a","?":"aa","æ":"ae","?":"ae","?":"ae","?":"ao","?":"au","?":"av","?":"av","?":"ay","?":"b","?":"b","?":"b","?":"b","?":"b","?":"b","b":"b","?":"b","?":"o","c":"c","c":"c","ç":"c","?":"c","c":"c","?":"c","c":"c","?":"c","?":"c","d":"d","?":"d","?":"d","?":"d","?":"d","?":"d","?":"d","?":"d","?":"d","?":"d","?":"d","d":"d","?":"d","?":"d","i":"i","?":"j","?":"j","?":"j","?":"dz","?":"dz","é":"e","e":"e","e":"e","?":"e","?":"e","ê":"e","?":"e","?":"e","?":"e","?":"e","?":"e","?":"e","ë":"e","e":"e","?":"e","?":"e","è":"e","?":"e","?":"e","e":"e","?":"e","?":"e","?":"e","e":"e","?":"e","?":"e","?":"e","?":"e","?":"et","?":"f","ƒ":"f","?":"f","?":"f","?":"g","g":"g","g":"g","g":"g","g":"g","g":"g","?":"g","?":"g","?":"g","g":"g","?":"h","?":"h","?":"h","h":"h","?":"h","?":"h","?":"h","?":"h","?":"h","?":"h","h":"h","?":"hv","í":"i","i":"i","i":"i","î":"i","ï":"i","?":"i","?":"i","?":"i","ì":"i","?":"i","?":"i","i":"i","i":"i","?":"i","?":"i","i":"i","?":"i","?":"d","?":"f","?":"g","?":"r","?":"s","?":"t","?":"is","j":"j","j":"j","?":"j","?":"j","?":"k","k":"k","k":"k","?":"k","?":"k","?":"k","?":"k","?":"k","?":"k","?":"k","?":"k","l":"l","l":"l","?":"l","l":"l","l":"l","?":"l","?":"l","?":"l","?":"l","?":"l","?":"l","?":"l","?":"l","?":"l","?":"l","?":"l","l":"l","?":"lj","?":"s","?":"s","?":"s","?":"s","?":"m","?":"m","?":"m","?":"m","?":"m","?":"m","n":"n","n":"n","n":"n","?":"n","?":"n","?":"n","?":"n","?":"n","?":"n","?":"n","?":"n","?":"n","?":"n","?":"n","ñ":"n","?":"nj","ó":"o","o":"o","o":"o","ô":"o","?":"o","?":"o","?":"o","?":"o","?":"o","ö":"o","?":"o","?":"o","?":"o","?":"o","o":"o","?":"o","ò":"o","?":"o","o":"o","?":"o","?":"o","?":"o","?":"o","?":"o","?":"o","?":"o","?":"o","?":"o","o":"o","?":"o","?":"o","o":"o","o":"o","ø":"o","?":"o","õ":"o","?":"o","?":"o","?":"o","?":"oi","?":"oo","?":"e","?":"e","?":"o","?":"o","?":"ou","?":"p","?":"p","?":"p","?":"p","?":"p","?":"p","?":"p","?":"p","?":"p","?":"q","?":"q","?":"q","?":"q","r":"r","r":"r","r":"r","?":"r","?":"r","?":"r","?":"r","?":"r","?":"r","?":"r","?":"r","?":"r","?":"r","?":"r","?":"r","?":"r","?":"c","?":"c","?":"e","?":"r","s":"s","?":"s","š":"s","?":"s","s":"s","s":"s","?":"s","?":"s","?":"s","?":"s","?":"s","?":"s","?":"s","?":"s","g":"g","?":"o","?":"o","?":"u","t":"t","t":"t","?":"t","?":"t","?":"t","?":"t","?":"t","?":"t","?":"t","?":"t","?":"t","?":"t","t":"t","?":"t","t":"t","?":"th","?":"a","?":"ae","?":"e","?":"g","?":"h","?":"h","?":"h","?":"i","?":"k","?":"l","?":"m","?":"m","?":"oe","?":"r","?":"r","?":"r","?":"r","?":"t","?":"v","?":"w","?":"y","?":"tz","ú":"u","u":"u","u":"u","û":"u","?":"u","ü":"u","u":"u","u":"u","u":"u","u":"u","?":"u","?":"u","u":"u","?":"u","ù":"u","?":"u","u":"u","?":"u","?":"u","?":"u","?":"u","?":"u","?":"u","u":"u","?":"u","u":"u","?":"u","u":"u","u":"u","?":"u","?":"u","?":"ue","?":"um","?":"v","?":"v","?":"v","?":"v","?":"v","?":"v","?":"v","?":"vy","?":"w","w":"w","?":"w","?":"w","?":"w","?":"w","?":"w","?":"w","?":"x","?":"x","?":"x","ý":"y","y":"y","ÿ":"y","?":"y","?":"y","?":"y","?":"y","?":"y","?":"y","?":"y","?":"y","?":"y","?":"y","z":"z","ž":"z","?":"z","?":"z","?":"z","z":"z","?":"z","?":"z","?":"z","?":"z","?":"z","?":"z","z":"z","?":"z","?":"ff","?":"ffi","?":"ffl","?":"fi","?":"fl","?":"ij","œ":"oe","?":"st","?":"a","?":"e","?":"i","?":"j","?":"o","?":"r","?":"u","?":"v","?":"x"};
String.prototype.latinise=function(){return this.replace(/[^A-Za-z0-9\[\] ]/g,function(a){return Latinise.latin_map[a]||a})};
String.prototype.isLatin=function(){return this==this.latinise()}

Some examples:

> "Piqué".latinize();
> "Piqué".isLatin();
> "Pique".isLatin();
> "Piqué".latinise().isLatin();

To ensure the above latin_map doesn't get corrupted by copy/pasting or other transformations, use this base64 encoded string, replacing the first line of the above:

var base64map="eyLDgSI6IkEiLCLEgiI6IkEiLCLhuq4iOiJBIiwi4bq2IjoiQSIsIuG6sCI6IkEiLCLhurIiOiJBIiwi4bq0IjoiQSIsIseNIjoiQSIsIsOCIjoiQSIsIuG6pCI6IkEiLCLhuqwiOiJBIiwi4bqmIjoiQSIsIuG6qCI6IkEiLCLhuqoiOiJBIiwiw4QiOiJBIiwix54iOiJBIiwiyKYiOiJBIiwix6AiOi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rGxIjoidiIsIuG5vSI6InYiLCLqnaEiOiJ2eSIsIuG6gyI6InciLCLFtSI6InciLCLhuoUiOiJ3Iiwi4bqHIjoidyIsIuG6iSI6InciLCLhuoEiOiJ3Iiwi4rGzIjoidyIsIuG6mCI6InciLCLhuo0iOiJ4Iiwi4bqLIjoieCIsIuG2jSI6IngiLCLDvSI6InkiLCLFtyI6InkiLCLDvyI6InkiLCLhuo8iOiJ5Iiwi4bu1IjoieSIsIuG7syI6InkiLCLGtCI6InkiLCLhu7ciOiJ5Iiwi4bu/IjoieSIsIsizIjoieSIsIuG6mSI6InkiLCLJjyI6InkiLCLhu7kiOiJ5IiwixboiOiJ6Iiwixb4iOiJ6Iiwi4bqRIjoieiIsIsqRIjoieiIsIuKxrCI6InoiLCLFvCI6InoiLCLhupMiOiJ6IiwiyKUiOiJ6Iiwi4bqVIjoieiIsIuG1tiI6InoiLCLhto4iOiJ6IiwiypAiOiJ6IiwixrYiOiJ6IiwiyYAiOiJ6Iiwi76yAIjoiZmYiLCLvrIMiOiJmZmkiLCLvrIQiOiJmZmwiLCLvrIEiOiJmaSIsIu+sgiI6ImZsIiwixLMiOiJpaiIsIsWTIjoib2UiLCLvrIYiOiJzdCIsIuKCkCI6ImEiLCLigpEiOiJlIiwi4bWiIjoiaSIsIuKxvCI6ImoiLCLigpIiOiJvIiwi4bWjIjoiciIsIuG1pCI6InUiLCLhtaUiOiJ2Iiwi4oKTIjoieCJ9";
var Latinise={};Latinise.latin_map=JSON.parse(decodeURIComponent(escape(atob(base64map))));

Jquery: Checking to see if div contains text, then action

Ayman is right but, you can use it like that as well :

if( $("#field > div.field-item").text().indexOf('someText') >= 0) {

error C2220: warning treated as error - no 'object' file generated

As a side-note, you can enable/disable individual warnings using #pragma. You can have a look at the documentation here

From the documentation:

// pragma_warning.cpp
// compile with: /W1
#pragma warning(disable:4700)
void Test() {
   int x;
   int y = x;   // no C4700 here
   #pragma warning(default:4700)   // C4700 enabled after Test ends

int main() {
   int x;
   int y = x;   // C4700
} cannot be cast to

in case your project use dagger, and then this error show up you can add this at android manifest

        android: name = ".BaseApplication"
        ...> ...

PostgreSQL: Show tables in PostgreSQL

use only see a tables

=> \dt

if want to see schema tables


if you want to see specific schema tables

=>\dt schema_name.*