Programs & Examples On #Custom painting

Convert default format to Timestamp in Java

You can use

  long startTime = date.getTime() * 1000000;;
  long estimatedTime = System.nanoTime() - startTime;

To get time in nano.

Java Docs

Check if Internet Connection Exists with jQuery?

i have a solution who work here to check if internet connection exist :

    url: "",
    context: document.body,
    error: function(jqXHR, exception) {
    success: function() {

How to make a round button?

Used the shape as oval. This makes the button oval

    <shape android:shape="oval" >
            android:color="#ffee82ee" />

        <solid android:color="#ffee82ee" />

            android:topRightRadius="12.0dip" />

Python: How exactly can you take a string, split it, reverse it and join it back together again?

I was asked to do so without using any inbuilt function. So I wrote three functions for these tasks. Here is the code-

def string_to_list(string):
'''function takes actual string and put each word of string in a list'''
list_ = []
x = 0 #Here x tracks the starting of word while y look after the end of word.
for y in range(len(string)):
    if string[y]==" ":
        x = y+1
    elif y==len(string)-1:
return list_

def list_to_reverse(list_):
'''Function takes the list of words and reverses that list'''
reversed_list = []
for element in list_[::-1]:
return reversed_list

def list_to_string(list_):
'''This function takes the list and put all the elements of the list to a string with 
space as a separator'''
final_string = str()
for element in list_:
    final_string += str(element) + " "
return final_string

text = "I love India"
list_ = string_to_list(text)
reverse_list = list_to_reverse(list_)
final_string = list_to_string(reverse_list)
print("Input is - {}; Output is - {}".format(text, final_string))
#op= Input is - I love India; Output is - India love I 

Please remember, This is one of a simpler solution. This can be optimized so try that. Thank you!

Override body style for content in an iframe

give the body of your iframe page an ID (or class if you wish)

<body id="myId">

then, also within the iframe's page, assign a background to that in CSS

#myId {
    background-color: white;

Why are hexadecimal numbers prefixed with 0x?

Short story: The 0 tells the parser it's dealing with a constant (and not an identifier/reserved word). Something is still needed to specify the number base: the x is an arbitrary choice.

Long story: In the 60's, the prevalent programming number systems were decimal and octal — mainframes had 12, 24 or 36 bits per byte, which is nicely divisible by 3 = log2(8).

The BCPL language used the syntax 8 1234 for octal numbers. When Ken Thompson created B from BCPL, he used the 0 prefix instead. This is great because

  1. an integer constant now always consists of a single token,
  2. the parser can still tell right away it's got a constant,
  3. the parser can immediately tell the base (0 is the same in both bases),
  4. it's mathematically sane (00005 == 05), and
  5. no precious special characters are needed (as in #123).

When C was created from B, the need for hexadecimal numbers arose (the PDP-11 had 16-bit words) and all of the points above were still valid. Since octals were still needed for other machines, 0x was arbitrarily chosen (00 was probably ruled out as awkward).

C# is a descendant of C, so it inherits the syntax.

How to create JNDI context in Spring Boot with Embedded Tomcat Container

Please note instead of

public TomcatEmbeddedServletContainerFactory tomcatFactory()

I had to use the following method signature

public EmbeddedServletContainerFactory embeddedServletContainerFactory() 

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

jquery disable form submit on enter

Complete Solution in JavaScript for all browsers

The code above and most of the solutions are perfect. However, I think the most liked one "short answer" which is incomplete.

So here's the entire answer. in JavaScript with native Support for IE 7 as well.

var form = document.getElementById("testForm");
form.addEventListener("submit",function(e){e.preventDefault(); return false;});

This solution will now prevent the user from submit using the enter Key and will not reload the page, or take you to the top of the page, if your form is somewhere below.

Reading json files in C++

Have a look at nlohmann's JSON Repository on GitHub. I have found that it is the most convenient way to work with JSON.

It is designed to behave just like an STL container, which makes its usage very intuitive.

Rounding a double value to x number of decimal places in swift

round a double value to x number of decimal
NO. of digits after decimal

var x = 1.5657676754
var y = (x*10000).rounded()/10000
print(y)  // 1.5658 

var x = 1.5657676754 
var y = (x*100).rounded()/100
print(y)  // 1.57 

var x = 1.5657676754
var y = (x*10).rounded()/10
print(y)  // 1.6

Long press on UITableView

I've used Anna-Karenina's answer, and it works almost great with a very serious bug.

If you're using sections, long-pressing the section title will give you a wrong result of pressing the first row on that section, I've added a fixed version below (including the filtering of dummy calls based on the gesture state, per Anna-Karenina suggestion).

- (IBAction)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {

        CGPoint p = [gestureRecognizer locationInView:self.tableView];

        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
        if (indexPath == nil) {
            NSLog(@"long press on table view but not on a row");
        } else {
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            if (cell.isHighlighted) {
                NSLog(@"long press on table view at section %d row %d", indexPath.section, indexPath.row);

Equivalent of .bat in mac os

The common convention would be to put it in a .sh file that looks like this -

java -cp  ".;./supportlibraries/Framework_Core.jar;... etc

Note that '\' become '/'.

You could execute as


or set the x bit on the file

chmod +x

and then just call

What is Node.js' Connect, Express and "middleware"?

middleware as the name suggests actually middleware is sit between middle.. middle of what? middle of request and request,response,express server sit in express app in this picture you can see requests are coming from client then the express server server serves those requests.. then lets dig deeper.. actually we can divide this whole express server's whole task in to small seperate tasks like in this way. how middleware sit between request and response small chunk of server parts doing some particular task and passed request to next one.. finally doing all the tasks response has been made.. all middle ware can access request object,response object and next function of request response cycle..

this is good example for explaining middleware in express youtube video for middleware

App installation failed due to application-identifier entitlement

The accepted answer didn't work for me. To make it work I had to reset the Apple Watch to the last available backup.

Freemarker iterating over hashmap keys

If using a BeansWrapper with an exposure level of Expose.SAFE or Expose.ALL, then the standard Java approach of iterating the entry set can be employed:

For example, the following will work in Freemarker (since at least version 2.3.19):

<#list map.entrySet() as entry>  
  <input type="hidden" name="${entry.key}" value="${entry.value}" />

In Struts2, for instance, an extension of the BeanWrapper is used with the exposure level defaulted to allow this manner of iteration.

Run an exe from C# code



Compiling the Code

Copy the code and paste it into the Main method of a console application. Replace "mspaint.exe" with the path to the application you want to run.

How to render an ASP.NET MVC view as a string?

Quick tip

For a strongly typed Model just add it to the ViewData.Model property before passing to RenderViewToString. e.g

this.ViewData.Model = new OrderResultEmailViewModel(order);
string myString = RenderViewToString(this.ControllerContext, "~/Views/Order/OrderResultEmail.aspx", "~/Views/Shared/Site.Master", this.ViewData, this.TempData);

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

There are a few misunderstandings in the discussion above.

First, you can always ROLLBACK a transaction... no matter what the state of the transaction. So you only have to check the XACT_STATE before a COMMIT, not before a rollback.

As far as the error in the code, you will want to put the transaction inside the TRY. Then in your CATCH, the first thing you should do is the following:

      ROLLBACK TRANSACTION @transaction

Then, after the statement above, then you can send an email or whatever is needed. (FYI: If you send the email BEFORE the rollback, then you will definitely get the "cannot... write to log file" error.)

This issue was from last year, so I hope you have resolved this by now :-) Remus pointed you in the right direction.

As a rule of thumb... the TRY will immediately jump to the CATCH when there is an error. Then, when you're in the CATCH, you can use the XACT_STATE to decide whether you can commit. But if you always want to ROLLBACK in the catch, then you don't need to check the state at all.

UITableview: How to Disable Selection for Some Rows but Not Others

For Swift 4.0 for example:

cell.isUserInteractionEnabled = false
cell.contentView.alpha = 0.5

How to remove the hash from window.location (URL) with JavaScript without page refresh?

How about the following?

window.location.hash=' '

Please note that am setting the hash to a single space and not an empty string.

Setting the hash to an invalid anchor does not cause a refresh either. Such as,


But, I find above solution to be misleading. This seems to indicate that there is an anchor on the given position with the given name although there isn't one. At the same time, using an empty string causes page to move to the top which can be unacceptable at times. Using a space also ensures that whenever the URL is copied and bookmarked and visited again, the page will usually be at the top and the space will be ignored.

And, hey, this is my first answer on StackOverflow. Hope someone finds it useful and it matches the community standards.

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?

Advantages of this solution

  • Simplest to read / use (imo)
  • Return value can be used as a sum, or just ignored
  • Plain es6 version, also link to TypeScript version of the code

Disadvantages - Mutation. Being internal only I don't care, maybe some others will not either.

Examples and Code

times(5, 3)                       // 15    (3+3+3+3+3)

times(5, (i) => Math.pow(2,i) )   // 31    (1+2+4+8+16)

times(5, '<br/>')                 // <br/><br/><br/><br/><br/>

times(3, (i, count) => {          // name[0], name[1], name[2]
    let n = 'name[' + i + ']'
    if (i < count-1)
        n += ', '
    return n

function times(count, callbackOrScalar) {
    let type = typeof callbackOrScalar
    let sum
    if (type === 'number') sum = 0
    else if (type === 'string') sum = ''

    for (let j = 0; j < count; j++) {
        if (type === 'function') {
            const callback = callbackOrScalar
            const result = callback(j, count)
            if (typeof result === 'number' || typeof result === 'string')
                sum = sum === undefined ? result : sum + result
        else if (type === 'number' || type === 'string') {
            const scalar = callbackOrScalar
            sum = sum === undefined ? scalar : sum + scalar
    return sum

TypeScipt version

remove first element from array and return the array minus the first element

You can use array.slice(0,1) // First index is removed and array is returned.

How do I convert a list of ascii values to a string in python?

l = [83, 84, 65, 67, 75]

s = "".join([chr(c) for c in l])

print s

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

wt = tt - cpu tm.
Tt = cpu tm + wt.

Where wt is a waiting time and tt is turnaround time. Cpu time is also called burst time.

Replace all double quotes within String

The following regex will work for both:

  text = text.replaceAll("('|\")", "\\\\$1");

How to create and write to a txt file using VBA

Dim SaveVar As Object

Sub Main()

    Console.WriteLine("Enter Text")


    SaveVar = Console.ReadLine

    My.Computer.FileSystem.WriteAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt", "Text: " & SaveVar & ", ", True)


    Console.WriteLine("File Saved")


    Console.WriteLine(My.Computer.FileSystem.ReadAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt"))

End Sub()

How to convert a Kotlin source file to a Java source file

Java and Kotlin runs on Java Virtual Machine (JVM).

Converting a Kotlin file to Java file involves two steps i.e. compiling the Kotlin code to the JVM bytecode and then decompile the bytecode to the Java code.

Steps to convert your Kotlin source file to Java source file:

  1. Open your Kotlin project in the Android Studio.
  2. Then navigate to Tools -> Kotlin -> Show Kotlin Bytecode.

enter image description here

  1. You will get the bytecode of your Kotin file.
  2. Now click on the Decompile button to get your Java code from the bytecode

Is it possible to change the location of packages for NuGet?

  1. Create nuget.config in same directory where your solution file is, with following content:
<?xml version="1.0" encoding="utf-8"?>
    <add key="repositoryPath" value="packages" />

'packages' will be the folder where all packages will be restored.

  1. Close Visual studio solution and open it again.

Adjust plot title (main) position

To summarize and explain visually how it works. Code construction is as follows:

par(mar = c(3,2,2,1))
barplot(...all parameters...)
title("Title text", adj = 0.5, line = 0)


par(mar = c(low, left, top, right)) - margins of the graph area.

title("text" - title text
      adj  = from left (0) to right (1) with anything in between: 0.1, 0.2, etc...
      line = positive values move title text up, negative - down)

enter image description here

How to retrieve the dimensions of a view?

Even though the proposed solution works, it might not be the best solution for every case because based on the documentation for ViewTreeObserver.OnGlobalLayoutListener

Interface definition for a callback to be invoked when the global layout state or the visibility of views within the view tree changes.

which means it gets called many times and not always the view is measured (it has its height and width determined)

An alternative is to use ViewTreeObserver.OnPreDrawListener which gets called only when the view is ready to be drawn and has all of its measurements.

final TextView tv = (TextView)findViewById(;
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnPreDrawListener(new OnPreDrawListener() {

    public void onPreDraw() {
        // Your view will have valid height and width at this point


How to extract text from an existing docx file using python-docx

I had a similar issue so I found a workaround (remove hyperlink tags thanks to regular expressions so that only a paragraph tag remains). I posted this solution on BP

Replace part of a string with another string

With C++11 you can use std::regex like so:

#include <regex>
std::string string("hello $name");
string = std::regex_replace(string, std::regex("\\$name"), "Somename");

The double backslash is required for escaping an escape character.

Why Doesn't C# Allow Static Methods to Implement an Interface?

OK here is an example of needing a 'type method'. I am creating one of a set of classes based on some source XML. So I have a

  static public bool IsHandled(XElement xml)

function which is called in turn on each class.

The function should be static as otherwise we waste time creating inappropriate objects. As @Ian Boyde points out it could be done in a factory class, but this just adds complexity.

It would be nice to add it to the interface to force class implementors to implement it. This would not cause significant overhead - it is only a compile/link time check and does not affect the vtable.

However, it would also be a fairly minor improvement. As the method is static, I as the caller, must call it explicitly and so get an immediate compile error if it is not implemented. Allowing it to be specified on the interface would mean this error comes marginally earlier in the development cycle, but this is trivial compared to other broken-interface issues.

So it is a minor potential feature which on balance is probably best left out.

Excel VBA - Range.Copy transpose paste

Here's an efficient option that doesn't use the clipboard.

Sub transposeAndPasteRow(rowToCopy As Range, pasteTarget As Range)
    pasteTarget.Resize(rowToCopy.Columns.Count) = Application.WorksheetFunction.Transpose(rowToCopy.Value)
End Sub

Use it like this.

Sub test()
    Call transposeAndPasteRow(Worksheets("Sheet1").Range("A1:A5"), Worksheets("Sheet2").Range("A1"))
End Sub

List only stopped Docker containers

docker container list -f "status=exited"


docker container ls -f "status=exited"


 docker ps -f "status=exited"

Getting char from string at specified index

Getting one char from string at specified index

Dim pos As Integer
Dim outStr As String
pos = 2 
Dim outStr As String
outStr = Left(Mid("abcdef", pos), 1)


Open URL in Java to get the content

public class UrlContent{
    public static void main(String[] args) {

        URL url;

        try {
            // get URL content

            String a="http://localhost:8080/TestWeb/index.jsp";
            url = new URL(a);
            URLConnection conn = url.openConnection();

            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(
                               new InputStreamReader(conn.getInputStream()));

            String inputLine;
            while ((inputLine = br.readLine()) != null) {


        } catch (MalformedURLException e) {
        } catch (IOException e) {


Explicitly calling return in a function or not

return can increase code readability:

foo <- function() {
    if (a) return(a)       

How to fix date format in ASP .NET BoundField (DataFormatString)?

Formatting depends on the server's culture setting. If you use en-US culture, you can use Short Date Pattern like {0:d}

For example, it formats 6/15/2009 1:45:30 to 6/15/2009

You can check more formats from BoundField.DataFormatString

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

I had this same issue. Fortunately you can use Google Analytics with BitCode enabled, but it's a bit confusing due to how Google had set up their CocoaPods support.

There's actually 2 CocoaPods you can use:

  • 'Google/Analytics'
  • 'GoogleAnalytics'

The first one is the "latest" but it's tied to the greater Google pods so it does not support Bitcode. The second one is for Analytics only and does support BitCode. However because the latter does not include extra Google pods some of the instructions on how to set it up are incorrect.

You have to use the v2 method of setting up analytics:

// Inside AppDelegate:

// Optional: automatically send uncaught exceptions to Google Analytics.
GAI.sharedInstance().trackUncaughtExceptions = true

// Optional: set Google Analytics dispatch interval to e.g. 20 seconds.
GAI.sharedInstance().dispatchInterval = 20

// Create tracker instance.
let tracker = GAI.sharedInstance().trackerWithTrackingId("XX-XXXXXXXX-Y")

The rest of the Google analytics api you can use the v3 documentation (you don't need to use v2).

The 'Google/Analytics' cocoapod as of this writing still does not support BitCode. See here

Using AJAX to pass variable to PHP and retrieve those using AJAX again

Use dataType:"json" for json data

     url: 'ajax.php', //This is the current doc
     type: "POST",
     dataType:'json', // add json datatype to get json
     data: ({name: 145}),
     success: function(data){

Read Docs

Also in PHP

  $userAnswer = $_POST['name']; 
  $sql="SELECT * FROM <tablename> where color='".$userAnswer."'" ;
  // for first row only and suppose table having data
  echo json_encode($row);  // pass array in json_encode  

Multiple Python versions on the same machine?

I'm using Mac & the best way that worked for me is using pyenv!

The commands below are for Mac but pretty similar to Linux (see the links below)

#Install pyenv
brew update
brew install pyenv

Let's say you have python 3.6 as your primary version on your mac:

python --version 


Python <your current version>

Now Install python 3.7, first list all

pyenv install -l

Let's take 3.7.3:

pyenv install 3.7.3

Make sure to run this in the Terminal (add it to ~/.bashrc or ~/.zshrc):

export PATH="/Users/username/.pyenv:$PATH"
eval "$(pyenv init -)"

Now let's run it only on the opened terminal/shell:

pyenv shell 3.7.3

Now run

python --version


Python 3.7.3

And not less important unset it in the opened shell/iTerm:

pyenv shell --unset

You can run it globally or locally as well

Hide/Show components in react native

I needed to switch between two images. With conditional switching between them there was 5sec delay with no image displayed.

I'm using approach from downvoted amos answer. Posting as new answer because it's hard to put code into comment with proper formatting.

Render function:

<View style={styles.logoWrapper}>
    style={[styles.logo, loading ? styles.hidden : {}]}
    source={require('./logo.png')} />
    style={[styles.logo, loading ? {} : styles.hidden]}
    source={require('./logo_spin.gif')} />


var styles = StyleSheet.create({
  logo: {
    width: 200,
    height: 200,
  hidden: {
    width: 0,
    height: 0,


Spring-Security-Oauth2: Full authentication is required to access this resource

I had the same problem, but I solve this with the following class:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class OAuthSecurityConfiguration extends WebSecurityConfigurerAdapter {

    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();

    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();

Using jQuery UI sortable with HTML tables

You can call sortable on a <tbody> instead of on the individual rows.



$(function() {_x000D_
  $( "tbody" ).sortable();_x000D_
table {_x000D_
    border-spacing: collapse;_x000D_
    border-spacing: 0;_x000D_
td {_x000D_
    width: 50px;_x000D_
    height: 25px;_x000D_
    border: 1px solid black;_x000D_
<link href="//" rel="stylesheet">_x000D_
<script src="//"></script>_x000D_
<script src="//"></script>_x000D_
        <tr> _x000D_
            <td>9</td> _x000D_
        </tr>  _x000D_
    </tbody>    _x000D_

eclipse stuck when building workspace

I had same issue with my Eclipse and as a solution, I created new project, copied all resources manually (using windows copy/paste) to new project, deleted old project and that's it.

Sometimes, this happens due to improper System shutdown and Eclipse workspace started facing similar issues.

Hope it will work.

How to find duplicate records in PostgreSQL

In your case, because of the constraint you need to delete the duplicated records.

  1. Find the duplicated rows
  2. Organize them by created_at date - in this case I'm keeping the oldest
  3. Delete the records with USING to filter the right rows
WITH duplicated AS ( 
    SELECT id,
    FROM products 
    GROUP BY id 
    HAVING count(*) > 1), 
ordered AS ( 
        rank() OVER (partition BY ORDER BY p.created_at) AS rnk 
    FROM products o 
    JOIN     duplicated d ON = ), 
products_to_delete AS ( 
    SELECT id, 
    FROM   ordered 
    WHERE  rnk = 2
FROM products 
USING products_to_delete 
    AND products.created_at = products_to_delete.created_at;

Global Variable in app.js accessible in routes?

To make a global variable, just declare it without the var keyword. (Generally speaking this isn't best practice, but in some cases it can be useful - just be careful as it will make the variable available everywhere.)

Here's an example from visionmedia/screenshot-app

file app.js:

 * Module dependencies.

var express = require('express')
  , stylus = require('stylus')
  , redis = require('redis')
  , http = require('http');

app = express();

//... require() route files

file routes/main.js

//we can now access 'app' without redeclaring it or passing it in...

 * GET home page.

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


Singleton design pattern vs Singleton beans in Spring container

"singleton" in spring is using bean factory get instance, then cache it; which singleton design pattern is strictly, the instance can only be retrieved from static get method, and the object can never be publicly instantiated.

Foreign Key to multiple tables

You have a few options, all varying in "correctness" and ease of use. As always, the right design depends on your needs.

  • You could simply create two columns in Ticket, OwnedByUserId and OwnedByGroupId, and have nullable Foreign Keys to each table.

  • You could create M:M reference tables enabling both ticket:user and ticket:group relationships. Perhaps in future you will want to allow a single ticket to be owned by multiple users or groups? This design does not enforce that a ticket must be owned by a single entity only.

  • You could create a default group for every user and have tickets simply owned by either a true Group or a User's default Group.

  • Or (my choice) model an entity that acts as a base for both Users and Groups, and have tickets owned by that entity.

Heres a rough example using your posted schema:

create table dbo.PartyType
    PartyTypeId tinyint primary key,
    PartyTypeName varchar(10)

insert into dbo.PartyType
    values(1, 'User'), (2, 'Group');

create table dbo.Party
    PartyId int identity(1,1) primary key,
    PartyTypeId tinyint references dbo.PartyType(PartyTypeId),
    unique (PartyId, PartyTypeId)

CREATE TABLE dbo.[Group]
    ID int primary key,
    Name varchar(50) NOT NULL,
    PartyTypeId as cast(2 as tinyint) persisted,
    foreign key (ID, PartyTypeId) references Party(PartyId, PartyTypeID)

    ID int primary key,
    Name varchar(50) NOT NULL,
    PartyTypeId as cast(1 as tinyint) persisted,
    foreign key (ID, PartyTypeId) references Party(PartyID, PartyTypeID)

    ID int primary key,
    [Owner] int NOT NULL references dbo.Party(PartyId),
    [Subject] varchar(50) NULL

How to convert a list of numbers to jsonarray in Python

import json
row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
row_json = json.dumps(row)

CSS3 animate border color

You can try this also...

button {
  background: none;
  border: 0;
  box-sizing: border-box;
  margin: 1em;
  padding: 1em 2em;
  box-shadow: inset 0 0 0 2px #f45e61;
  color: #f45e61;
  font-size: inherit;
  font-weight: 700;
  vertical-align: middle;
  position: relative;
button::before, button::after {
  box-sizing: inherit;
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;

.draw {
  -webkit-transition: color 0.25s;
  transition: color 0.25s;
.draw::before, .draw::after {
  border: 2px solid transparent;
  width: 0;
  height: 0;
.draw::before {
  top: 0;
  left: 0;
.draw::after {
  bottom: 0;
  right: 0;
.draw:hover {
  color: #60daaa;
.draw:hover::before, .draw:hover::after {
  width: 100%;
  height: 100%;
.draw:hover::before {
  border-top-color: #60daaa;
  border-right-color: #60daaa;
  -webkit-transition: width 0.25s ease-out, height 0.25s ease-out 0.25s;
  transition: width 0.25s ease-out, height 0.25s ease-out 0.25s;
.draw:hover::after {
  border-bottom-color: #60daaa;
  border-left-color: #60daaa;
  -webkit-transition: border-color 0s ease-out 0.5s, width 0.25s ease-out 0.5s, height 0.25s ease-out 0.75s;
  transition: border-color 0s ease-out 0.5s, width 0.25s ease-out 0.5s, height 0.25s ease-out 0.75s;
<section class="buttons">
  <button class="draw">Draw</button>

Why do multiple-table joins produce duplicate rows?

This might sound like a really basic "DUH" answer, but make sure that the column you're using to Lookup from on the merging file is actually full of unique values!

I noticed earlier today that PowerQuery won't throw you an error (like in PowerPivot) and will happily allow you to run a Many-Many merge. This will result in multiple rows being produced for each record that matches with a non-unique value.

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

How can I fill out a Python string with spaces?

As of Python 3.6 you can just do

>>> strng = 'hi'
>>> f'{strng: <10}'

with literal string interpolation.

Or, if your padding size is in a variable, like this (thanks @Matt M.!):

>>> to_pad = 10
>>> f'{strng: <{to_pad}}'

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

All above not worked for me, but this was: Check that the name of Root element of class is exactly like the one from XML case sensitive.

How do I print the full value of a long string in gdb?

set print elements 0

From the GDB manual:

set print elements number-of-elements
Set a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the set print elements command. This limit also applies to the display of strings. When GDB starts, this limit is set to 200. Setting number-of-elements to zero means that the printing is unlimited.

How to install gdb (debugger) in Mac OSX El Capitan?

Install Homebrew first :

/usr/bin/ruby -e "$(curl -fsSL"

Then run this : brew install gdb

What does "The APR based Apache Tomcat Native library was not found" mean?

on debian 8 I fix it with installing libapr1-dev:

apt-get install libtcnative-1 libapr1-dev

Split Spark Dataframe string column into multiple columns

Here's another approach, in case you want split a string with a delimiter.

import pyspark.sql.functions as f

df = spark.createDataFrame([("1:a:2001",),("2:b:2002",),("3:c:2003",)],["value"])
|   value|

df_split =,":")).rdd.flatMap(
              lambda x: x).toDF(schema=["col1","col2","col3"])
|   1|   a|2001|
|   2|   b|2002|
|   3|   c|2003|

I don't think this transition back and forth to RDDs is going to slow you down... Also don't worry about last schema specification: it's optional, you can avoid it generalizing the solution to data with unknown column size.

Which browsers support <script async="async" />?

There's two parts to this question, really.

  1. Q: Which browsers support the "async" attribute on a script tag in markup?

    A: IE10p2+, Chrome 11+, Safari 5+, Firefox 3.6+

  2. Q: Which browsers support the new spec that defines behavior for the "async" property in JavaScript, on a dynamically created script element?

    A: IE10p2+, Chrome 12+, Safari 5.1+, Firefox 4+

As for Opera, they are very close to releasing a version which will support both types of async. I've been working with them closely on this, and it should come out soon (I hope!).

More info on ordered-async (aka, "async=false") can be found here:

Also, to test if a browser supports the new dynamic async property behavior:

HTML Mobile -forcing the soft keyboard to hide

I could not use some of the suggestions provided.

In my case I had Google Chrome being used to display an Oracle APEX Application. There were some very specific input fields that allowed you to start typing a value and a list of values would begin to be displayed and reduced as you became more specific in your typing. Once you selected the item from the list of available options, the focus would still be on the input field.

I found that my solution was easily accomplished with a custom event that throws a custom error like the following:

throw "throwing a custom error exits input and hides keyboard";

Deserialize a json string to an object in python

Another way is to simply pass the json string as a dict to the constructor of your object. For example your object is:

class Payload(object):
    def __init__(self, action, method, data, *args, **kwargs):
        self.action = action
        self.method = method = data

And the following two lines of python code will construct it:

j = json.loads(yourJsonString)
payload = Payload(**j)

Basically, we first create a generic json object from the json string. Then, we pass the generic json object as a dict to the constructor of the Payload class. The constructor of Payload class interprets the dict as keyword arguments and sets all the appropriate fields.

Table 'performance_schema.session_variables' doesn't exist

If, while using the mysql_upgrade -u root -p --force command You get this error:

Could not create the upgrade info file '/var/lib/mysql/mysql_upgrade_info' in the MySQL Servers datadir, errno: 13

just add the sudo before the command. That worked for me, and I solved my problem. So, it's: sudo mysql_upgrade -u root -p --force :)

What is logits, softmax and softmax_cross_entropy_with_logits?

One more thing that I would definitely like to highlight as logit is just a raw output, generally the output of last layer. This can be a negative value as well. If we use it as it's for "cross entropy" evaluation as mentioned below:

-tf.reduce_sum(y_true * tf.log(logits))

then it wont work. As log of -ve is not defined. So using o softmax activation, will overcome this problem.

This is my understanding, please correct me if Im wrong.

MySQL and PHP - insert NULL rather than empty string

Normally, you add regular values to mySQL, from PHP like this:

function addValues($val1, $val2) {
    db_open(); // just some code ot open the DB 
    $query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES ('$val1', '$val2')";
    $result = mysql_query($query);
    db_close(); // just some code to close the DB

When your values are empty/null ($val1=="" or $val1==NULL), and you want NULL to be added to SQL and not 0 or empty string, to the following:

function addValues($val1, $val2) {
    db_open(); // just some code ot open the DB 
    $query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
        (($val1=='')?"NULL":("'".$val1."'")) . ", ".
        (($val2=='')?"NULL":("'".$val2."'")) . 
    $result = mysql_query($query);
    db_close(); // just some code to close the DB

Note that null must be added as "NULL" and not as "'NULL'" . The non-null values must be added as "'".$val1."'", etc.

Hope this helps, I just had to use this for some hardware data loggers, some of them collecting temperature and radiation, others only radiation. For those without the temperature sensor I needed NULL and not 0, for obvious reasons ( 0 is an accepted temperature value also).

Is it possible to print a variable's type in standard C++?

In C++11, we have decltype. There is no way in standard c++ to display exact type of variable declared using decltype. We can use boost typeindex i.e type_id_with_cvr (cvr stands for const, volatile, reference) to print type like below.

#include <iostream>
#include <boost/type_index.hpp>

using namespace std;
using boost::typeindex::type_id_with_cvr;

int main() {
  int i = 0;
  const int ci = 0;
  cout << "decltype(i) is " << type_id_with_cvr<decltype(i)>().pretty_name() << '\n';
  cout << "decltype((i)) is " << type_id_with_cvr<decltype((i))>().pretty_name() << '\n';
  cout << "decltype(ci) is " << type_id_with_cvr<decltype(ci)>().pretty_name() << '\n';
  cout << "decltype((ci)) is " << type_id_with_cvr<decltype((ci))>().pretty_name() << '\n';
  cout << "decltype(std::move(i)) is " << type_id_with_cvr<decltype(std::move(i))>().pretty_name() << '\n';
  cout << "decltype(std::static_cast<int&&>(i)) is " << type_id_with_cvr<decltype(static_cast<int&&>(i))>().pretty_name() << '\n';
  return 0;

How to install Android app on LG smart TV?

LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.

jQuery - Getting form values for ajax POST

var username = $('#username').val();
var email= $('#email').val();
var password= $('#password').val();

When to use std::size_t?

Use std::size_t for indexing/counting C-style arrays.

For STL containers, you'll have (for example) vector<int>::size_type, which should be used for indexing and counting vector elements.

In practice, they are usually both unsigned ints, but it isn't guaranteed, especially when using custom allocators.

Responsive table handling in Twitter Bootstrap

There are many different things you can do when dealing with responsive tables.

I personally like this approach by Chris Coyier:

You can find many other alternatives here:

If you can leverage Bootstrap and get something quickly, you can simply use the class names ".hidden-phone" and ".hidden-tablet" to hide some rows but this approach might to be the best in many cases. More info (see "Responsive utility classes"):

How to find out the username and password for mysql database

One of valid JDBC url is


Check if page gets reloaded or refreshed in JavaScript

    var currpage    = window.location.href;
    var lasturl     = sessionStorage.getItem("last_url");

    if(lasturl == null || lasturl.length === 0 || currpage !== lasturl ){
        sessionStorage.setItem("last_url", currpage);
        alert("New page loaded");
        alert("Refreshed Page");  


" netsh wlan start hostednetwork " command not working no matter what I try

This was a real issue for me, and quite a sneaky problem to try and remedy...

The problem I had was that a module that was installed on my WiFi adapter was conflicting with the Microsoft Virtual Adapter (or whatever it's actually called).

To fix it:

  1. Hold the Windows Key + Push R
  2. Type: ncpa.cpl in to the box, and hit OK.
  3. Identify the network adapter you want to use for the hostednetwork, right-click it, and select Properties.
  4. You'll see a big box in the middle of the properties window, under the heading The connection uses the following items:. Look down the list for anything that seems out of the ordinary, and uncheck it. Hit OK.
  5. Try running the netsh wlan start hostednetwork command again.
  6. Repeat steps 4 and 5 as necessary.

In my case my adapter was running a module called SoftEther Lightweight Network Protocol, which I believe is used to help connect to VPN Gate VPN servers via the SoftEther software.

If literally nothing else works, then I'd suspect something similar to the problem I encountered, namely that a module on your network adapter is interfering with the hostednetwork aspect of your driver.

Is an empty href valid?

Indeed, you can leave it empty (W3 validator doesn't complain).

Taking the idea one step further: leave out the ="". The advantage of this is that the link isn't treated as an anchor to the current page.

<a href>sth</a>

SQL Inner join 2 tables with multiple column conditions and update

    T1.Inci = T2.Inci 
    T1.Brands = T2.Brands
    T1.Category= T2.Category
    T1.Date = T2.Date

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

What's the location of the JavaFX runtime JAR file, jfxrt.jar, on Linux?

On Ubuntu with OpenJDK, it installed in /usr/lib/jvm/default-java/jre/lib/ext/jfxrt.jar (technically its a symlink to /usr/share/java/openjfx/jre/lib/ext/jfxrt.jar, but it is probably better to use the default-java link)

Entity Framework Query for inner join

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

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

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

How to represent e^(-t^2) in MATLAB?

If t is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.

x = exp( -t.^2 )


x = exp( -t.*t )

How and when to use ‘async’ and ‘await’

On a higher level:

1) Async keyword enables the await and that's all it does. Async keyword does not run the method in a separate thread. The beginning f async method runs synchronously until it hits await on a time-consuming task.

2) You can await on a method that returns Task or Task of type T. You cannot await on async void method.

3) The moment main thread encounters await on time-consuming task or when the actual work is started, the main thread returns to the caller of the current method.

4) If the main thread sees await on a task that is still executing, it doesn't wait for it and returns to the caller of the current method. In this way, the application remains responsive.

5) Await on processing task, will now execute on a separate thread from the thread pool.

6) When this await task is completed, all the code below it will be executed by the separate thread

Below is the sample code. Execute it and check the thread id

using System;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncAwaitDemo
    class Program
        public static async void AsynchronousOperation()
            Console.WriteLine("Inside AsynchronousOperation Before AsyncMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId);
            //Task<int> _task = AsyncMethod();
            int count = await AsyncMethod();

            Console.WriteLine("Inside AsynchronousOperation After AsyncMethod Before Await, Thread Id: " + Thread.CurrentThread.ManagedThreadId);

            //int count = await _task;

            Console.WriteLine("Inside AsynchronousOperation After AsyncMethod After Await Before DependentMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId);


            Console.WriteLine("Inside AsynchronousOperation After AsyncMethod After Await After DependentMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId);

        public static async Task<int> AsyncMethod()
            Console.WriteLine("Inside AsyncMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId);
            int count = 0;

            await Task.Run(() =>
                Console.WriteLine("Executing a long running task which takes 10 seconds to complete, Thread Id: " + Thread.CurrentThread.ManagedThreadId);
                count = 10;

            Console.WriteLine("Completed AsyncMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId);

            return count;

        public static void DependentMethod(int count)
            Console.WriteLine("Inside DependentMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId + ". Total count is " + count);

        static void Main(string[] args)
            Console.WriteLine("Started Main method, Thread Id: " + Thread.CurrentThread.ManagedThreadId);


            Console.WriteLine("Completed Main method, Thread Id: " + Thread.CurrentThread.ManagedThreadId);



Easy way to turn JavaScript array into comma-separated list?

var array = ["Zero", "One", "Two"];
var s = array + [];
console.log(s); // => Zero,One,Two

How to convert int to char with leading zeros?

I found a good article here:

Padding a string with leading zeros

I've need to do this a lot of times when outputing a fixed length data export where for instance a numeric column is 9 characters long and you need to prefix with leading 0's.

What is the difference between DSA and RSA?


RSA encryption and decryption are commutative
hence it may be used directly as a digital signature scheme
given an RSA scheme {(e,R), (d,p,q)}
to sign a message M, compute:
S = M power d (mod R)
to verify a signature, compute:
M = S power e(mod R) = M power e.d(mod R) = M(mod R)

RSA can be used both for encryption and digital signatures, simply by reversing the order in which the exponents are used: the secret exponent (d) to create the signature, the public exponent (e) for anyone to verify the signature. Everything else is identical.

DSA (Digital Signature Algorithm)
DSA is a variant on the ElGamal and Schnorr algorithms. It creates a 320 bit signature, but with 512-1024 bit security again rests on difficulty of computing discrete logarithms has been quite widely accepted.

DSA Key Generation
firstly shared global public key values (p,q,g) are chosen:
choose a large prime p = 2 power L
where L= 512 to 1024 bits and is a multiple of 64
choose q, a 160 bit prime factor of p-1
choose g = h power (p-1)/q
for any h<p-1, h(p-1)/q(mod p)>1
then each user chooses a private key and computes their public key:
choose x<q
compute y = g power x(mod p)

DSA key generation is related to, but somewhat more complex than El Gamal. Mostly because of the use of the secondary 160-bit modulus q used to help speed up calculations and reduce the size of the resulting signature.

DSA Signature Creation and Verification

to sign a message M
generate random signature key k, k<q
r = (g power k(mod p))(mod q)
s = k-1.SHA(M)+ x.r (mod q)
send signature (r,s) with message

to verify a signature, compute:
w = s-1(mod q)
u1= (SHA(M).w)(mod q)
u2= r.w(mod q)
v = (g power u1.y power u2(mod p))(mod q)
if v=r then the signature is verified

Signature creation is again similar to ElGamal with the use of a per message temporary signature key k, but doing calc first mod p, then mod q to reduce the size of the result. Note that the use of the hash function SHA is explicit here. Verification also consists of comparing two computations, again being a bit more complex than, but related to El Gamal.
Note that nearly all the calculations are mod q, and hence are much faster.
But, In contrast to RSA, DSA can be used only for digital signatures

DSA Security
The presence of a subliminal channel exists in many schemes (any that need a random number to be chosen), not just DSA. It emphasises the need for "system security", not just a good algorithm.

How to force browser to download file?

You are setting the response headers after writing the contents of the file to the output stream. This is quite late in the response lifecycle to be setting headers. The correct sequence of operations should be to set the headers first, and then write the contents of the file to the servlet's outputstream.

Therefore, your method should be written as follows (this won't compile as it is a mere representation):

response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition","attachment; filename=\"" + "xxx\"");//fileName);
File f= new File(fileName);

InputStream in = new FileInputStream(f);
BufferedInputStream bin = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bin);

while(din.available() > 0){

The reason for the failure is that it is possible for the actual headers sent by the servlet would be different from what you are intending to send. After all, if the servlet container does not know what headers (which appear before the body in the HTTP response), then it may set appropriate headers to ensure that the response is valid; setting the headers after the file has been written is therefore futile and redundant as the container might have already set the headers. You could confirm this by looking at the network traffic using Wireshark or a HTTP debugging proxy like Fiddler or WebScarab.

You may also refer to the Java EE API documentation for ServletResponse.setContentType to understand this behavior:

Sets the content type of the response being sent to the client, if the response has not been committed yet. The given content type may include a character encoding specification, for example, text/html;charset=UTF-8. The response's character encoding is only set from the given content type if this method is called before getWriter is called.

This method may be called repeatedly to change content type and character encoding. This method has no effect if called after the response has been committed.


Bootstrap 4 img-circle class not working

Now the class is this

 <img src="img/img5.jpg" width="200px" class="rounded-circle float-right">

if checkbox is checked, do this

It may happen that "this.checked" is always "on". Therefore, I recommend:

$('#checkbox').change(function() {
  if ($(this).is(':checked')) {
  } else {

Get yesterday's date using Date

   Calendar cal = Calendar.getInstance();
   DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
   System.out.println("Today's date is "+dateFormat.format(cal.getTime()));

   cal.add(Calendar.DATE, -1);
   System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));  

Use Calender Api

How to connect to Oracle 11g database remotely

# . /u01/app/oracle/product/11.2.0/xe/bin/  

#  sqlplus /nolog  

SQL> connect sys/password as sysdba                                           


SQL> CONNECT sys/password@hostname:1521 as sysdba

converting a base 64 string to an image and saving it

Here is what I ended up going with.

    private void SaveByteArrayAsImage(string fullOutputPath, string base64String)
        byte[] bytes = Convert.FromBase64String(base64String);

        Image image;
        using (MemoryStream ms = new MemoryStream(bytes))
            image = Image.FromStream(ms);

        image.Save(fullOutputPath, System.Drawing.Imaging.ImageFormat.Png);

Escape double quote character in XML

If you just need to try something out quickly, here's a quick and dirty solution. Use single quotes for the attribute value:

<parameter name='Quote = " '>

Hidden TextArea

Set CSS display to none for textarea

<textarea name="hide" style="display:none;"></textarea>

Add and remove multiple classes in jQuery

Add multiple classes:

$("p").addClass("class1 class2 class3");

or in cascade:


Very similar also to remove more classes:

$("p").removeClass("class1 class2 class3");

or in cascade:


Bootstrap with jQuery Validation Plugin

I used this for radio's:

    if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
    else if (element.parent(".input-group").length) {
    else {

this way the error is displayed under last radio option.

how to create inline style with :before and :after

I resolved a similar problem by border-color: inherit

, see:

<li style="border-color: <?php echo $hex ?>;">...</li>

li {
    border-width: 0;

li:before {
    content: '';
    display: inline-block;
    float: none;
    margin-right: 10px;
    border-width: 4px;
    border-style: solid;
    border-color: inherit;

jQuery has deprecated synchronous XMLHTTPRequest

It was mentioned as a comment by @henri-chan, but I think it deserves some more attention:

When you update the content of an element with new html using jQuery/javascript, and this new html contains <script> tags, those are executed synchronously and thus triggering this error. Same goes for stylesheets.

You know this is happening when you see (multiple) scripts or stylesheets being loaded as XHR in the console window. (firefox).

How to build x86 and/or x64 on Windows from command line with CMAKE?



// x86

// x64

Difference between java HH:mm and hh:mm on SimpleDateFormat

Use the built-in localized formats

If this is for showing a time of day to a user, then in at least 19 out of 20 you don’t need to care about kk, HH nor hh. I suggest that you use something like this:

    DateTimeFormatter defaultTimeFormatter
            = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
    System.out.format("%s: %s%n",
            Locale.getDefault(), LocalTime.MIN.format(defaultTimeFormatter));

The point is that it gives different output in different default locales. For example:

en_SS: 12:00 AM
fr_BL: 00:00
ps_AF: 0:00
es_CO: 12:00 a.m.

The localized formats have been designed to conform with the expectations of different cultures. So they generally give the user a better experience and they save you of writing a format pattern string, which is always error-prone.

I furthermore suggest that you don’t use SimpleDateFormat. That class is notoriously troublesome and fortunately long outdated. Instead I use java.time, the modern Java date and time API. It is so much nicer to work with.

Four pattern letters for hour: H, h, k and K

Of course if you need to parse a string with a specified format, and also if you have a very specific formatting requirement, it’s good to use a format pattern string. There are actually four different pattern letters to choose from for hour (quoted from the documentation):

  Symbol  Meaning                     Presentation      Examples
  ------  -------                     ------------      -------
   h       clock-hour-of-am-pm (1-12)  number            12
   K       hour-of-am-pm (0-11)        number            0
   k       clock-hour-of-day (1-24)    number            24
   H       hour-of-day (0-23)          number            0

In practice H and h are used. As far as I know k and K are not (they may just have been included for the sake of completeness). But let’s just see them all in action:

    DateTimeFormatter timeFormatter
            = DateTimeFormatter.ofPattern("hh:mm a  HH:mm  kk:mm  KK:mm a", Locale.ENGLISH);
    System.out.println(LocalTime.of(0, 0).format(timeFormatter));
    System.out.println(LocalTime.of(1, 15).format(timeFormatter));
    System.out.println(LocalTime.of(11, 25).format(timeFormatter));
    System.out.println(LocalTime.of(12, 35).format(timeFormatter));
    System.out.println(LocalTime.of(13, 40).format(timeFormatter));
12:00 AM  00:00  24:00  00:00 AM
01:15 AM  01:15  01:15  01:15 AM
11:25 AM  11:25  11:25  11:25 AM
12:35 PM  12:35  12:35  00:35 PM
01:40 PM  13:40  13:40  01:40 PM

If you don’t want the leading zero, just specify one pattern letter, that is h instead of hh or H instead of HH. It will still accept two digits when parsing, and if a number to be printed is greater than 9, two digits will still be printed.


Javascript: How to check if a string is empty?

This should work:

if (variable === "") {


What is Func, how and when is it used

Aforementioned answers are great, just putting few points I see might be helpful:

  • Func is built-in delegate type

  • Func delegate type must return a value. Use Action delegate if no return type needed.

  • Func delegate type can have zero to 16 input parameters.

  • Func delegate does not allow ref and out parameters.

  • Func delegate type can be used with an anonymous method or lambda expression.

    Func<int, int, int> Sum = (x, y) => x + y;

rotate image with css

The trouble looks like the image isn't square and the browser adjusts as such. After rotation ensure the dimensions are retained by changing the image margin.

.imagetest img {
  transform: rotate(270deg);
  margin: 10px 0px;

The amount will depend on the difference in height x width of the image. You may also need to add display:inline-block; or display:block to get it to recognize the margin parameter.

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

1.a. Add following in applicationContext-mvc.xml

xmlns:mvc="" xsi:schemaLocation="

  1. add jackson library

php mail setup in xampp

Unless you have a mail server set up on your local computer, setting SMTP = localhost won't have any effect.

In days gone by (long ago), it was sufficient to set the value of SMTP to the address of your ISP's SMTP server. This now rarely works because most ISPs insist on authentication with a username and password. However, the PHP mail() function doesn't support SMTP authentication. It's designed to work directly with the mail transport agent of the local server.

You either need to set up a local mail server or to use a PHP classs that supports SMTP authentication, such as Zend_Mail or PHPMailer. The simplest solution, however, is to upload your mail processing script to your remote server.

How can I center text (horizontally and vertically) inside a div block?

Adjusting line height to get the vertical alignment.

line-height: 90px;

What does the "@" symbol do in Powershell?

While the above responses provide most of the answer it is useful--even this late to the question--to provide the full answer, to wit:

Array sub-expression (see about_arrays)

Forces the value to be an array, even if a singleton or a null, e.g. $a = @(ps | where name -like 'foo')

Hash initializer (see about_hash_tables)

Initializes a hash table with key-value pairs, e.g. $HashArguments = @{ Path = "test.txt"; Destination = "test2.txt"; WhatIf = $true }

Splatting (see about_splatting)

Let's you invoke a cmdlet with parameters from an array or a hash-table rather than the more customary individually enumerated parameters, e.g. using the hash table just above, Copy-Item @HashArguments

Here strings (see about_quoting_rules)

Let's you create strings with easily embedded quotes, typically used for multi-line strings, e.g.:

$data = @"
line one
line two
something "quoted" here

Because this type of question (what does 'x' notation mean in PowerShell?) is so common here on StackOverflow as well as in many reader comments, I put together a lexicon of PowerShell punctuation, just published on Read all about @ as well as % and # and $_ and ? and more at The Complete Guide to PowerShell Punctuation. Attached to the article is this wallchart that gives you everything on a single sheet: enter image description here

How to create a scrollable Div Tag Vertically?

Well, your code worked for me (running Chrome 5.0.307.9 and Firefox 3.5.8 on Ubuntu 9.10), though I switched

overflow-y: scroll;


overflow-y: auto;

Demo page over at:

xhtml below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">

<html xmlns="" xml:lang="en" lang="en">

    <META http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title>Div in table</title>
    <link rel="stylesheet" type="text/css" href="css/stylesheet.css" />

        <style type="text/css" media="all">

        th      {border-bottom: 2px solid #ccc; }

        th,td       {padding: 0.5em 1em; 
                margin: 0;
                border-collapse: collapse;

        tr td:first-child
                {border-right: 2px solid #ccc; } 

        td > div    {width: 249px;
                height: 299px;
                overflow-y: auto;

    <script type="text/javascript" src="js/jquery.js"></script>

    <script type="text/javascript">






            <tr><th>This is column one</th><th>This is column two</th><th>This is column three</th>

            <tr><td>This is row one</td><td>data point 2.1</td><td>data point 3.1</td>
            <tr><td>This is row two</td><td>data point 2.2</td><td>data point 3.2</td>
            <tr><td>This is row three</td><td>data point 2.3</td><td>data point 3.3</td>
            <tr><td>This is row four</td><td><div><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies mattis dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum a accumsan purus. Vivamus semper tempus nisi et convallis. Aliquam pretium rutrum lacus sed auctor. Phasellus viverra elit vel neque lacinia ut dictum mauris aliquet. Etiam elementum iaculis lectus, laoreet tempor ligula aliquet non. Mauris ornare adipiscing feugiat. Vivamus condimentum luctus tortor venenatis fermentum. Maecenas eu risus nec leo vehicula mattis. In nisi nibh, fermentum vitae tincidunt non, mattis eu metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc vel est purus. Ut accumsan, elit non lacinia porta, nibh magna pretium ligula, sed iaculis metus tortor aliquam urna. Duis commodo tincidunt aliquam. Maecenas in augue ut ligula sodales elementum quis vitae risus. Vivamus mollis blandit magna, eu fringilla velit auctor sed.</p></div></td><td>data point 3.4</td>
            <tr><td>This is row five</td><td>data point 2.5</td><td>data point 3.5</td>
            <tr><td>This is row six</td><td>data point 2.6</td><td>data point 3.6</td>
            <tr><td>This is row seven</td><td>data point 2.7</td><td>data point 3.7</td>





How to reference a file for variables using Bash?

If the variables are being generated and not saved to a file you cannot pipe them in into source. The deceptively simple way to do it is this:

some command | xargs

Creating custom function in React component

You can create functions in react components. It is actually regular ES6 class which inherits from React.Component. Just be careful and bind it to the correct context in onClick event:

export default class Archive extends React.Component { 

    saySomething(something) {

    handleClick(e) {
        this.saySomething("element clicked");

    componentDidMount() {
        this.saySomething("component did mount");

    render() {
        return <button onClick={this.handleClick.bind(this)} value="Click me" />;

Jenkins Git Plugin: How to build specific tag?

Adding my two cents here since I have not seen an answer that uses the option "Build with parameters" in Jenkins.

Here I am using Jenkins CI browser console for project starwars_api and I was able to build directly with "Build with parameters" with value refs/tags/tag-name

  1. choose the "build with parameters" option.
  2. add value in the box as "refs/tags/tag_142" (tag_name = tag_142 for my example)

build with ref tag name

What's the simplest way to extend a numpy array in 2 dimensions?

Another elegant solution to the first question may be the insert command:

p = np.array([[1,2],[3,4]])
p = np.insert(p, 2, values=0, axis=1) # insert values before column 2

Leads to:

array([[1, 2, 0],
       [3, 4, 0]])

insert may be slower than append but allows you to fill the whole row/column with one value easily.

As for the second question, delete has been suggested before:

p = np.delete(p, 2, axis=1)

Which restores the original array again:

array([[1, 2],
       [3, 4]])

How to define the css :hover state in a jQuery selector?

It's too late, however the best example, how to add pseudo element in jQuery style

 $("a.dummy").css({"background":"#003d79","color":"#fff","padding": "5px 10px","border-radius": "3px","text-decoration":"none"});_x000D_
 $("a.dummy").hover(function() {_x000D_
<script src=""></script>_x000D_
<a class="dummy" href="javascript:void()">Just Link</a>

The application has stopped unexpectedly: How to Debug?

  1. From the Home screen, press the Menu key.
  2. List item
  3. Touch Settings.
  4. Touch Applications.
  5. Touch Manage Applications.
  6. Touch All.
  7. Select the application that is having issues.
  8. Touch Clear data and Clear cache if they are available. This resets the app as if it was new, and may delete personal data stored in the app.

How do I strip all spaces out of a string in PHP?

Do you just mean spaces or all whitespace?

For just spaces, use str_replace:

$string = str_replace(' ', '', $string);

For all whitespace (including tabs and line ends), use preg_replace:

$string = preg_replace('/\s+/', '', $string);

(From here).

jQuery, get ID of each element in a class using .each?

Try this, replacing .myClassName with the actual name of the class (but keep the period at the beginning).

$('.myClassName').each(function() {
    alert( );

So if the class is "test", you'd do $('.test').each(func....

This is the specific form of .each() that iterates over a jQuery object.

The form you were using iterates over any type of collection. So you were essentially iterating over an array of characters t,e,s,t.

Using that form of $.each(), you would need to do it like this:

$.each($('.myClassName'), function() {
    alert( );

...which will have the same result as the example above.

pandas three-way joining multiple dataframes on columns

The three dataframes are

enter image description here

enter image description here

Let's merge these frames using nested pd.merge

enter image description here

Here we go, we have our merged dataframe.

Happy Analysis!!!

Spring MVC - HttpMediaTypeNotAcceptableException


You've got this Spring @RestController and mapped a URL that contains an email as part of the URL path. You cunningly worked around the dot truncation issue [1] and you are ready to roll. And suddenly, on some URLs, Spring will return a 406 [2] which says that the browser requested a certain content type and Spring can't serialize the response to that content type. The point is, you've been doing Spring applications for years and you did all the MVC declarations right and you included Jackson and basically you are stuck. Even worse, it will spit that error out only on some emails in the URL path, most notably those ending in a ".com" domain.

@RequestMapping(value = "/agenda/{email:.+}", method = RequestMethod.GET)
public List<AgendaEntryDTO> checkAgenda(@PathVariable("email") String email)

The issue [3] is quite tricky: the application server performs some content negotiation and convinces Spring that the browser requested a "application/x-msdownload" content, despite that occurring nowhere in the request the browser actually submitted.

The solution is to specify a content negotiation manager for the web application context:

<mvc:annotation-driven enable-matrix-variables="true"
    content-negotiation-manager="contentNegotiationManager" />
<bean id="contentNegotiationManager"
    <property name="defaultContentType" value="application/json" />
    <property name="favorPathExtension" value="false" />
    <property name="favorParameter" value="false" />
    <property name="parameterName" value="mediaType" />
    <property name="ignoreAcceptHeader" value="false" />
    <property name="useJaf" value="false" />

foreach with index

No, there is not.

As other people have shown, there are ways to simulate Ruby's behavior. But it is possible to have a type that implements IEnumerable that does not expose an index.

Best way to "push" into C# array

array.push is like List<T>.Add. .NET arrays are fixed-size so you can't actually add a new element. All you can do is create a new array that is one element larger than the original and then set that last element, e.g.

Array.Resize(ref myArray, myArray.Length + 1);
myArray[myArray.GetUpperBound(0)] = newValue;


I'm not sure that this answer actually applies given this edit to the question:

The crux of the matter is that the element needs to be added into the first empty slot in an array, lie a Java push function would do.

The code I provided effectively appends an element. If the aim is to set the first empty element then you could do this:

int index = Array.IndexOf(myArray, null);

if (index != -1)
    myArray[index] = newValue;


Here's an extension method that encapsulates that logic and returns the index at which the value was placed, or -1 if there was no empty element. Note that this method will work for value types too, treating an element with the default value for that type as empty.

public static class ArrayExtensions
    public static int Push<T>(this T[] source, T value)
        var index = Array.IndexOf(source, default(T));

        if (index != -1)
            source[index] = value;

        return index;

Table cell widths - fixing width, wrapping/truncating long words

Stack Overflow has solved a similar problem with long lines of code by using a DIV and having overflow-x:auto. CSS can't break up words for you.

Unable to install Android Studio in Ubuntu

Checkout this page

If you are running a 64-bit distribution on your development machine, you need to install additional packages first. For Ubuntu 13.10 (Saucy Salamander) and above, install the libncurses5:i386, libstdc++6:i386, and zlib1g:i386 packages using apt-get:

sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386

How does Python's super() work with multiple inheritance?

Another not yet covered point is passing parameters for initialization of classes. Since the destination of super depends on the subclass the only good way to pass parameters is packing them all together. Then be careful to not have the same parameter name with different meanings.


class A(object):
    def __init__(self, **kwargs):

class B(A):
    def __init__(self, **kwargs):
        print('B.__init__ {}'.format(kwargs['x']))

class C(A):
    def __init__(self, **kwargs):
        print('C.__init__ with {}, {}'.format(kwargs['a'], kwargs['b']))

class D(B, C): # MRO=D, B, C, A
    def __init__(self):
        super().__init__(a=1, b=2, x=3)



[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
B.__init__ 3
C.__init__ with 1, 2

Calling the super class __init__ directly to more direct assignment of parameters is tempting but fails if there is any super call in a super class and/or the MRO is changed and class A may be called multiple times, depending on the implementation.

To conclude: cooperative inheritance and super and specific parameters for initialization aren't working together very well.

Remote debugging Tomcat with Eclipse

First of all, if you open catalina.bat with text editor, you see that: "Do not set the variables in this script....." So never change it in that script, instead you can do below steps:

  1. It advices you to create a new bat file with name "setenv.bat".
  2. Then set 2 variables in that bat file such as:

    set CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"

    set JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"

  3. Lastly run that at cmd that: "catalina.bat jpda start"

  4. In IDE, create remote debug configuration and set host to related server ip and port to 8000.

Parse DateTime string in JavaScript

We use this code to check if the string is a valid date

var dt = new Date(txtDate.value)
if (isNaN(dt))

show icon in actionbar/toolbar with AppCompat-v7 21

This worked for me:

    getSupportActionBar().setDisplayShowTitleEnabled(false); //optional

as well as:

    getSupportActionBar().setIcon(R.drawable.ic_logo); //also displays wide logo
    getSupportActionBar().setDisplayShowTitleEnabled(false); //optional

time.sleep -- sleeps thread or process?

Only the thread unless your process has a single thread.

MongoDb query condition on comparing 2 fields

If your query consists only of the $where operator, you can pass in just the JavaScript expression:

db.T.find("this.Grade1 > this.Grade2");

For greater performance, run an aggregate operation that has a $redact pipeline to filter the documents which satisfy the given condition.

The $redact pipeline incorporates the functionality of $project and $match to implement field level redaction where it will return all documents matching the condition using $$KEEP and removes from the pipeline results those that don't match using the $$PRUNE variable.

Running the following aggregate operation filter the documents more efficiently than using $where for large collections as this uses a single pipeline and native MongoDB operators, rather than JavaScript evaluations with $where, which can slow down the query:

        "$redact": {
            "$cond": [
                { "$gt": [ "$Grade1", "$Grade2" ] },

which is a more simplified version of incorporating the two pipelines $project and $match:

        "$project": {
            "isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] },
            "Grade1": 1,
            "Grade2": 1,
            "OtherFields": 1,
    { "$match": { "isGrade1Greater": 1 } }

With MongoDB 3.4 and newer:

        "$addFields": {
            "isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] }
    { "$match": { "isGrade1Greater": 1 } }

Plot correlation matrix using pandas

If you dataframe is df you can simply use:

import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(15, 10))
sns.heatmap(df.corr(), annot=True)

how to write procedure to insert data in to the table in phpmyadmin?

This method work for me:


Android view layout_width - how to change programmatically?

try using

View view_instance = (View)findViewById(;

use Layoutparams to do so where you can set width and height like below.

LayoutParams lp = new LayoutParams(10,LayoutParams.wrap_content);

How can I check if a string only contains letters in Python?

You can leverage regular expressions.

>>> import re
>>> pattern = re.compile("^[a-zA-Z]+$")
>>> pattern.match("hello")
<_sre.SRE_Match object; span=(0, 5), match='hello'>
>>> pattern.match("hel7lo")

The match() method will return a Match object if a match is found. Otherwise it will return None.

An easier approach is to use the .isalpha() method

>>> "Hello".isalpha()
>>> "Hel7lo".isalpha()

isalpha() returns true if there is at least 1 character in the string and if all the characters in the string are alphabets.

How to center absolute div horizontally using CSS?

Flexbox? You can use flexbox.

.box {_x000D_
  display: -ms-flexbox;_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-justify-content: center;_x000D_
  justify-content: center;_x000D_
.box div {_x000D_
  border:1px solid grey;_x000D_
  flex: 0 1 auto;_x000D_
  align-self: auto;_x000D_
  background: grey;_x000D_
<div class="box">_x000D_
  <div class="A">I'm horizontally centered.</div>_x000D_

Oracle Date datatype, transformed to 'YYYY-MM-DD HH24:MI:SS TMZ' through SQL

to convert a TimestampTZ in oracle, you do

TO_TIMESTAMP_TZ('2012-10-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') 
  at time zone 'region'

see here:

and here for regions:


SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

09-APR-13 CST
09-APR-13 -05:00

SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-03-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

09-MAR-13 CST
09-MAR-13 -05:00

SQL> select a, sys_extract_utc(a), a at time zone 'America/Los_Angeles' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

09-APR-13 CST

Retrieve column values of the selected row of a multicolumn Access listbox

Use listboxControl.Column(intColumn,intRow). Both Column and Row are zero-based.

adb server version doesn't match this client

Ensure that there are no other adb processes running

There may be more than one adb process running on the system. Tools such as the Android Reverse Tether may use their own version of the adb tool, hence the version in memory may conflict with the version run from the command line (via the path variable).


In Windows, press CTL+Shift+ESC to access Task Manager, sort in the Image Name column, then kill all instances of adb.exe by right-clicking, and choosing End Process. Note that there are multiple instances of adb.exe below:

Multiple adb.exe instances - how to kill

Linux (Android)

In a Linux environment, just use the kill -9 command. Something like this worked on an Android device running adb (use ps output, search using grep for a process starting with adb, get the Process ID from the adb process(es), and send that ID to the kill -9 command):

kill -9  $(ps  | grep "S adb" | busybox awk '{print $2}')

Then, restart adb

Once the adb processes - and thus conflicts - are resolved, then retry running adb from the command-line again:

adb start-server

Getting "type or namespace name could not be found" but everything seems ok?

In my case, adding the dll as a reference gave the type or namespace name could not be found error. However, copying and pasting the dll file directly in bin folder resolved the error.

No idea why this worked.

docker unauthorized: authentication required - upon push with successful login

Though the standard process is to login and then push to docker registry, trick to get over this particular problem is to login by providing username and password in same line.

So :

docker login -u xxx -p yyy 
docker push



docker login 
username : xxx
password : yyy
Login Succeeded

docker push


ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
var result = => ({ value:, text: }));_x000D_

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

If you are using AS 3.1 the new build graphical console isn't very helpful for finding out the source of the problem.

you need to click on toggle view and see the logs in text format to see the error and if needed to Run with --stacktrace

enter image description here

How to automatically convert strongly typed enum into int?

#include <cstdlib>
#include <cstdio>
#include <cstdint>

#include <type_traits>

namespace utils

namespace details

template< typename E >
using enable_enum_t = typename std::enable_if< std::is_enum<E>::value, 
                                               typename std::underlying_type<E>::type 

}   // namespace details

template< typename E >
constexpr inline details::enable_enum_t<E> underlying_value( E e )noexcept
    return static_cast< typename std::underlying_type<E>::type >( e );

template< typename E , typename T>
constexpr inline typename std::enable_if< std::is_enum<E>::value &&
                                          std::is_integral<T>::value, E
 to_enum( T value ) noexcept 
     return static_cast<E>( value );

} // namespace utils

int main()
    enum class E{ a = 1, b = 3, c = 5 };

    constexpr auto a = utils::underlying_value(E::a);
    constexpr E    b = utils::to_enum<E>(5);
    constexpr auto bv = utils::underlying_value(b);

    printf("a = %d, b = %d", a,bv);
    return 0;

The best way to calculate the height in a binary search tree? (balancing an AVL-tree)

This BFS-like solution is pretty straightforward. Simply jumps levels one-by-one.

def getHeight(self,root, method='links'):
    c_node = root
    cur_lvl_nodes = [root]
    nxt_lvl_nodes = []
    height = {'links': -1, 'nodes': 0}[method]

    while(cur_lvl_nodes or nxt_lvl_nodes):
        for c_node in cur_lvl_nodes:
            for n_node in filter(lambda x: x is not None, [c_node.left, c_node.right]):

        cur_lvl_nodes = nxt_lvl_nodes
        nxt_lvl_nodes = []
        height += 1

    return height

How to empty/destroy a session in rails?

To clear only certain parameters, you can use:

[:param1, :param2, :param3].each { |k| session.delete(k) }

checking memory_limit in PHP

very old post. but i'll just leave this here:

/* converts a number with byte unit (B / K / M / G) into an integer */
function unitToInt($s)
    return (int)preg_replace_callback('/(\-?\d+)(.?)/', function ($m) {
        return $m[1] * pow(1024, strpos('BKMG', $m[2]));
    }, strtoupper($s));

$mem_limit = unitToInt(ini_get('memory_limit'));

Sending an Intent to browser to open specific URL

Use following snippet in your code

Intent newIntent = new Intent(Intent.ACTION_VIEW, 

Use This link

How to initialize log4j properly?

I've created file in resources folder next to hibernate.cfg.xml file and filled it with text below:

log4j.rootLogger=INFO, CONSOLE

log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}:%L] %m%n

now I got rid of warnings and errors

'Property does not exist on type 'never'

if you're receiving the error in parameter, so keep any or any[] type of input like below

getOptionLabel={(option: any) => option!.name}
    getOptionLabel={(option: any) => option!.name}

Efficiently convert rows to columns in sql server

There are several ways that you can transform data from multiple rows into columns.


In SQL Server you can use the PIVOT function to transform the data from rows to columns:

select Firstname, Amount, PostalCode, LastName, AccountNumber
  select value, columnname
  from yourtable
) d
  for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;

See Demo.

Pivot with unknown number of columnnames

If you have an unknown number of columnnames that you want to transpose, then you can use dynamic SQL:

    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName) 
                    from yourtable
                    group by ColumnName, id
                    order by id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 

set @query = N'SELECT ' + @cols + N' from 
                select value, ColumnName
                from yourtable
            ) x
                for ColumnName in (' + @cols + N')
            ) p '

exec sp_executesql @query;

See Demo.

Using an aggregate function

If you do not want to use the PIVOT function, then you can use an aggregate function with a CASE expression:

  max(case when columnname = 'FirstName' then value end) Firstname,
  max(case when columnname = 'Amount' then value end) Amount,
  max(case when columnname = 'PostalCode' then value end) PostalCode,
  max(case when columnname = 'LastName' then value end) LastName,
  max(case when columnname = 'AccountNumber' then value end) AccountNumber
from yourtable

See Demo.

Using multiple joins

This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:

select fn.value as FirstName,
  a.value as Amount,
  pc.value as PostalCode,
  ln.value as LastName,
  an.value as AccountNumber
from yourtable fn
left join yourtable a
  on fn.somecol = a.somecol
  and a.columnname = 'Amount'
left join yourtable pc
  on fn.somecol = pc.somecol
  and pc.columnname = 'PostalCode'
left join yourtable ln
  on fn.somecol = ln.somecol
  and ln.columnname = 'LastName'
left join yourtable an
  on fn.somecol = an.somecol
  and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'

Convert integer to class Date

You can use ymd from lubridate

#[1] "2008-11-01"

Or anytime::anydate

#[1] "2008-11-01"

What is the difference between CSS and SCSS?

css has variables as well. You can use them like this:

--primaryColor: #ffffff;
--width: 800px;

body {
    width: var(--width);
    color: var(--primaryColor);
    width: var(--width);
    background: var(--primaryColor);

Deleting multiple columns based on column names in Pandas

You can do this in one line and one go:

df.drop([col for col in df.columns if "Unnamed" in col], axis=1, inplace=True)

This involves less moving around/copying of the object than the solutions above.

How to state in requirements.txt a direct github source

I'm finding that it's kind of tricky to get pip3 (v9.0.1, as installed by Ubuntu 18.04's package manager) to actually install the thing I tell it to install. I'm posting this answer to save anyone's time who runs into this problem.

Putting this into a requirements.txt file failed:


By "failed" I mean that while it downloaded the code from Git, it ended up installing the original version of the code, as found on PyPi, instead of the code in the repo on that branch.

However, installing the commmit instead of the branch name works:


Ansible: Store command's stdout in new variable?

In case than you want to store a complex command to compare text result, for example to compare the version of OS, maybe this can help you:

       - shell: echo $(cat /etc/issue | awk {'print $7'})
         register: echo_content

       - shell: echo "It works"
         when: echo_content.stdout == "12"
         register: out
       - debug: var=out.stdout_lines

How to set only time part of a DateTime variable in C#

I'm not sure exactly what you're trying to do but you can set the date/time to exactly what you want in a number of ways...

You can specify 12/25/2010 4:58 PM by using

DateTime myDate = Convert.ToDateTime("2010-12-25 16:58:00");

OR if you have an existing datetime construct , say 12/25/2010 (and any random time) and you want to set it to 12/25/2010 4:58 PM, you could do so like this:

DateTime myDate = ExistingTime.Date.AddHours(16).AddMinutes(58);

The ExistingTime.Date will be 12/25 at midnight, and you just add hours and minutes to get it to the time you want.

Why does viewWillAppear not get called when an app comes back from the background?

Just trying to make it as easy as possible see code below:

- (void)viewDidLoad
   [self appWillEnterForeground]; //register For Application Will enterForeground

- (id)appWillEnterForeground{ //Application will enter foreground.

    [[NSNotificationCenter defaultCenter] addObserver:self
    return self;

-(void) allFunctions{ //call any functions that need to be run when application will enter foreground 
    NSLog(@"calling all functions...application just came back from foreground");


Run function in script from command line (Node JS)

No comment on why you want to do this, or what might be a more standard practice: here is a solution to your question.... Keep in mind that the type of quotes required by your command line may vary.

In your db.js, export the init function. There are many ways, but for example:

module.exports.init = function () {

Then call it like this, assuming your db.js is in the same directory as your command prompt:

node -e 'require("./db").init()'

To other readers, the OP's init function could have been called anything, it is not important, it is just the specific name used in the question.

This Handler class should be static or leaks might occur: IncomingHandler

This way worked well for me, keeps code clean by keeping where you handle the message in its own inner class.

The handler you wish to use

Handler mIncomingHandler = new Handler(new IncomingHandlerCallback());

The inner class

class IncomingHandlerCallback implements Handler.Callback{

        public boolean handleMessage(Message message) {

            // Handle message code

            return true;

VBA, if a string contains a certain letter


If myString like "*A*" Then

auto refresh for every 5 mins

Auto reload with target of your choice. In this case target is _self set to every 5 minutes.

300000 milliseconds = 300 seconds = 5 minutes

as 60000 milliseconds = 60 seconds = 1 minute.

This is how you do it:

<script type="text/javascript">
function load()
setTimeout("'', '_self');", 300000);
<body onload="load()">

Or this if it is the same page to reload itself:

<script type="text/javascript">
function load()
setTimeout(", '_self');", 300000);
<body onload="load()">

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

If using win7 64 bit OS:

After installing the latest JDK make sure you copy the jre folder from the install location {C:\Program Files\Java\jdk1.7.0_40} directly to your eclipse folder as even pathing it apparently does nothing on win7.



Actual jdk version number on folder name will vary as newer versions are released

npm install error from the terminal

In case it helps anyone else - my issue was a rookie error, I had a space in the name line of my package.json and it caused the dependencies to be unreadable.

How to know function return type and argument types?

Well things have changed a little bit since 2011! Now there's type hints in Python 3.5 which you can use to annotate arguments and return the type of your function. For example this:

def greeting(name):
  return 'Hello, {}'.format(name)

can now be written as this:

def greeting(name: str) -> str:
  return 'Hello, {}'.format(name)

As you can now see types, there's some sort of optional static type checking which will help you and your type checker to investigate your code.

for more explanation I suggest to take a look at the blog post on type hints in PyCharm blog.

Log record changes in SQL server in an audit table

This is the code with two bug fixes. The first bug fix was mentioned by Royi Namir in the comment on the accepted answer to this question. The bug is described on StackOverflow at Bug in Trigger Code. The second one was found by @Fandango68 and fixes columns with multiples words for their names.

ON [dbo].[person]
           DECLARE @bit            INT,
                   @field          INT,
                   @maxfield       INT,
                   @char           INT,
                   @fieldname      VARCHAR(128),
                   @TableName      VARCHAR(128),
                   @PKCols         VARCHAR(1000),
                   @sql            VARCHAR(2000),
                   @UpdateDate     VARCHAR(21),
                   @UserName       VARCHAR(128),
                   @Type           CHAR(1),
                   @PKSelect       VARCHAR(1000)

           --You will need to change @TableName to match the table to be audited.
           -- Here we made GUESTS for your example.
           SELECT @TableName = 'PERSON'

           SELECT @UserName = SYSTEM_USER,
                  @UpdateDate = CONVERT(NVARCHAR(30), GETDATE(), 126)

           -- Action
           IF EXISTS (
                  SELECT *
                  FROM   INSERTED
               IF EXISTS (
                      SELECT *
                      FROM   DELETED
                   SELECT @Type = 'U'
                   SELECT @Type = 'I'
               SELECT @Type = 'D'

           -- get list of columns
           SELECT * INTO #ins
           FROM   INSERTED

           SELECT * INTO #del
           FROM   DELETED

           -- Get primary key columns for full outer join
           SELECT @PKCols = COALESCE(@PKCols + ' and', ' on') 
                  + ' i.[' + c.COLUMN_NAME + '] = d.[' + c.COLUMN_NAME + ']'
           WHERE  pk.TABLE_NAME = @TableName
                  AND c.TABLE_NAME = pk.TABLE_NAME

           -- Get primary key select for insert
           SELECT @PKSelect = COALESCE(@PKSelect + '+', '') 
                  + '''<[' + COLUMN_NAME 
                  + ']=''+convert(varchar(100),
           coalesce(i.[' + COLUMN_NAME + '],d.[' + COLUMN_NAME + ']))+''>'''
           WHERE  pk.TABLE_NAME = @TableName
                  AND c.TABLE_NAME = pk.TABLE_NAME

           IF @PKCols IS NULL
               RAISERROR('no PK on table %s', 16, -1, @TableName)


           SELECT @field = 0,
                  -- @maxfield = MAX(COLUMN_NAME) 
                  @maxfield = -- FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName

                          OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
           WHERE  TABLE_NAME = @TableName

           WHILE @field < @maxfield
               SELECT @field = MIN(
                              OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
               WHERE  TABLE_NAME = @TableName
                      AND COLUMNPROPERTY(
                              OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                          ) > @field

               SELECT @bit = (@field - 1)% 8 + 1

               SELECT @bit = POWER(2, @bit - 1)

               SELECT @char = ((@field - 1) / 8) + 1

               IF SUBSTRING(COLUMNS_UPDATED(), @char, 1) & @bit > 0
                  OR @Type IN ('I', 'D')
                   SELECT @fieldname = COLUMN_NAME
                   WHERE  TABLE_NAME = @TableName
                          AND COLUMNPROPERTY(
                                  OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                              ) = @field

                   SELECT @sql = 
           insert into Audit (    Type, 
           select ''' + @Type + ''',''' 
                          + @TableName + ''',' + @PKSelect
                          + ',''' + @fieldname + ''''
                          + ',convert(varchar(1000),d.' + @fieldname + ')'
                          + ',convert(varchar(1000),i.' + @fieldname + ')'
                          + ',''' + @UpdateDate + ''''
                          + ',''' + @UserName + ''''
                          + ' from #ins i full outer join #del d'
                          + @PKCols
                          + ' where i.' + @fieldname + ' <> d.' + @fieldname 
                          + ' or (i.' + @fieldname + ' is null and  d.'
                          + @fieldname
                          + ' is not null)' 
                          + ' or (i.' + @fieldname + ' is not null and  d.' 
                          + @fieldname
                          + ' is null)' 

                   EXEC (@sql)

/exclude in xcopy just for a file type

The /EXCLUDE: argument expects a file containing a list of excluded files.

So create a file called excludedfileslist.txt containing:


Then a command like this:

xcopy /r /d /i /s /y /exclude:excludedfileslist.txt C:\dev\apan C:\web\apan

Alternatively you could use Robocopy, but would require installing / copying a robocopy.exe to the machines.


An anonymous comment edit which simply stated "This Solution exclude also css file!"

This is true creating a excludedfileslist.txt file contain just:


(note no backslash on the end)

Will also exclude all of the following:

  • file1.cs
  • file2.css
  • dir1.cs\file3.txt
  • dir2\anyfile.cs.something.txt

Sometimes people don't read or understand the XCOPY command's help, here is an item I would like to highlight:

Using /exclude

  • List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.

As the example states it excludes "all files with the .obj extension" but it doesn't state that it also excludes files or directories named file1.obj.tmp or dir.obj.output\example2.txt.

There is a way around .css files being excluded also, change the excludedfileslist.txt file to contain just:


(note the backslash on the end).

Here is a complete test sequence for your reference:


Microsoft Windows [Version 6.1.7601]

C:\test1>md src
C:\test1>md dst
C:\test1>md src\dir1
C:\test1>md src\dir2.cs
C:\test1>echo "file contents" > src\file1.cs
C:\test1>echo "file contents" > src\file2.css
C:\test1>echo "file contents" > src\dir1\file3.txt
C:\test1>echo "file contents" > src\dir1\file4.cs.txt
C:\test1>echo "file contents" > src\dir2.cs\file5.txt

C:\test1>xcopy /r /i /s /y .\src .\dst
5 File(s) copied

C:\test1>echo .cs > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
1 File(s) copied

C:\test1>echo .cs\ > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
3 File(s) copied

This test was completed on a Windows 7 command line and retested on Windows 10 "10.0.14393".

Note that the last example does exclude .\src\dir2.cs\file5.txt which may or may not be unexpected for you.

Best way to create a simple python web service is probably the simplest web framework out there. "Bare" CGI is simpler, but you're completely on your own when it comes to making a service that actually does something.

"Hello, World!" according to isn't much longer than an bare CGI version, but it adds URL mapping, HTTP command distinction, and query parameter parsing for free:

import web

urls = (
    '/(.*)', 'hello'
app = web.application(urls, globals())

class hello:        
    def GET(self, name):
        if not name: 
            name = 'world'
        return 'Hello, ' + name + '!'

if __name__ == "__main__":

setState() inside of componentDidUpdate()

This example will help you to understand the React Life Cycle Hooks.

You can setState in getDerivedStateFromProps method i.e. static and trigger the method after props change in componentDidUpdate.

In componentDidUpdate you will get 3rd param which returns from getSnapshotBeforeUpdate.

You can check this codesandbox link

// Child component_x000D_
class Child extends React.Component {_x000D_
  // First thing called when component loaded_x000D_
  constructor(props) {_x000D_
    this.state = {_x000D_
      value: this.props.value,_x000D_
      color: "green"_x000D_
  // static method_x000D_
  // dont have access of 'this'_x000D_
  // return object will update the state_x000D_
  static getDerivedStateFromProps(props, state) {_x000D_
    return {_x000D_
      value: props.value,_x000D_
      color: props.value % 2 === 0 ? "green" : "red"_x000D_
  // skip render if return false_x000D_
  shouldComponentUpdate(nextProps, nextState) {_x000D_
    // return nextState.color !== this.state.color;_x000D_
    return true;_x000D_
  // In between before real DOM updates (pre-commit)_x000D_
  // has access of 'this'_x000D_
  // return object will be captured in componentDidUpdate_x000D_
  getSnapshotBeforeUpdate(prevProps, prevState) {_x000D_
    return { oldValue: prevState.value };_x000D_
  // Calls after component updated_x000D_
  // has access of previous state and props with snapshot_x000D_
  // Can call methods here_x000D_
  // setState inside this will cause infinite loop_x000D_
  componentDidUpdate(prevProps, prevState, snapshot) {_x000D_
    console.log("componentDidUpdate: ", prevProps, prevState, snapshot);_x000D_
  static getDerivedStateFromError(error) {_x000D_
    return { hasError: true };_x000D_
  componentDidCatch(error, info) {_x000D_
    console.log("componentDidCatch: ", error, info);_x000D_
  // After component mount_x000D_
  // Good place to start AJAX call and initial state_x000D_
  componentDidMount() {_x000D_
  makeAjaxCall() {_x000D_
  onClick() {_x000D_
    console.log("state: ", this.state);_x000D_
  render() {_x000D_
    return (_x000D_
      <div style={{ border: "1px solid red", padding: "0px 10px 10px 10px" }}>_x000D_
        <p style={{ color: this.state.color }}>Color: {this.state.color}</p>_x000D_
        <button onClick={() => this.onClick()}>{this.props.value}</button>_x000D_
// Parent component_x000D_
class Parent extends React.Component {_x000D_
  constructor(props) {_x000D_
    this.state = { value: 1 };_x000D_
    this.tick = () => {_x000D_
        date: new Date(),_x000D_
        value: this.state.value + 1_x000D_
  componentDidMount() {_x000D_
    setTimeout(this.tick, 2000);_x000D_
  render() {_x000D_
    return (_x000D_
      <div style={{ border: "1px solid blue", padding: "0px 10px 10px 10px" }}>_x000D_
        <Child value={this.state.value} />_x000D_
function App() {_x000D_
  return (_x000D_
      <Parent />_x000D_
const rootElement = document.getElementById("root");_x000D_
ReactDOM.render(<App />, rootElement);
<div id="root"></div>_x000D_
<script src=""></script>_x000D_
<script src=""></script>

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

This is likely when you have a PRIMARY KEY field and you are inserting a value that is duplicating or you have the INSERT_IDENTITY flag set to on

Android Studio-No Module

I was able to resolve this issue by performing a Gradle sync

To do this:

  1. In project view, right click the root (in my example below, "JamsMusicPlayer"

  2. Click "Synchronize {ProjectName}"

  3. Once this completes, you should see a module in your "Run" dialog

Gradle sync

How to read/process command line arguments?

I recommend looking at docopt as a simple alternative to these others.

docopt is a new project that works by parsing your --help usage message rather than requiring you to implement everything yourself. You just have to put your usage message in the POSIX format.

Getting multiple values with scanf()


int minx, miny, maxx,maxy;
do {
   printf("enter four integers: ");
} while (scanf("%d %d %d %d", &minx, &miny, &maxx, &maxy)!=4);

The loop is just to demonstrate that scanf returns the number of fields succesfully read (or EOF).

Detect if the app was launched/opened from a push notification

Xcode 10 Swift 4.2

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

    let state : UIApplicationState = application.applicationState
    if (state == .Inactive || state == .Background) {
        // coming from background
    } else {
        // App is running in foreground

.NET Core vs Mono

.Net Core does not require mono in the sense of the mono framework. .Net Core is a framework that will work on multiple platforms including Linux. Reference

However the .Net core can use the mono framework. Reference (note rc1 documentatiopn no rc2 available), however mono is not a Microsoft supported framework and would recommend using a supported framework

Now entity framework 7 is now called Entity Framework Core and is available on multiple platforms including Linux. Reference (review the road map)

I am currently using both of these frameworks however you must understand that it is still in release candidate stage (RC2 is the current version) and over the beta & release candidates there have been massive changes that usually end up with you scratching your head.

Here is a tutorial on how to install MVC .Net Core into Linux.

Finally you have a choice of Web Servers (where I am assuming the fast cgi reference came from) to host your application on Linux. Here is a reference point for installing to a Linux enviroment.

I realise this post ends up being mostly links to documentation but at this point those are your best sources of information. .Net core is still relatively new in the .Net community and until its fully released I would be hesitant to use it in a product environment given the breaking changes between released version.

PHP Unset Array value effect on other indexes

The Key Disappears, whether it is numeric or not. Try out the test script below.

    $t = array( 'a', 'b', 'c', 'd' );
    foreach($t as $k => $v)
        echo($k . ": " . $v . "<br/>");
    // Output: 0: a, 1: b, 2: c, 3: d


    foreach($t as $k => $v)
        echo($k . ": " . $v . "<br/>");
    // Output: 0: a, 2: c, 3: d

Create an ArrayList of unique values

You could use a Set. It is a collection which doesn't accept duplicates.

For div to extend full height

This is an old question. CSS has evolved. There now is the vh (viewport height) unit, also new layout options like flexbox or CSS grid to achieve classical designs in cleaner ways.

How do you make a deep copy of an object?

Deep copying can only be done with each class's consent. If you have control over the class hierarchy then you can implement the clonable interface and implement the Clone method. Otherwise doing a deep copy is impossible to do safely because the object may also be sharing non-data resources (e.g. database connections). In general however deep copying is considered bad practice in the Java environment and should be avoided via the appropriate design practices.

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

To avoid this problem you can use native method Bitmap.recycle() before null-ing Bitmap object (or setting another value). Example:

public final void setMyBitmap(Bitmap bitmap) {
  if (this.myBitmap != null) {
  this.myBitmap = bitmap;

And next you can change myBitmap w/o calling System.gc() like:


Determine a string's encoding in C#

It depends where the string 'came from'. A .NET string is Unicode (UTF-16). The only way it could be different if you, say, read the data from a database into a byte array.

This CodeProject article might be of interest: Detect Encoding for in- and outgoing text

Jon Skeet's Strings in C# and .NET is an excellent explanation of .NET strings.

What is this CSS selector? [class*="span"]

It's an attribute wildcard selector. In the sample you've given, it looks for any child element under .show-grid that has a class that CONTAINS span.

So would select the <strong> element in this example:

<div class="show-grid">
    <strong class="span6">Blah blah</strong>

You can also do searches for 'begins with...'

div[class^="something"] { }

which would work on something like this:-

<div class="something-else-class"></div>

and 'ends with...'

div[class$="something"] { }

which would work on

<div class="you-are-something"></div>

Good references

How do I get java logging output to appear on a single line?

Eclipse config

Per screenshot, in Eclipse select "run as" then "Run Configurations..." and add the answer from Trevor Robinson with double quotes instead of quotes. If you miss the double quotes you'll get "could not find or load main class" errors.

how to load url into div tag

Not using iframes puts you in a world of handling #document security issues with cross domain and links firing unexpected ways that was not intended for originally, do you really need bad Advertisements?

You can use jquery .load function to send the page to whatever html element you want to target, assuming your not getting this from another domain.

You can use javascript .innerHTML value to set and to rewrite the element with whatever you want, but if you add another file you might be writing against 2 documents in 1... like a in another

iframes are old, another way we can add "src" into the html alone without any use for javascript. But it's old, prehistoric, and just plain OLD! Frameset makes it worse because I can put #document in those to handle multiple html files. An Old way people created navigation menu's Long and before people had FLIP phones.

1.) Yes you will have to work in Javascript if you do NOT want to use an Iframe.

2.) There is a good hack in which you can set the domain to equal each other without having to set server stuff around. Means you will have to have edit capabilities of the documents.

3.) javascript window.document is limited to the iframe itself and can NOT go above the iframe if you want to grab something through the DOM itself. Because it treats it like a separate tab, it also defines it in another document object model.

Do I need <class> elements in persistence.xml?

I'm not sure this solution is under the spec but I think I can share for others.

dependency tree


Contains entity classes only. No META-INF/persistence.xml.


Depends on my-entities. Contains EJBs only.


Depends on my-services. Contains resource classes and META-INF/persistence.xml.


  • How can we specify <jar-file/> element in my-resources as the version-postfixed artifact name of a transient dependency?
  • How can we sync the <jar-file/> element's value and the actual transient dependency's one?


direct (redundant?) dependency and resource filtering

I put a property and a dependency in my-resources/pom.xml.

    <!-- this is actually a transitive dependency -->
    <scope>compile</scope> <!-- other values won't work -->

Now get the persistence.xml ready for being filtered

<?xml version="1.0" encoding="UTF-8"?>
<persistence ...>
  <persistence-unit name="myPU" transaction-type="JTA">

Maven Enforcer Plugin

With the dependencyConvergence rule, we can assure that the my-entities' version is same in both direct and transitive.


How to use a findBy method with comparative criteria

I like to use such static methods:

$result = $purchases_repository->matching(
        Criteria::expr()->gt('prize', 200)

Of course, you can push logic when it is 1 condition, but when you have more conditions it is better to divide it into fragments, configure and pass it to the method:

$expr = Criteria::expr();

$criteria = Criteria::create();
$criteria->where($expr->gt('prize', 200));
$criteria->orderBy(['prize' => Criteria::DESC]);

$result = $purchases_repository->matching($criteria);

Maven error :Perhaps you are running on a JRE rather than a JDK?

For me, it worked like following. Please look at JAVA_HOME environment variable, whether it is pointing to JRE or JDK.? If it pointed to JRE, you will face "Perhaps you are running on a JRE rather than a JDK" issue. if so change the path to JDK.

Modifying like this, it worked for me.

JAVA_HOME C:\Program Files\Java\jdk1.8.0_31

Scale Image to fill ImageView width and keep aspect ratio

try with this simple line... add this line in your xml code in image view tag with out adding any dependency android:scaleType="fitXY"

TimeStamp on file name using PowerShell

Here's some PowerShell code that should work. You can combine most of this into fewer lines, but I wanted to keep it clear and readable.

[string]$filePath = "C:\";

[string]$directory = [System.IO.Path]::GetDirectoryName($filePath);
[string]$strippedFileName = [System.IO.Path]::GetFileNameWithoutExtension($filePath);
[string]$extension = [System.IO.Path]::GetExtension($filePath);
[string]$newFileName = $strippedFileName + [DateTime]::Now.ToString("yyyyMMdd-HHmmss") + $extension;
[string]$newFilePath = [System.IO.Path]::Combine($directory, $newFileName);

Move-Item -LiteralPath $filePath -Destination $newFilePath;

What is "runtime"?

Runtime is somewhat opposite to design-time and compile-time/link-time. Historically it comes from slow mainframe environment where machine-time was expensive.

PHP Warning: Division by zero

If a variable is not set then it is NULL and if you try to divide something by null you will get a divides by zero error

How can I use jQuery to make an input readonly?

Use this example to make text box ReadOnly or Not.

<input type="textbox" class="txt" id="txt"/>
<input type="button" class="Btn_readOnly" value="Readonly" />
<input type="button" class="Btn_notreadOnly" value="Not Readonly" />


           $("#txt").prop("readonly", true);

           $("#txt").prop("readonly", false);


What is the canonical way to check for errors using the CUDA runtime API?

The C++-canonical way: Don't check for errors...use the C++ bindings which throw exceptions.

I used to be irked by this problem; and I used to have a macro-cum-wrapper-function solution just like in Talonmies and Jared's answers, but, honestly? It makes using the CUDA Runtime API even more ugly and C-like.

So I've approached this in a different and more fundamental way. For a sample of the result, here's part of the CUDA vectorAdd sample - with complete error checking of every runtime API call:

// (... prepare host-side buffers here ...)

auto current_device = cuda::device::current::get();
auto d_A = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_B = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_C = cuda::memory::device::make_unique<float[]>(current_device, numElements);

cuda::memory::copy(d_A.get(), h_A.get(), size);
cuda::memory::copy(d_B.get(), h_B.get(), size);

// (... prepare a launch configuration here... )

cuda::launch(vectorAdd, launch_config,
    d_A.get(), d_B.get(), d_C.get(), numElements
cuda::memory::copy(h_C.get(), d_C.get(), size);

// (... verify results here...)

Again - all potential errors are checked , and an exception if an error occurred (caveat: If the kernel caused some error after launch, it will be caught after the attempt to copy the result, not before; to ensure the kernel was successful you would need to check for error between the launch and the copy with a cuda::outstanding_error::ensure_none() command).

The code above uses my

Thin Modern-C++ wrappers for the CUDA Runtime API library (Github)

Note that the exceptions carry both a string explanation and the CUDA runtime API status code after the failing call.

A few links to how CUDA errors are automagically checked with these wrappers:

How can I remove the gloss on a select element in Safari on Mac?

As mentioned several times here


also removes the arrows, which is not what you want in most cases.

An easy workaround I found is to simply use select2 instead of select. You can re-style a select2 element as well, and most importantly, select2 looks the same on Windows, Android, iOS and Mac.

Java - Including variables within strings?

you can use String format to include variables within strings

i use this code to include 2 variable in string:

String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);

Postgresql: password authentication failed for user "postgres"

Answer given is almost correct just missing some pointers which i'll be taking care of in my solution

First make sure your user have a sudo access if not you can use the below command to add your user as sudo user :-

sudo adduser <username> sudo

The change will take effect the next time the user logs in.

i) Now go to sudo vim /etc/postgresql/<your_postgres_version>/main/pg_hba.conf file and look for line that says :

local   all             postgres                                md5 #peer

and comment that. Just below that line there must be a commented line that says:

local   all             postgres                                peer

or for older versions it'll be :-

local   all         postgres                          ident

Uncomment that line.

ii) Now restart the postgres by using any of these commands :-

sudo /etc/init.d/postgresql restart


sudo service postgresql restart

iii) Now you can simply log into postgres using the following command :

sudo -u postgres psql

iv) once you're in you can create any operation you want to in my case i wanted to create a new database you can do the same using below command :

CREATE DATABASE airflow_replica;

Support for the experimental syntax 'classProperties' isn't currently enabled

After almost 3 hours of searching and spending time on the same error, I found that I'm using name import for React:

import { React } from 'react';

which is totally wrong. Just by switching it to:

import React from 'react';

all the error are gone. I hope this helps someone. This is my .babelrc:

  "presets": [
  "plugins": [

the webpack.config.js

const path = require('path');
const devMode = process.env.Node_ENV !== 'production';
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  entry: './src/App.js',
  devtool: 'source-map',
  output: {
    path: path.resolve(__dirname, 'public'),
    filename: 'App.js'
  mode: 'development',
  devServer: {
    contentBase: path.resolve(__dirname, 'public'),
    open: 'google chrome',
    historyApiFallback: true
  module: {
    rules: [
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        test: /\.(sa|sc|c)ss$/,
        use: [
          devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
            loader: 'css-loader',
            options: {
              modules: true,
              localIdentName: '[local]--[hash:base64:5]',
              sourceMap: true
            loader: 'sass-loader'
  plugins: [
    new MiniCssExtractPlugin({
      filename: devMode ? '[name].css' : '[name].[hash].css',
      chunkFilename: devMode ? '[id].css' : '[id].[hash].css'

the package.json

  "name": "expense-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack",
    "serve": "webpack-dev-server"
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.1.2",
    "@babel/core": "^7.1.2",
    "@babel/plugin-proposal-class-properties": "^7.1.0",
    "@babel/preset-env": "^7.1.0",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.4",
    "css-loader": "^1.0.0",
    "mini-css-extract-plugin": "^0.4.3",
    "node-sass": "^4.9.3",
    "react-router-dom": "^4.3.1",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.20.2",
    "webpack-cli": "^3.1.2",
    "webpack-dev-server": "^3.1.9"
  "dependencies": {
    "normalize.css": "^8.0.0",
    "react": "^16.5.2",
    "react-dom": "^16.5.2"

Understanding ibeacon distancing

Distances to the source of iBeacon-formatted advertisement packets are estimated from the signal path attenuation calculated by comparing the measured received signal strength to the claimed transmit power which the transmitter is supposed to encode in the advertising data.

A path loss based scheme like this is only approximate and is subject to variation with things like antenna angles, intervening objects, and presumably a noisy RF environment. In comparison, systems really designed for distance measurement (GPS, Radar, etc) rely on precise measurements of propagation time, in same cases even examining the phase of the signal.

As Jiaru points out, 160 ft is probably beyond the intended range, but that doesn't necessarily mean that a packet will never get through, only that one shouldn't expect it to work at that distance.

How can I set up an editor to work with Git on Windows?

Edit: After updating to Vim 7.3, I've come to the conclusion that the cleanest and easiest way to do this is:

  1. Add Vim's main folder to your path (right click on My ComputerPropertiesAdvancedEnvironment Variables)

  2. Run this:

    git config --global core.editor "gvim --nofork '%*'"

If you do it this way, then I am fairly sure it will work with Cygwin as well.

Original answer:

Even with a couple of Vim-related answers, I was having trouble getting this to work with gVim under Windows (while not using a batch file or %EDITOR% or Cygwin).

What I eventually arrived at is nice and clean, and draws from a few of the solutions here:

git config --global core.editor \
"'C:/Program Files/Vim/vim72/gvim.exe' --nofork '%*'"

One gotcha that took me a while is these are not the Windows-style backslashes. They are normal forward slashes.

Simple JavaScript login form validation

<form name="loginform" onsubmit="validateForm()">

instead of putting the onsubmit on the actual input button

Execute SQL script from command line

If you want to run the script file then use below in cmd

sqlcmd -U user -P pass  -S servername -d databasename -i "G:\Hiren\Lab_Prodution.sql"