Programs & Examples On #Applet servlet


Why is vertical-align:text-top; not working in CSS

The vertical-align attribute is for inline elements only. It will have no effect on block level elements, like a div. Also text-top only moves the text to the top of the current font size. If you would like to vertically align an inline element to the top just use this.

vertical-align: top;

The paragraph tag is not outdated. Also, the vertical-align attribute applied to a span element may not display as intended in some mozilla browsers.

Creating a class object in c++

First of all, both cases calls a constructor. If you write

Example *example = new Example();

then you are creating an object, call the constructor and retrieve a pointer to it.

If you write

Example example;

The only difference is that you are getting the object and not a pointer to it. The constructor called in this case is the same as above, the default (no argument) constructor.

As for the singleton question, you must simple invoke your static method by writing:

Example *e = Singleton::getExample();

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

If you want an empty string default then a preferred way is one of these (depending on your need):

$str_value = strval($_GET['something']);
$trimmed_value = trim($_GET['something']);
$int_value = intval($_GET['somenumber']);

If the url parameter something doesn't exist in the url then $_GET['something'] will return null

strval($_GET['something']) -> strval(null) -> ""

and your variable $value is set to an empty string.

  • trim() might be prefered over strval() depending on code (e.g. a Name parameter might want to use it)
  • intval() if only numeric values are expected and the default is zero. intval(null) -> 0

Cases to consider:

...&something=value1&key2=value2 (typical)

...&key2=value2 (parameter missing from url $_GET will return null for it)

...&something=+++&key2=value (parameter is " ")

Why this is a preferred approach:

  • It fits neatly on one line and is clear what's going on.
  • It's readable than $value = isset($_GET['something']) ? $_GET['something'] : '';
  • Lower risk of copy/paste mistake or a typo: $value=isset($_GET['something'])?$_GET['somthing']:'';
  • It's compatible with older and newer php.

Update Strict mode may require something like this:

$str_value = strval(@$_GET['something']);
$trimmed_value = trim(@$_GET['something']);
$int_value = intval(@$_GET['somenumber']);

SQL Server - after insert trigger - update another column in the same table

Yes, it will recursively call your trigger unless you turn the recursive triggers setting off:


MSDN has a good explanation of the behavior at under the Recursive Triggers heading.

SQL Query NOT Between Two Dates

If the 'NOT' is put before the start_date it should work. For some reason (I don't know why) when 'NOT' is put before 'BETWEEN' it seems to return everything.

NOT (start_date BETWEEN CAST('2009-12-15' AS DATE) AND CAST('2010-01-02' AS DATE))

Simple search MySQL database using php



$errors = FALSE;
$errorMessage = "";

  $errors = TRUE;
  $errorMessage .= "There was a connection error <br/>";
} else if($errors != "TRUE"){
  $errors .= FALSE;

  $search = mysqli_real_escape_string($_POST['search']);

//This is functions.php
function search($searchQuery){
  echo "<div class="col-md-10 col-md-offset-1">";
  $query = query("SELECT * FROM `index` WHERE `keywords` LIKE '".$searchTerm."' ");
  while($row = mysqli_fetch_array($query)){
    $results = <<< DELIMITER
      <div class="result col-md-12">
        <a href="index.php?search={$row['id']}"> {$row['Title']} </a>
        <p class="searchDesc">{$row['description']}</p>
    echo $results;
  echo "</div>";

function errorDisplay($msg){
    $_SESSION['errors'] = $msg;
  } else if() {
    $_SESSION['errors'] .= $msg . "<br>";
function showError($msg) {
  return $msg;

Perhaps That Helps?

WordPress asking for my FTP credentials to install plugins

First move to your installation folder (for example)

cd /Applications/XAMPP/xamppfiles/

Now we’re going to modify your htdocs directory:

sudo chown -R daemon htdocs

Enter your root password when prompted, then finish it out with a chmod call:

sudo chmod -R g+w htdocs

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

The CORS issue should be fixed in the backend. Temporary workaround uses this option.

  1. Go to C:\Program Files\Google\Chrome\Application

  2. Open command prompt

  3. Execute the command chrome.exe --disable-web-security --user-data-dir="c:/ChromeDevSession"

Using the above option, you can able to open new chrome without security. this chrome will not throw any cors issue.

enter image description here

How to deploy a React App on Apache web server

As well described in React's official docs, If you use routers that use the HTML5 pushState history API under the hood, you just need to below content to .htaccess file in public directory of your react-app.

Options -MultiViews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.html [QSA,L]

And if using relative path update the package.json like this:

"homepage": ".",

Note: If you are using react-router@^4, you can root <Link> using the basename prop on any <Router>.

import React from 'react';
import BrowserRouter as Router from 'react-router-dom';
<Router basename="/calendar"/>
<Link to="/today"/>

GROUP BY without aggregate function

As an addition

basically the number of columns have to be equal to the number of columns in the GROUP BY clause

is not a correct statement.

  • Any attribute which is not a part of GROUP BY clause can not be used for selection
  • Any attribute which is a part of GROUP BY clause can be used for selection but not mandatory.

JAX-WS and BASIC authentication, when user names and passwords are in a database

In your client SOAP handler you need to set and property as follow:

public class ClientHandler implements SOAPHandler<SOAPMessageContext>{

    public boolean handleMessage(final SOAPMessageContext soapMessageContext)
        final Boolean outInd = (Boolean)soapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (outInd.booleanValue())
               soapMessageContext.put("", <ClientUserName>);
               soapMessageContext.put("", <ClientPassword>);
          catch (Exception e)
               return false;
      return true;

How can I pass a username/password in the header to a SOAP WCF Service

The answers above are so wrong! DO NOT add custom headers. Judging from your sample xml, it is a standard WS-Security header. WCF definitely supports it out of the box. When you add a service reference you should have basicHttpBinding binding created for you in the config file. You will have to modify it to include security element with mode TransportWithMessageCredential and message element with clientCredentialType = UserName:

  <binding name="usernameHttps">
    <security mode="TransportWithMessageCredential">
      <message clientCredentialType="UserName"/>

The config above is telling WCF to expect userid/password in the SOAP header over HTTPS. Then you can set id/password in your code before making a call:

var service = new MyServiceClient();
service.ClientCredentials.UserName.UserName = "username";
service.ClientCredentials.UserName.Password = "password";

Unless this particular service provider deviated from the standard, it should work.

How can I add comments in MySQL?

Several ways:

# Comment
-- Comment
/* Comment */

Remember to put the space after --.

See the documentation.

Floating point exception( core dump

Floating Point Exception happens because of an unexpected infinity or NaN. You can track that using gdb, which allows you to see what is going on inside your C program while it runs. For more details:

In a nutshell, these commands might be useful...

gcc -g myprog.c

gdb a.out

gdb core a.out

ddd a.out

how to remove "," from a string in javascript

Use String.replace(), e.g.

var str = "a,d,k";
str = str.replace( /,/g, "" );

Note the g (global) flag on the regular expression, which matches all instances of ",".

What is the difference between Tomcat, JBoss and Glassfish?

Tomcat is merely an HTTP server and Java servlet container. JBoss and GlassFish are full-blown Java EE application servers, including an EJB container and all the other features of that stack. On the other hand, Tomcat has a lighter memory footprint (~60-70 MB), while those Java EE servers weigh in at hundreds of megs. Tomcat is very popular for simple web applications, or applications using frameworks such as Spring that do not require a full Java EE server. Administration of a Tomcat server is arguably easier, as there are fewer moving parts.

However, for applications that do require a full Java EE stack (or at least more pieces that could easily be bolted-on to Tomcat)... JBoss and GlassFish are two of the most popular open source offerings (the third one is Apache Geronimo, upon which the free version of IBM WebSphere is built). JBoss has a larger and deeper user community, and a more mature codebase. However, JBoss lags significantly behind GlassFish in implementing the current Java EE specs. Also, for those who prefer a GUI-based admin system... GlassFish's admin console is extremely slick, whereas most administration in JBoss is done with a command-line and text editor. GlassFish comes straight from Sun/Oracle, with all the advantages that can offer. JBoss is NOT under the control of Sun/Oracle, with all the advantages THAT can offer.

How to get data from database in javascript based on the value passed to the function

'SELECT * FROM Employ where number = ' + parseInt(val, 10) + ';'

For example, if val is "10" then this will end up building the string:

"SELECT * FROM Employ where number = 10;"

Case-insensitive search in Rails model

This is a complete setup in Rails, for my own reference. I'm happy if it helps you too.

the query:

Product.where("lower(name) = ?", name.downcase).first

the validator:

validates :name, presence: true, uniqueness: {case_sensitive: false}

the index (answer from Case-insensitive unique index in Rails/ActiveRecord?):

execute "CREATE UNIQUE INDEX index_products_on_lower_name ON products USING btree (lower(name));"

I wish there was a more beautiful way to do the first and the last, but then again, Rails and ActiveRecord is open source, we shouldn't complain - we can implement it ourselves and send pull request.

Getting Git to work with a proxy server - fails with "Request timed out"

There's something I noticed and want to share here:

git config --global http.proxy http://<proxy address>:<port number>

The method above will not work for SSH URLs (i.e., [email protected]:<user name>/<project name>.git):

git clone [email protected]:<user name>/<project name>.git // will not use the http proxy

And things will not change if we set SSH over the HTTPS port ( because it only changes the port (22 by default) the SSH connection connects to.

Change CSS properties on click

With jquery you can do it like:

    $('#foo').css('background-color', 'red').css('color', 'white');

this applies for all img tags you should set an id attribute for it like image and then:

    $('#foo').css('background-color', 'red').css('color', 'white');

How to resolve this System.IO.FileNotFoundException

I came across a similar situation after publishing a ClickOnce application, and one of my colleagues on a different domain reported that it fails to launch.

To find out what was going on, I added a try catch statement inside the MainWindow method as @BradleyDotNET mentioned in one comment on the original post, and then published again.

public MainWindow()
    catch (Exception exc)

Then my colleague reported to me the exception detail, and it was a missing reference of a third party framework dll file.

Added the reference and problem solved.

How to change Jquery UI Slider handle

You also should set border:none to that css class.

Passing Objects By Reference or Value in C#

Lots of good answers had been added. I still want to contribute, might be it will clarify slightly more.

When you pass an instance as an argument to the method it passes the copy of the instance. Now, if the instance you pass is a value type(resides in the stack) you pass the copy of that value, so if you modify it, it won't be reflected in the caller. If the instance is a reference type you pass the copy of the reference(again resides in the stack) to the object. So you got two references to the same object. Both of them can modify the object. But if within the method body, you instantiate new object your copy of the reference will no longer refer to the original object, it will refer to the new object you just created. So you will end up having 2 references and 2 objects.

How to Insert Double or Single Quotes

Or Select range and Format cells > Custom \"@\"

R adding days to a date

Just use

 as.Date("2001-01-01") + 45

from base R, or date functionality in one of the many contributed packages. My RcppBDT package wraps functionality from Boost Date_Time including things like 'date of third Wednesday' in a given month.

Edit: And egged on by @Andrie, here is a bit more from RcppBDT (which is mostly a test case for Rcpp modules, really).

R> library(RcppBDT)
Loading required package: Rcpp
R> str(bdt)
Reference class 'Rcpp_date' [package ".GlobalEnv"] with 0 fields
 and 42 methods, of which 31 are possibly relevant:
   addDays, finalize, fromDate, getDate, getDay, getDayOfWeek, getDayOfYear, 
   getEndOfBizWeek, getEndOfMonth, getFirstDayOfWeekAfter,
   getFirstDayOfWeekInMonth, getFirstOfNextMonth, getIMMDate, getJulian, 
   getLastDayOfWeekBefore, getLastDayOfWeekInMonth, getLocalClock, getModJulian,
   getMonth, getNthDayOfWeek, getUTC, getWeekNumber, getYear, initialize, 
   setEndOfBizWeek, setEndOfMonth, setFirstOfNextMonth, setFromLocalClock,
   setFromUTC, setIMMDate, subtractDays
R> bdt$fromDate( as.Date("2001-01-01") )
R> bdt$addDays( 45 )
R> print(bdt)
[1] "2001-02-15"

How to insert &nbsp; in XSLT

You might want to add the definition for this entity in the beginning of the file (below xml declaration):

<!DOCTYPE stylesheet [
<!ENTITY nbsp  "&#160;" >

Also you can add more entities such as Ntilde, Aacute, etc.

Which characters make a URL invalid?

In your supplementary question you asked if[/].html is a valid URL.

That URL isn't valid because a URL is a type of URI and a valid URI must have a scheme like http: (see RFC 3986).

If you meant to ask if[/].html is a valid URL then the answer is still no because the square bracket characters aren't valid there.

The square bracket characters are reserved for URLs in this format: http://[2001:db8:85a3::8a2e:370:7334]/foo/bar (i.e. an IPv6 literal instead of a host name)

It's worth reading RFC 3986 carefully if you want to understand the issue fully.

What does the "On Error Resume Next" statement do?

It's worth noting that even when On Error Resume Next is in effect, the Err object is still populated when an error occurs, so you can still do C-style error handling.

On Error Resume Next


If Err Then
    WScript.StdErr.WriteLine "error " & Err.Number
    WScript.Quit 1
End If

On Error GoTo 0

adb remount permission denied, but able to access super user in shell -- android

I rebooted to recovery then

adb root; adb adb remount system; 

worked for me my recovery is twrp v3.5

Why write <script type="text/javascript"> when the mime type is set by the server?

Douglas Crockford says:


This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.

He also says:

W3C did not adopt the language attribute, favoring instead a type attribute which takes a MIME type. Unfortunately, the MIME type was not standardized, so it is sometimes "text/javascript" or "application/ecmascript" or something else. Fortunately, all browsers will always choose JavaScript as the default programming language, so it is always best to simply write <script>. It is smallest, and it works on the most browsers.

For entertainment purposes only, I tried out the following five scripts

  <script type="application/ecmascript">alert("1");</script>
  <script type="text/javascript">alert("2");</script>
  <script type="baloney">alert("3");</script>
  <script type="">alert("4");</script>
  <script >alert("5");</script>

On Chrome, all but script 3 (type="baloney") worked. IE8 did not run script 1 (type="application/ecmascript") or script 3. Based on my non-extensive sample of two browsers, it looks like you can safely ignore the type attribute, but that it you use it you better use a legal (browser dependent) value.

Split string into list in jinja?

You can’t run arbitrary Python code in jinja; it doesn’t work like JSP in that regard (it just looks similar). All the things in jinja are custom syntax.

For your purpose, it would make most sense to define a custom filter, so you could for example do the following:

The grass is {{ variable1 | splitpart(0, ',') }} and the boat is {{  splitpart(1, ',') }}
Or just:
The grass is {{ variable1 | splitpart(0) }} and the boat is {{  splitpart(1) }}

The filter function could then look like this:

def splitpart (value, index, char = ','):
    return value.split(char)[index]

An alternative, which might make even more sense, would be to split it in the controller and pass the splitted list to the view.

`IF` statement with 3 possible answers each based on 3 different ranges

You need to use the AND function for the multiple conditions:

=IF(AND(A2>=75, A2<=79),0.255,IF(AND(A2>=80, X2<=84),0.327,IF(A2>=85,0.559,0)))

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

The trick here is to use the -C (comment) parameter to specify your GCE userid. It looks like Google introduced this change last in 2018.

If the Google user who owns the GCE instance is [email protected] (which you will use as your login userid), then generate the key pair with (for example)

ssh-keygen -b521 -t ecdsa -C myname -f mykeypair

When you paste into the instance's public key list, you should see "myname" appear as the userid of the key.

Setting this up will let you use ssh, scp, etc from your command line.

Get form data in ReactJS

Also, this can be used too.

handleChange: function(state,e) {
render : function() {
  return (
      <input type="text" name="email" placeholder="Email" value={} onChange={this.handleChange.bind(this, 'email')} />
      <input type="password" name="password" placeholder="Password" value={this.state.password} onChange={this.handleChange.bind(this, 'password')}/>
      <button type="button" onClick={this.handleLogin}>Login</button>
handleLogin: function() {
  console.log("EMail: ",;
  console.log("Password: ", this.state.password);

php - get numeric index of associative array

a solution i came up with... probably pretty inefficient in comparison tho Fosco's solution:

 protected function getFirstPosition(array$array, $content, $key = true) {

  $index = 0;
  if ($key) {
   foreach ($array as $key => $value) {
    if ($key == $content) {
     return $index;
  } else {
   foreach ($array as $key => $value) {
    if ($value == $content) {
     return $index;

How to find the privileges and roles granted to a user in Oracle?

IF privileges are given to a user through some roles, then below SQL can be used

select * from ROLE_ROLE_PRIVS where ROLE = 'ROLE_NAME';
select * from ROLE_TAB_PRIVS  where ROLE = 'ROLE_NAME';
select * from ROLE_SYS_PRIVS  where ROLE = 'ROLE_NAME';

Displaying the build date

In 2018 some of the above solutions do not work anymore or do not work with .NET Core.

I use the following approach which is simple and works for my .NET Core 2.0 project.

Add the following to your .csproj inside the PropertyGroup :


This defines a PropertyFunction which you can access in your pre build command.

Your pre-build looks like this

echo $(today) > $(ProjectDir)BuildTimeStamp.txt

Set the property of the BuildTimeStamp.txt to Embedded resource.

Now you can read the time stamp like this

public static class BuildTimeStamp
        public static string GetTimestamp()
            var assembly = Assembly.GetEntryAssembly(); 

            var stream = assembly.GetManifestResourceStream("NamespaceGoesHere.BuildTimeStamp.txt");

            using (var reader = new StreamReader(stream))
                return reader.ReadToEnd();

How can I convert a stack trace to a string?

The solution is to convert the stackTrace of array to string data type. See the following example:

import java.util.Arrays;


}catch(Exception ex){
    String stack = Arrays.toString(ex.getStackTrace());
    System.out.println("stack "+ stack);

Why does my Spring Boot App always shutdown immediately after starting?

In my case I fixed this issue like below:-

  1. First I removed (apache) C:\Users\myuserId\.m2\repository\org\apache

  2. I added below dependencies in my pom.xml file

  3. I have changed the default socket by adding below lines in resource file ..\yourprojectfolder\src\main\resourcesand\ manually created this file)

     [email protected]@

    for that I have added below block in my pom.xml under <build> section.


My final pom.xml file look like

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""


    <description>Welcome project for Spring Boot</description>

        <relativePath/> <!-- lookup parent from repository -->











ORA-01008: not all variables bound. They are bound

On Charles' comment problem: to make things worse, let

:p1 = 'TRIALDEV'

via a Command Parameter, then execute

select T.table_name as NAME, COALESCE(C.comments, '===') as DESCRIPTION
from all_all_tables T
Inner Join all_tab_comments C on T.owner = C.owner and T.table_name = C.table_name
where Upper(T.owner)=:p1
order by T.table_name

558 line(s) affected. Processing time: 00:00:00.6535711

and when changing the literal string from === to ---

select T.table_name as NAME, COALESCE(C.comments, '---') as DESCRIPTION

ORA-01008: not all variables bound

Both statements execute fine in SQL Developer. The shortened code:

            Using con = New OracleConnection(cs)
                Using cmd = con.CreateCommand()
                    cmd.CommandText = cmdText
                    cmd.Parameters.Add(pn, OracleDbType.NVarchar2, 250).Value = p
                    Dim tbl = New DataTable
                    Dim da = New OracleDataAdapter(cmd)
                    Return tbl
                End Using
            End Using

using Oracle.ManagedDataAccess.dll Version with the default settings in VS2015 on the .Net 4.61 platform.

So somewhere in the call chain, there might be a parser that is a bit too aggressively looking for one-line-comments started by -- in the commandText. But even if this would be true, the error message "not all variables bound" is at least misleading.

How Exactly Does @param Work - Java

@param will not affect testNumber.It is a Javadoc comment - i.e used for generating documentation . You can put a Javadoc comment immediately before a class, field, method, constructor, or interface such as @param, @return . Generally begins with '@' and must be the first thing on the line.

The Advantage of using @param is :- By creating simple Java classes that contain attributes and some custom Javadoc tags, you allow those classes to serve as a simple metadata description for code generation.

       *@param testNumber
       *@return integer
    public int main testNumberIsValid(int testNumber){

       if (testNumber < 6) {

Whenever in your code if you reuse testNumberIsValid method, IDE will show you the parameters the method accepts and return type of the method.

Please explain the exec() function and its family

The exec family of functions make your process execute a different program, replacing the old program it was running. I.e., if you call

execl("/bin/ls", "ls", NULL);

then the ls program is executed with the process id, current working dir and user/group (access rights) of the process that called execl. Afterwards, the original program is not running anymore.

To start a new process, the fork system call is used. To execute a program without replacing the original, you need to fork, then exec.

Laravel eloquent update record without loading from database

Use property exists:

$post = new Post();
$post->exists = true;
$post->id = 3; //already exists in database.
$post->title = "Updated title";

Here is the API documentation:

package javax.mail and javax.mail.internet do not exist

I just resolved this for myself, so hope this helps. My project runs on GlassFish 4, Eclipse MARS, with JDK 1.8 and JavaEE 7.

Firstly, you can find javax.mail.jar in the extracted glassfish folder: glassfish4->glassfish->modules

Next, in Eclipse, Right Click on your project in the explorer and navigate the following: Properties->Java Build Path->Libraries->Add External JARs-> Go to the aforementioned folder to add javax.mail.jar

Standard way to embed version into python package?

Using setuptools and pbr

There is not a standard way to manage version, but the standard way to manage your packages is setuptools.

The best solution I've found overall for managing version is to use setuptools with the pbr extension. This is now my standard way of managing version.

Setting up your project for full packaging may be overkill for simple projects, but if you need to manage version, you are probably at the right level to just set everything up. Doing so also makes your package releasable at PyPi so everyone can download and use it with Pip.

PBR moves most metadata out of the tools and into a setup.cfg file that is then used as a source for most metadata, which can include version. This allows the metadata to be packaged into an executable using something like pyinstaller if needed (if so, you will probably need this info), and separates the metadata from the other package management/setup scripts. You can directly update the version string in setup.cfg manually, and it will be pulled into the *.egg-info folder when building your package releases. Your scripts can then access the version from the metadata using various methods (these processes are outlined in sections below).

When using Git for VCS/SCM, this setup is even better, as it will pull in a lot of the metadata from Git so that your repo can be your primary source of truth for some of the metadata, including version, authors, changelogs, etc. For version specifically, it will create a version string for the current commit based on git tags in the repo.

As PBR will pull version, author, changelog and other info directly from your git repo, so some of the metadata in setup.cfg can be left out and auto generated whenever a distribution is created for your package (using

Get the current version in real-time

setuptools will pull the latest info in real-time using

python --version

This will pull the latest version either from the setup.cfg file, or from the git repo, based on the latest commit that was made and tags that exist in the repo. This command doesn't update the version in a distribution though.

Updating the version metadata

When you create a distribution with (i.e. py sdist, for example), then all the current info will be extracted and stored in the distribution. This essentially runs the --version command and then stores that version info into the package.egg-info folder in a set of files that store distribution metadata.

Note on process to update version meta-data:

If you are not using pbr to pull version data from git, then just update your setup.cfg directly with new version info (easy enough, but make sure this is a standard part of your release process).

If you are using git, and you don't need to create a source or binary distribution (using python sdist or one of the python bdist_xxx commands) the simplest way to update the git repo info into your <mypackage>.egg-info metadata folder is to just run the python install command. This will run all the PBR functions related to pulling metadata from the git repo and update your local .egg-info folder, install script executables for any entry-points you have defined, and other functions you can see from the output when you run this command.

Note that the .egg-info folder is generally excluded from being stored in the git repo itself in standard Python .gitignore files (such as from Gitignore.IO), as it can be generated from your source. If it is excluded, make sure you have a standard "release process" to get the metadata updated locally before release, and any package you upload to or otherwise distribute must include this data to have the correct version. If you want the Git repo to contain this info, you can exclude specific files from being ignored (i.e. add !*.egg-info/PKG_INFO to .gitignore)

Accessing the version from a script

You can access the metadata from the current build within Python scripts in the package itself. For version, for example, there are several ways to do this I have found so far:

## This one is a new built-in as of Python 3.8.0 should become the standard
from importlib-metadata import version

v0 = version("mypackage")
print('v0 {}'.format(v0))

## I don't like this one because the version method is hidden
import pkg_resources  # part of setuptools

v1 = pkg_resources.require("mypackage")[0].version
print('v1 {}'.format(v1))

# Probably best for pre v3.8.0 - the output without .version is just a longer string with
# both the package name, a space, and the version string
import pkg_resources  # part of setuptools

v2 = pkg_resources.get_distribution('mypackage').version
print('v2 {}'.format(v2))

## This one seems to be slower, and with pyinstaller makes the exe a lot bigger
from pbr.version import VersionInfo

v3 = VersionInfo('mypackage').release_string()
print('v3 {}'.format(v3))

You can put one of these directly in your for the package to extract the version info as follows, similar to some other answers:

__all__ = (

import pkg_resources  # part of setuptools

__version__ = pkg_resources.get_distribution("mypackage").version

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

Several fixes:

  1. Use the right driver class name for your environment: if you are using an out-of-process Derby server, then you want ClientDriver (and need to use derbyclient.jar), the hostname and port, etc. If you want an in-process Derby server, then you want derby.jar, EmbeddedDriver, and a URL that is appropriate for an embedded database.

  2. Put your driver JAR file only in Tomcat's lib/ directory.

  3. Don't put anything in Tomcat's conf/context.xml: there's really no reason for it. Instead, use your webapp's META-INF/context.xml to define your <Resource>.

The error "Cannot create JDBC driver of class '' for connect URL 'null' usually occurs because the JDBC driver is not in the right place (or in too many places, like Tomcat's lib/ directory but also in the webapp's WEB-INF/lib/ directory). Please verify that you have the right driver JAR file in the right place.

How does Access-Control-Allow-Origin header work?

Who can't control backend for Options 405 Method Not Allowed.
Workaround for Chrome browser.
execute in command line:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="path_to_profile"
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:\Users\vital\AppData\Local\Google\Chrome\User Data\Profile 2"

Importing a function from a class in another file?

It would really help if you'd include the code that's not working (from the 'other' file), but I suspect you could do what you want with a healthy dose of the 'eval' function.

For example:

def run():
    print "this does nothing"

def chooser():
    return "run"

def main():
    '''works just like:

The chooser returns the name of the function to execute, eval then turns a string into actual code to be executed in-place, and the parentheses finish off the function call.

How to edit the size of the submit button on a form?

<input type="button" value="submit" style="height: 100px; width: 100px; left: 250; top: 250;">

Use this with your requirements.

Nginx: stat() failed (13: permission denied)

You can also add which user will run the nginx. In the nginx.conf file, make the following changes:

user root;

You can add the above line as the first line in your nginx conf. You can write the name of any user who has the permission to write in that directory.

Stored procedure or function expects parameter which is not supplied

in my case, I was passing all the parameters but one of the parameter my code was passing a null value for string.

Eg: cmd.Parameters.AddWithValue("@userName", userName);

in the above case, if the data type of userName is string, I was passing userName as null.

Android Spinner : Avoid onItemSelected calls during initialization

To avoid calling spinner.setOnItemSelectedListener() during initialization

spinner.setSelection(Adapter.NO_SELECTION, true); //Add this line before setting listener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {


    public void onNothingSelected(AdapterView<?> parent) {


Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

If you're using IntelliJ & Mac just go to Project structure -> SDK and make sure that there is Java listed but it points to sth like


Rather than user home...

CSS display:table-row does not expand when width is set to 100%

You can nest table-cell directly within table. You muslt have a table. Starting eith table-row does not work. Try it with this HTML:

    <style type="text/css">
.table {
  display: table;
  width: 100%;
.tr {
  display: table-row;
  width: 100%;
.td {
  display: table-cell;

    <div class="table">
      <div class="tr">
        <div class="td">
        <div class="td">
        <div class="td">

      <div class="tr">
        <div class="td">
        <div class="td">
        <div class="td">

    <div class="table">
        <div class="td">
        <div class="td">
        <div class="td">


How to disable logging on the standard error stream in Python?

No need to divert stdout. Here is better way to do it:

import logging
class MyLogHandler(logging.Handler):
    def emit(self, record):


An even simpler way is:


A cycle was detected in the build path of project xxx - Build Path Problem

Eclipse had a bug which reported more cycles than necessary. This has been fixed with the 2019-12 release. See

How to store a dataframe using Pandas

Pickle works good!

import pandas as pd
df.to_pickle('123.pkl')    #to save the dataframe, df to 123.pkl
df1 = pd.read_pickle('123.pkl') #to load 123.pkl back to the dataframe df

Passing parameters to a JDBC PreparedStatement

The problem was that you needed to add " ' ;" at the end.

Disable pasting text into HTML form

I did something similar to this for - there I wanted to detect when a user copied something into an HTML field. The implementation I came up with was to check the field constantly to see if at any time there was suddenly a whole lot of text in there.

In other words: if once milisecond ago there was no text, and now there are more than 5 chars... then the user probably pasted something in the field.

If you want to see this working in Bookmarkchamp (you need to be registered), paste a URL into the URL field (or drag and drop a URL in there).

How can I filter a date of a DateTimeField in Django?


// edit after comments

YourModel.objects.filter(datetime_published=datetime(2008, 03, 27))

doest not work because it creates a datetime object with time values set to 0, so the time in database doesn't match.

AttributeError: 'module' object has no attribute 'urlopen'

One of the possible way to do it:

import urllib

    # Python 2
    from urllib2 import urlopen
except ImportError:
    # Python 3
    from urllib.request import urlopen

How does one generate a random number in Apple's Swift language?

@jstn's answer is good, but a bit verbose. Swift is known as a protocol-oriented language, so we can achieve the same result without having to implement boilerplate code for every class in the integer family, by adding a default implementation for the protocol extension.

public extension ExpressibleByIntegerLiteral {
    public static func arc4random() -> Self {
        var r: Self = 0
        arc4random_buf(&r, MemoryLayout<Self>.size)
        return r

Now we can do:

let i = Int.arc4random()
let j = UInt32.arc4random()

and all other integer classes are ok.

How do I compare a value to a backslash?

When you only need to check for equality, you can also simply use the in operator to do a membership test in a sequence of accepted elements:

if message.value[0] in ('/', '\\'):

How can I get nth element from a list?

An alternative to using (!!) is to use the lens package and its element function and associated operators. The lens provides a uniform interface for accessing a wide variety of structures and nested structures above and beyond lists. Below I will focus on providing examples and will gloss over both the type signatures and the theory behind the lens package. If you want to know more about the theory a good place to start is the readme file at the github repo.

Accessing lists and other datatypes

Getting access to the lens package

At the command line:

$ cabal install lens
$ ghci
GHCi, version 7.6.3:  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
> import Control.Lens

Accessing lists

To access a list with the infix operator

> [1,2,3,4,5] ^? element 2  -- 0 based indexing
Just 3

Unlike the (!!) this will not throw an exception when accessing an element out of bounds and will return Nothing instead. It is often recommend to avoid partial functions like (!!) or head since they have more corner cases and are more likely to cause a run time error. You can read a little more about why to avoid partial functions at this wiki page.

> [1,2,3] !! 9
*** Exception: Prelude.(!!): index too large

> [1,2,3] ^? element 9

You can force the lens technique to be a partial function and throw an exception when out of bounds by using the (^?!) operator instead of the (^?) operator.

> [1,2,3] ^?! element 1
> [1,2,3] ^?! element 9
*** Exception: (^?!): empty Fold

Working with types other than lists

This is not just limited to lists however. For example the same technique works on trees from the standard containers package.

 > import Data.Tree
 > :{
  tree = Node 1 [
       Node 2 [Node 4[], Node 5 []]
     , Node 3 [Node 6 [], Node 7 []]
> putStrLn . drawTree . fmap show $tree
+- 2
|  |
|  +- 4
|  |
|  `- 5
`- 3
   +- 6
   `- 7

We can now access the elements of the tree in depth-first order:

> tree ^? element 0
Just 1
> tree ^? element 1
Just 2
> tree ^? element 2
Just 4
> tree ^? element 3
Just 5
> tree ^? element 4
Just 3
> tree ^? element 5
Just 6
> tree ^? element 6
Just 7

We can also access sequences from the containers package:

> import qualified Data.Sequence as Seq
> Seq.fromList [1,2,3,4] ^? element 3
Just 4

We can access the standard int indexed arrays from the vector package, text from the standard text package, bytestrings fro the standard bytestring package, and many other standard data structures. This standard method of access can be extended to your personal data structures by making them an instance of the typeclass Taversable, see a longer list of example Traversables in the Lens documentation..

Nested structures

Digging down into nested structures is simple with the lens hackage. For example accessing an element in a list of lists:

> [[1,2,3],[4,5,6]] ^? element 0 . element 1
Just 2
> [[1,2,3],[4,5,6]] ^? element 1 . element 2
Just 6

This composition works even when the nested data structures are of different types. So for example if I had a list of trees:

> :{
  tree = Node 1 [
       Node 2 []
     , Node 3 []
> putStrLn . drawTree . fmap show $ tree
+- 2
`- 3
> :{
  listOfTrees = [ tree
      , fmap (*2) tree -- All tree elements times 2
      , fmap (*3) tree -- All tree elements times 3

> listOfTrees ^? element 1 . element 0
Just 2
> listOfTrees ^? element 1 . element 1
Just 4

You can nest arbitrarily deeply with arbitrary types as long as they meet the Traversable requirement. So accessing a list of trees of sequences of text is no sweat.

Changing the nth element

A common operation in many languages is to assign to an indexed position in an array. In python you might:

>>> a = [1,2,3,4,5]
>>> a[3] = 9
>>> a
[1, 2, 3, 9, 5]

The lens package gives this functionality with the (.~) operator. Though unlike in python the original list is not mutated, rather a new list is returned.

> let a = [1,2,3,4,5]
> a & element 3 .~ 9
> a

element 3 .~ 9 is just a function and the (&) operator, part of the lens package, is just reverse function application. Here it is with the more common function application.

> (element 3 .~ 9) [1,2,3,4,5]

Assignment again works perfectly fine with arbitrary nesting of Traversables.

> [[1,2,3],[4,5,6]] & element 0 . element 1 .~ 9

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

Change from @Controller to @Service to CompteController and add @Service annotation to CompteDAOHib. Let me know if you still face this issue.

Crystal Reports 13 And Asp.Net 3.5

I had faced the same issue because of some dll files were missing from References of VS13. I went to the location and installed the newest pack. It resolved the issue.

How to check string length with JavaScript

UPDATE: Since I wrote this, the input event has gotten a decent level of support. It is still not 100% in IE9, so you will have to wait a bit until IE9 is fully phased out. In light of my answer to this question, however, input is more than a decent replacement for the method I've presented, so I recommend switching.

Use keyup event

var inp = document.getElementById('myinput');_x000D_
var chars = document.getElementById('chars');_x000D_
inp.onkeyup = function() {_x000D_
  chars.innerHTML = inp.value.length;_x000D_
<input id="myinput"><span id="chars">0</span>


Just a note for those that suggest keydown. That won't work. The keydown fires before character is added to the input box or textarea, so the length of the value would be wrong (one step behind). Therefore, the only solution that works is keyup, which fires after the character is added.

Understanding the Gemfile.lock file

It looks to me like PATH lists the first-generation dependencies directly from your gemspec, whereas GEM lists second-generation dependencies (i.e. what your dependencies depend on) and those from your Gemfile. PATH::remote is . because it relied on a local gemspec in the current directory to find out what belongs in PATH::spec, whereas GEM::remote is, since that's where it had to go to find out what belongs in GEM::spec.

In a Rails plugin, you'll see a PATH section, but not in a Rails app. Since the app doesn't have a gemspec file, there would be nothing to put in PATH.

As for DEPENDENCIES, states:

Runtime dependencies in your gemspec are treated like base dependencies, 
and development dependencies are added by default to the group, :development

The Gemfile generated by rails plugin new my_plugin says something similar:

# Bundler will treat runtime dependencies like base dependencies, and
# development dependencies will be added by default to the :development group.

What this means is that the difference between

s.add_development_dependency "july" # (1)


s.add_dependency "july" # (2)

is that (1) will only include "july" in Gemfile.lock (and therefore in the application) in a development environment. So when you run bundle install, you'll see "july" not only under PATH but also under DEPENDENCIES, but only in development. In production, it won't be there at all. However, when you use (2), you'll see "july" only in PATH, not in DEPENDENCIES, but it will show up when you bundle install from a production environment (i.e. in some other gem that includes yours as a dependency), not only development.

These are just my observations and I can't fully explain why any of this is the way it is but I welcome further comments.

Bloomberg Open API

Since the data is not free, you can use this Bloomberg API Emulator (disclaimer: it's my project) to learn how to send requests and make subscriptions. This emulator looks and acts just like the real Bloomberg API, although it doesn't return real data. In my time developing applications that use the Bloomberg API, I rarely care about the actual data that I'm handling; I care about how to retrieve data.

If you want to learn how to use the Bloomberg API give it a try. If you want to test out your code without an account, use this. A Bloomberg account costs about $2,000 a month, so you can save a lot with this project.

The emulator now supports Java and C++ in addition to C#.

C#, C++, and Java:

  • Intraday Tick Requests
  • Intraday Bar Requests
  • Reference Data Requests
  • Historical Data Requests
  • Market Data Subscriptions

Edit: Updated Project link, moved to github

Android: How to Programmatically set the size of a Layout


This should work:

// Gets linearlayout
LinearLayout layout = findViewById(;
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = 100;
params.width = 100;

If you want to convert dip to pixels, use this:

int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, <HEIGHT>, getResources().getDisplayMetrics());


How do I monitor all incoming http requests?

Guys found the perfect way to monitor ALL traffic that is flowing locally between requests from my machine to my machine:

  1. Install Wireshark

  2. When you need to capture traffic that is flowing from a localhost to a localhost then you will struggle to use wireshark as this only monitors incoming traffic on the network card. The way to do this is to add a route to windows that will force all traffic through a gateway and this be captured on the network interface.

    To do this, add a route with <ip address> <gateway>:

     cmd> route add
  3. Then run a capture on wireshark (make sure you select the interface that has bytes flowing through it) Then filter.

The newly added routes will come up in black. (as they are local addresses)

Export HTML table to pdf using jspdf

Here is working example:

in head

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


<script type="text/javascript">
        function demoFromHTML() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            // source can be HTML-formatted string, or a reference
            // to an actual DOM element from which the text will be scraped.
            source = $('#customers')[0];

            // we support special element handlers. Register them with jQuery-style 
            // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
            // There is no support for any other type of selectors 
            // (class, of compound) at this time.
            specialElementHandlers = {
                // element with id of "bypass" - jQuery style selector
                '#bypassme': function(element, renderer) {
                    // true = "handled elsewhere, bypass text extraction"
                    return true
            margins = {
                top: 80,
                bottom: 60,
                left: 40,
                width: 522
            // all coords and widths are in jsPDF instance's declared units
            // 'inches' in this case
                    source, // HTML string or DOM elem ref.
                    margins.left, // x coord
          , {// y coord
                        'width': margins.width, // max width of content on PDF
                        'elementHandlers': specialElementHandlers
            function(dispose) {
                // dispose: object with X, Y of the last line add to the PDF 
                //          this allow the insertion of new lines after html
            , margins);

and table:

<div id="customers">
        <table id="tab_customers" class="table table-striped" >
                <col width="20%">
                <col width="20%">
                <col width="20%">
                <col width="20%">
                <tr class='warning'>
                    <td>March 24, 2014</td>
                    <td>March 24, 2014</td>
                    <td>United States</td>
                    <td>March 24, 2014</td>
                    <td>July 1, 2013</td>
                    <td>July 1, 2013</td>

and button to run:

<button onclick="javascript:demoFromHTML()">PDF</button>

and working example online:

tabel to pdf jspdf

or try this: HTML Table Export

Removing Duplicate Values from ArrayList

list =;
This could be one of the solutions using Java8 Stream API. Hope this helps.

Node update a specific package

Always you can do it manually. Those are the steps:

  • Go to the NPM package page, and search for the GitHub link.
  • Now download the latest version using GitHub download link, or by clonning. git clone github_url
  • Copy the package to your node_modules folder for e.g. node_modules/browser-sync

Now it should work for you. To be sure it will not break in the future when you do npm i, continue the upcoming two steps:

  • Check the version of the new package by reading the package.json file in it's folder.
  • Open your project package.json and set the same version for where it's appear in the dependencies part of your package.json

While it's not recommened to do it manually. Sometimes it's good to understand how things are working under the hood, to be able to fix things. I found myself doing it from time to time.

Android Studio : unmappable character for encoding UTF-8

Check all 'C' characters. There are may be some cyrillic 'C's in english-looking word.
Reason for this is that in both english and russian keyboards 'C' occupies same physical button.

How to iterate over a JavaScript object?

Yes. You can loop through an object using for loop. Here is an example

var myObj = {_x000D_
    abc: 'ABC',_x000D_
    bca: 'BCA',_x000D_
    zzz: 'ZZZ',_x000D_
    xxx: 'XXX',_x000D_
    ccc: 'CCC',_x000D_
var k = Object.keys (myObj);_x000D_
for (var i = 0; i < k.length; i++) {_x000D_
    console.log (k[i] + ": " + myObj[k[i]]);_x000D_

NOTE: the example mentioned above will only work in IE9+. See Objec.keys browser support here.

How to alert using jQuery

Don't do this, but this is how you would do it:

$(".overdue").each(function() { 
    alert("Your book is overdue"); 

The reason I say "don't do it" is because nothing is more annoying to users, in my opinion, than repeated pop-ups that cannot be stopped. Instead, just use the length property and let them know that "You have X books overdue".

Check if PHP-page is accessed from an iOS device

51Degrees' PHP solution is able to do this. you can get the free Open Source API here You can use the HardwareFamily Property to determine if it is an iPad/iPod/iPhone etc.

Due to the nature of Apple's User-Agents the initial result will return a generic device, however if you are interested in the specific device you can use a JavaScript client side override to determine to specific model.

To do this you can implement something similar to the following logic once you have determined it is an Apple Device, in this case for an iPhone.

// iPhone model checks.
function getiPhoneModel() {
// iPhone 6 Plus
if ((window.screen.height / window.screen.width == 736 / 414) && 
(window.devicePixelRatio == 3)) {
return "iPhone 6 Plus";
// iPhone 6
else if ((window.screen.height / window.screen.width == 667 / 375) && 
(window.devicePixelRatio == 2)) {
return "iPhone 6";
// iPhone 5/5C/5S or 6 in zoom mode
else if ((window.screen.height / window.screen.width == 1.775) && 
(window.devicePixelRatio == 2)) {
return "iPhone 5, 5C, 5S or 6 (display zoom)";
// iPhone 4/4S
else if ((window.screen.height / window.screen.width == 1.5) && 
(window.devicePixelRatio == 2)) {
return "iPhone 4 or 4S";
// iPhone 1/3G/3GS
else if ((window.screen.height / window.screen.width == 1.5) && 
(window.devicePixelRatio == 1)) {
return "iPhone 1, 3G or 3GS";
} else {
return "Not an iPhone";

Or for an iPad

function getiPadVersion() {
var pixelRatio = getPixelRatio();
var return_string = "Not an iPad";
if (pixelRatio == 1 ) {
return_string = "iPad 1, iPad 2, iPad Mini 1";
if (pixelRatio == 2) {
return_string = "iPad 3, iPad 4, iPad Air 1, iPad Air 2, iPad Mini 2, iPad 
Mini 3";
return return_string;

For more information on research 51Degrees have done into Apple devices you can read their blog post here

Disclosure: I work for 51Degrees.

How can I add reflection to a C++ application?

And I would love a pony, but ponies aren't free. :-p is what you're going to get. Reflection like you're thinking about -- fully descriptive metadata available at runtime -- just doesn't exist for C++ by default.

How do I get the last day of a month?

You can find the last day of the month by a single line of code:

int maxdt = (new DateTime(dtfrom.Year, dtfrom.Month, 1).AddMonths(1).AddDays(-1)).Day;

Accessing elements by type in javascript

If you are lucky and need to care only for recent browsers, you can use:


"recent" means not IE6 and IE7

How do I add a project as a dependency of another project?

Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so


That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.

If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

|- pom.xml
|- MyEJBProject
|   `- pom.xml
`- MyWarProject
    `- pom.xml

The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)



That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects

Finally, if your projects are not in related directories, you might try to give them as relative modules:

 |- mywarproject
 |   `pom.xml
 |- myejbproject
 |   `pom.xml
 `- parent

now you could just do this (worked in maven 2, just tried it):


Display unescaped HTML in Vue.js

You can read that here

If you use

{{<br />}}

it'll be escaped. If you want raw html, you gotta use

{{{<br />}}}

EDIT (Feb 5 2017): As @hitautodestruct points out, in vue 2 you should use v-html instead of triple curly braces.

Which command do I use to generate the build of a Vue app?

If you want to build and send to your remote server you can use cli-service ( you can create tasks to serve, build and one to deploy with some specific plugins as vue-cli-plugin-s3-deploy

".addEventListener is not a function" why does this error occur?

The first line of your code returns an array and assigns it to the var comment, when what you want is an element assigned to the var comment...

var comment = document.getElementsByClassName("button");

So you are trying to use the method addEventListener() on the array when you need to use the method addEventListener() on the actual element within the array. You need to return an element not an array by accessing the element within the array so the var comment itself is assigned an element not an array.


var comment = document.getElementsByClassName("button");


var comment = document.getElementsByClassName("button")[0];

How do you run a Python script as a service in Windows?

  1. Follow up the

  2. changing the dll folder

I know this is old but I was stuck on this forever. For me, this specific problem was solved by copying this file - pywintypes36.dll

From -> Python36\Lib\site-packages\pywin32_system32

To -> Python36\Lib\site-packages\win32

setx /M PATH "%PATH%;C:\Users\user\AppData\Local\Programs\Python\Python38-32;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Scripts;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pywin32_system32;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\win32
  1. changing the path to python folder by

cd C:\Users\user\AppData\Local\Programs\Python\Python38-32

  1. NET START PySvc
  2. NET STOP PySvc

axios post request to send form data

Upload (multiple) binary files


Things become complicated when you want to post files via multipart/form-data, especially multiple binary files. Below is a working example:

const FormData = require('form-data')
const fs = require('fs')
const path = require('path')

const formData = new FormData()
formData.append('files[]', JSON.stringify({ to: [{ phoneNumber: process.env.RINGCENTRAL_RECEIVER }] }), 'test.json')
formData.append('files[]', fs.createReadStream(path.join(__dirname, 'test.png')), 'test.png')
await'/restapi/v1.0/account/~/extension/~/fax', formData, {
  headers: formData.getHeaders()
  • Instead of headers: {'Content-Type': 'multipart/form-data' } I prefer headers: formData.getHeaders()
  • I use async and await above, you can change them to plain Promise statements if you don't like them
  • In order to add your own headers, you just headers: { ...yourHeaders, ...formData.getHeaders() }

Newly added content below:


Browser's FormData is different from the NPM package 'form-data'. The following code works for me in browser:


<input type="file" id="image" accept="image/png"/>


const formData = new FormData()

// add a non-binary file
formData.append('files[]', new Blob(['{"hello": "world"}'], { type: 'application/json' }), 'request.json')

// add a binary file
const element = document.getElementById('image')
const file = element.files[0]
formData.append('files[]', file,
await'/restapi/v1.0/account/~/extension/~/fax', formData)

Java error: Only a type can be imported. XYZ resolves to a package

Got this exception as well.

Environment: Mac with Eclipse running Tomcat from inside Eclipse using Servers view.

For any reason Eclipse does not copy classes folder to WEB-INF. After classes folder was manually copied, everything works fine.

Don't know, or it is Eclipse bug or I missed something.

How to execute INSERT statement using JdbcTemplate class from Spring Framework

You'll need a datasource for working with JdbcTemplate.

JdbcTemplate template = new JdbcTemplate(yourDataSource);

    new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection)
            throws SQLException {

            PreparedStatement statement = connection.prepareStatement(ourInsertQuery);
            //statement.setLong(1, beginning); set parameters you need in your insert

            return statement;

How to read the output from git diff?

Here's the simple example.

diff --git a/file b/file 
index 10ff2df..84d4fa2 100644
--- a/file
+++ b/file
@@ -1,5 +1,5 @@
-this line will be deleted
+this line is added

Here's an explanation (see details here).

  • --git is not a command, this means it's a git version of diff (not unix)
  • a/ b/ are directories, they are not real. it's just a convenience when we deal with the same file (in my case a/ is in index and b/ is in working directory)
  • 10ff2df..84d4fa2 are blob IDs of these 2 files
  • 100644 is the “mode bits,” indicating that this is a regular file (not executable and not a symbolic link)
  • --- a/file +++ b/file minus signs shows lines in the a/ version but missing from the b/ version; and plus signs shows lines missing in a/ but present in b/ (in my case --- means deleted lines and +++ means added lines in b/ and this the file in the working directory)
  • @@ -1,5 +1,5 @@ in order to understand this it's better to work with a big file; if you have two changes in different places you'll get two entries like @@ -1,5 +1,5 @@; suppose you have file line1 ... line100 and deleted line10 and add new line100 - you'll get:
@@ -7,7 +7,6 @@ line6
-this line10 to be deleted
@@ -98,3 +97,4 @@ line97
+this is new line100

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like or where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.


Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
        Require all granted

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

Remove Null Value from String array in java

Those are zero-length strings, not null. But if you want to remove them:

firstArray[0] refers to the first element
firstArray[1] refers to the second element

You can move the second into the first thusly:

firstArray[0]  = firstArray[1]

If you were to do this for elements [1,2], then [2,3], etc. you would eventually shift the entire contents of the array to the left, eliminating element 0. Can you see how that would apply?

Where is Ubuntu storing installed programs?

If you are looking for the folder such as brushes, curves, etc. you can try:


This folder will contain all the gimp folders.

Good Luck.

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

% ...    
% ...

Input & Output& Action return \\
DNF &  simulation & jsp\\

Kill some processes by .exe file name

If you have the process ID (PID) you can kill this process as follow:

Process processToKill = Process.GetProcessById(pid);

Add params to given URL in Python

python3, self explanatory I guess

from urllib.parse import urlparse, urlencode, parse_qsl

url = ''

parsed = urlparse(url)
current_params = dict(parse_qsl(parsed.query))
new_params = {'location': 'United States'}
merged_params = urlencode({**current_params, **new_params})
parsed = parsed._replace(query=merged_params)


How do I convert seconds to hours, minutes and seconds?

dateutil.relativedelta is convenient if you need to access hours, minutes and seconds as floats as well. datetime.timedelta does not provide a similar interface.

from dateutil.relativedelta import relativedelta
rt = relativedelta(seconds=5440)
    int(rt.hours), int(rt.minutes), int(rt.seconds)))



What is a deadlock?

Above some explanations are nice. Hope this may also useful:

In a database, when a session (e.g. ora) wants a resource held by another session (e.g. data), but that session (data) also wants a resource which is held by the first session (ora). There can be more than 2 sessions involved also but idea will be the same. Actually, Deadlocks prevent some transactions from continuing to work. For example: Suppose, ORA-DATA holds lock A and requests lock B And SKU holds lock B and requests lock A.


beyond top level package error in relative import

As the most popular answer suggests, basically its because your PYTHONPATH or sys.path includes . but not your path to your package. And the relative import is relative to your current working directory, not the file where the import happens; oddly.

You could fix this by first changing your relative import to absolute and then either starting it with:

PYTHONPATH=/path/to/package python -m test_A.test

OR forcing the python path when called this way, because:

With python -m test_A.test you're executing test_A/ with __name__ == '__main__' and __file__ == '/absolute/path/to/test_A/'

That means that in you could use your absolute import semi-protected in the main case condition and also do some one-time Python path manipulation:

from os import path
def main():
if __name__ == '__main__':
    import sys
    sys.path.append(path.join(path.dirname(__file__), '..'))
    from A import foo


Insert a string at a specific index

I wanted to compare the method using substring and the method using slice from Base33 and user113716 respectively, to do that I wrote some code

also have a look at this performance comparison, substring, slice

The code I used creates huge strings and inserts the string "bar " multiple times into the huge string

if (!String.prototype.splice) {
     * {JSDoc}
     * The splice() method changes the content of a string by removing a range of
     * characters and/or adding new characters.
     * @this {String}
     * @param {number} start Index at which to start changing the string.
     * @param {number} delCount An integer indicating the number of old chars to remove.
     * @param {string} newSubStr The String that is spliced in.
     * @return {string} A new string with the spliced substring.
    String.prototype.splice = function (start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));

String.prototype.splice = function (idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));

String.prototype.insert = function (index, string) {
    if (index > 0)
        return this.substring(0, index) + string + this.substring(index, this.length);

    return string + this;

function createString(size) {
    var s = ""
    for (var i = 0; i < size; i++) {
        s += "Some String "
    return s

function testSubStringPerformance(str, times) {
    for (var i = 0; i < times; i++)
        str.insert(4, "bar ")

function testSpliceStringPerformance(str, times) {
    for (var i = 0; i < times; i++)
        str.splice(4, 0, "bar ")

function doTests(repeatMax, sSizeMax) {
    n = 1000
    sSize = 1000
    for (var i = 1; i <= repeatMax; i++) {
        var repeatTimes = n * (10 * i)
        for (var j = 1; j <= sSizeMax; j++) {
            var actualStringSize = sSize *  (10 * j)
            var s1 = createString(actualStringSize)
            var s2 = createString(actualStringSize)
            var start =
            testSubStringPerformance(s1, repeatTimes)
            var end =
            var subStrPerf = end - start

            start =
            testSpliceStringPerformance(s2, repeatTimes)
            end =
            var splicePerf = end - start

                "string size           =", "Some String ".length * actualStringSize, "\n",
                "repeat count          = ", repeatTimes, "\n",
                "splice performance    = ", splicePerf, "\n",
                "substring performance = ", subStrPerf, "\n",
                "difference = ", splicePerf - subStrPerf  // + = splice is faster, - = subStr is faster


doTests(1, 100)

The general difference in performance is marginal at best and both methods work just fine (even on strings of length ~~ 12000000)

How to install and use "make" in Windows?

  1. Install npm
  2. install Node
  3. Install Make node install make up node install make if above commands displays any error then install Chocolatey(choco) Open cmd and copy and paste the below command (command copied from chocolatey URL) @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command " [System.Net.ServicePointManager]::SecurityProtocol = 3072; iex ((New-Object System.Net.WebClient).DownloadString(''))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"

How can I tell AngularJS to "refresh"

The solution was to call...

$scope.$apply(); my jQuery event callback.

What is the best way to left align and right align two div tags?

This solution has left aligned text and button on the far right.

If anyone is looking for a material design answer:

<div layout="column" layout-align="start start">
 <div layout="row" style="width:100%">
    <div flex="grow">Left Aligned text</div>
    <md-button aria-label="help" ng-click="showHelpDialog()">
      <md-icon md-svg-icon="help"></md-icon>

Disable all Database related auto configuration in Spring Boot

Also if you use Spring Actuator org.springframework.boot.actuate.autoconfigure.jdbc.DataSourceHealthContributorAutoConfiguration might be initializing DataSource as well.

Interpreting segfault messages

Error 4 means "The cause was a user-mode read resulting in no page being found.". There's a tool that decodes it here.

Here's the definition from the kernel. Keep in mind that 4 means that bit 2 is set and no other bits are set. If you convert it to binary that becomes clear.

 * Page fault error code bits
 *      bit 0 == 0 means no page found, 1 means protection fault
 *      bit 1 == 0 means read, 1 means write
 *      bit 2 == 0 means kernel, 1 means user-mode
 *      bit 3 == 1 means use of reserved bit detected
 *      bit 4 == 1 means fault was an instruction fetch
#define PF_PROT         (1<<0)
#define PF_WRITE        (1<<1)
#define PF_USER         (1<<2)
#define PF_RSVD         (1<<3)
#define PF_INSTR        (1<<4)

Now then, "ip 00007f9bebcca90d" means the instruction pointer was at 0x00007f9bebcca90d when the segfault happened.

"[7f9beb83a000+f6f000]" tells you:

  • The object the crash was in: ""
  • The base address of that object "7f9beb83a000"
  • How big that object is: "f6f000"

If you take the base address and subtract it from the ip, you get the offset into that object:

0x00007f9bebcca90d - 0x7f9beb83a000 = 0x49090D

Then you can run addr2line on it:

addr2line -e /usr/lib64/qt45/lib/ -fCi 0x49090D

In my case it wasn't successful, either the copy I installed isn't identical to yours, or it's stripped.

Pie chart with jQuery

jqPlot looks pretty good and it is open source.

Here's a link to the most impressive and up-to-date jqPlot examples.

How to put a link on a button with bootstrap?

Another trick to get the link color working correctly inside the <button> markup

<button type="button" class="btn btn-outline-success and-all-other-classes"> 
  <a href="#" style="color:inherit"> Button text with correct colors </a>

Please keep in mind that in bs4 beta e.g. btn-primary-outline changed to btn-outline-primary

What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism?

spark.default.parallelism is the default number of partition set by spark which is by default 200. and if you want to increase the number of partition than you can apply the property spark.sql.shuffle.partitions to set number of partition in the spark configuration or while running spark SQL.

Normally this spark.sql.shuffle.partitions it is being used when we have a memory congestion and we see below error: spark error:java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE

so set your can allocate a partition as 256 MB per partition and that you can use to set for your processes.

also If number of partitions is near to 2000 then increase it to more than 2000. As spark applies different logic for partition < 2000 and > 2000 which will increase your code performance by decreasing the memory footprint as data default is highly compressed if >2000.

Clear dropdownlist with JQuery

<select id="ddlvalue" name="ddlvaluename">
<option value='0' disabled selected>Select Value</option>
<option value='1' >Value 1</option>
<option value='2' >Value 2</option>

<input type="submit" id="btn_submit" value="click me"/>


UIImageView - How to get the file name of the image assigned?

use below

 UIImageView *imageView = ((UIImageView *)(barButtonItem.customView.subviews.lastObject));
 file_name = imageView.accessibilityLabel;

chai test array equality doesn't work as expected

import chai from 'chai';
const arr1 = [2, 1];
const arr2 = [2, 1];
chai.expect(arr1).to.eql(arr2); // Will pass. `eql` is data compare instead of object compare.

/usr/lib/ version `GLIBCXX_3.4.15' not found

I got same error. This is how it worked for me:

  • cleaned the project under currently installed gcc
  • recompiled it

Worked perfectly!

Exposing the current state name with ui router

In my current project the solution looks like this:

I created an abstract Language State

$stateProvider.state('language', {
    abstract: true,
    url: '/:language',
    template: '<div ui-view class="lang-{{language}}"></div>'

Every state in the project has to depend on this state

$stateProvider.state('language.dashboard', {
    url: '/dashboard'

The language switch buttons calls a custom function:

<a ng-click="footer.setLanguage('de')">de</a>

And the corresponding function looks like this (inside a controller of course):

this.setLanguage = function(lang) {
    FooterLog.log('switch to language', lang);
    $state.go($state.current, { language: lang }, {
        location: true,
        reload: true,
        inherit: true
    }).then(function() {
        FooterLog.log('transition successfull');

This works, but there is a nicer solution just changing a value in the state params from html:

<a ui-sref="{ language: 'de' }">de</a>

Unfortunately this does not work, see

Returning multiple values from a C++ function

Quick answer:

#include <iostream>
using namespace std;

// different values of [operate] can return different number.
int yourFunction(int a, int b, int operate)
    a = 1;
    b = 2;

    if (operate== 1)
        return a;
        return b;

int main()
    int a, b;

    a = yourFunction(a, b, 1); // get return 1
    b = yourFunction(a, b, 2); // get return 2

    return 0;

Read file data without saving it in Flask

in function

def handleUpload():
    if 'photo' in request.files:
        photo = request.files['photo']
        if photo.filename != '':      
            image = request.files['photo']  
            image_string = base64.b64encode(
            image_string = image_string.decode('utf-8')
            #use this to remove b'...' to get raw string
            return render_template('handleUpload.html',filestring = image_string)
    return render_template('upload.html')

in html file

    <title>Simple file upload using Python Flask</title>
    {% if filestring %}
      <h1>Raw image:</h1>
      <img src="data:image/png;base64, {{filestring}}" alt="alternate" />.
    {% else %}
    {% endif %}

Simple pthread! C++

Linkage. Try this:

extern "C" void *print_message() {...

Change the content of a div based on selection from dropdown menu

I am not a coder, but you could save a few lines:

            <select onchange="if(selectedIndex!=0)document.getElementById('less_is_more').innerHTML=options[selectedIndex].value;">
                <option value="">hire me for real estate</option>
                <option value="me!!!">Who is a good Broker? </option>
                <option value="yes!!!">Can I buy a house with no down payment</option>
                <option value="send me a note!">Get my contact info?</option>

<div id="less_is_more"></div>

Here is demo.

How to convert object to Dictionary<TKey, TValue> in C#?

I use this simple method:

public Dictionary<string, string> objToDict(XYZ.ObjectCollection objs) {
    var dict = new Dictionary<string, string>();
    foreach (KeyValuePair<string, string> each in objs){
        dict.Add(each.Key, each.Value);
    return dict;

how can the textbox width be reduced?

<input type='text' 
       placeholder='typing some text' >

This is the text box, it has a fixed length of 10 characters, and if you can try but this text box does not contain maximum length 10 character

C# LINQ find duplicates in List

there is an answer but i did not understand why is not working;

var anyDuplicate = enumerable.GroupBy(x => x.Key).Any(g => g.Count() > 1);

my solution is like that in this situation;

var duplicates = model.list
                    .GroupBy(s => s.SAME_ID)
                    .Where(g => g.Count() > 1).Count() > 0;
if(duplicates) {

Perl: Use s/ (replace) and return new string

print "bla: ", $myvar =~ tr{a}{b},"\n";

How can I check if a URL exists via PHP?

cURL can return HTTP code I don’t think all that extra code is necessary?

function urlExists($url=NULL)
        if($url == NULL) return false;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if($httpcode>=200 && $httpcode<300){
            return true;
        } else {
            return false;

How to pass the button value into my onclick event function?

Maybe you can take a look at closure in JavaScript. Here is a working solution:

<!DOCTYPE html>_x000D_
        <meta charset="utf-8" />_x000D_
        <p class="button">Button 0</p>_x000D_
        <p class="button">Button 1</p>_x000D_
        <p class="button">Button 2</p>_x000D_
            var buttons = document.getElementsByClassName('button');_x000D_
            for (var i=0 ; i < buttons.length ; i++){_x000D_
                buttons[index].onclick = function(){_x000D_
                  alert("I am button " + index);_x000D_

How to show data in a table by using psql command line interface?

On windows use the name of the table in quotes: TABLE "user"; or SELECT * FROM "user";

How can I read input from the console using the Scanner class in Java?

Scanner scan = new Scanner(;
String myLine = scan.nextLine();

Execute command without keeping it in history

Start your command with a space and it won't be included in the history.

Be aware that this does require the environment variable $HISTCONTROL to be set.

  • Check that the following command returns ignorespace or ignoreboth

    #> echo $HISTCONTROL
  • To add the environment variable if missing, the following line can be added to the bash profile. E.g. %HOME/.bashrc

    export HISTCONTROL=ignorespace

After sourcing the profile again space prefixed commands will not be written to $HISTFILE

How can I see CakePHP's SQL dump in the controller?

In CakePHP 1.2 ..

$db =& ConnectionManager::getDataSource('default');

How to redirect the output of an application in background to /dev/null

These will also redirect both:

yourcommand  &> /dev/null

yourcommand  >& /dev/null

though the bash manual says the first is preferred.

How to select first child with jQuery?

Hi we can use default method "first" in jQuery

Here some examples:

When you want to add class for first div

  $('.alldivs div').first().addClass('active');

When you want to change the remove the "onediv" class and add only to first child

   $('.alldivs div').removeClass('onediv').first().addClass('onediv');

ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error

If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY is not "V_ARRAY", then you are using different types; even if they are declared identically (e.g. both are table of number) this will not work.

You're hitting this data type compatibility restriction:

You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.

You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.

invalid target release: 1.7

You need to set JAVA_HOME to your jdk7 home directory, for example on Microsoft Windows:

  • "C:\Program Files\Java\jdk1.7.0_40"

or on OS X:

  • /Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home

JComboBox Selection Change Listener?

Code example of ItemListener implementation

class ItemChangeListener implements ItemListener{
    public void itemStateChanged(ItemEvent event) {
       if (event.getStateChange() == ItemEvent.SELECTED) {
          Object item = event.getItem();
          // do something with object

Now we will get only selected item.

Then just add listener to your JComboBox

addItemListener(new ItemChangeListener());

What is a difference between unsigned int and signed int in C?

Here is the very nice link which explains the storage of signed and unsigned INT in C -

Taken from this above article -

"process called two's complement is used to transform positive numbers into negative numbers. The side effect of this is that the most significant bit is used to tell the computer if the number is positive or negative. If the most significant bit is a 1, then the number is negative. If it's 0, the number is positive."

undefined offset PHP error

If preg_match did not find a match, $matches is an empty array. So you should check if preg_match found an match before accessing $matches[0], for example:

function get_match($regex,$content)
    if (preg_match($regex,$content,$matches)) {
        return $matches[0];
    } else {
        return null;

Converting ISO 8601-compliant String to java.util.Date

For Java version 7

You can follow Oracle documentation:

X - is used for ISO 8601 time zone

TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
String nowAsISO = df.format(new Date());


DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
//nowAsISO = "2013-05-31T00:00:00Z";
Date finalResult = df1.parse(nowAsISO);


Pandas convert dataframe to array of tuples

Many data sets are large enough that we need to concern ourselves with speed/efficiency. So I offer this solution in that spirit. It happens to also be succinct.

For the sake of comparison, let's drop the index column

df = data_set.drop('index', 1)

I'll propose the use of zip and map

list(zip(*map(df.get, df)))

[('2012-02-17', 24.75, 25.03),
 ('2012-02-16', 25.0, 25.07),
 ('2012-02-15', 24.99, 25.15),
 ('2012-02-14', 24.68, 25.05),
 ('2012-02-13', 24.62, 24.77),
 ('2012-02-10', 24.38, 24.61)]

It happens to also be flexible if we wanted to deal with a specific subset of columns. We'll assume the columns we've already displayed are the subset we want.

list(zip(*map(df.get, ['data_date', 'data_1', 'data_2'])))

[('2012-02-17', 24.75, 25.03),
 ('2012-02-16', 25.0, 25.07),
 ('2012-02-15', 24.99, 25.15),
 ('2012-02-14', 24.68, 25.05),
 ('2012-02-13', 24.62, 24.77),
 ('2012-02-10', 24.38, 24.61)]

What is Quicker?

Turn's out records is quickest followed by asymptotically converging zipmap and iter_tuples

I'll use a library simple_benchmarks that I got from this post

from simple_benchmark import BenchmarkBuilder
b = BenchmarkBuilder()

import pandas as pd
import numpy as np

def tuple_comp(df): return [tuple(x) for x in df.to_numpy()]
def iter_namedtuples(df): return list(df.itertuples(index=False))
def iter_tuples(df): return list(df.itertuples(index=False, name=None))
def records(df): return df.to_records(index=False).tolist()
def zipmap(df): return list(zip(*map(df.get, df)))

funcs = [tuple_comp, iter_namedtuples, iter_tuples, records, zipmap]
for func in funcs:

def creator(n):
    return pd.DataFrame({"A": random.randint(n, size=n), "B": random.randint(n, size=n)})

@b.add_arguments('Rows in DataFrame')
def argument_provider():
    for n in (10 ** (np.arange(4, 11) / 2)).astype(int):
        yield n, creator(n)

r =

Check the results

r.to_pandas_dataframe().pipe(lambda d: d.div(d.min(1), 0))

        tuple_comp  iter_namedtuples  iter_tuples   records    zipmap
100       2.905662          6.626308     3.450741  1.469471  1.000000
316       4.612692          4.814433     2.375874  1.096352  1.000000
1000      6.513121          4.106426     1.958293  1.000000  1.316303
3162      8.446138          4.082161     1.808339  1.000000  1.533605
10000     8.424483          3.621461     1.651831  1.000000  1.558592
31622     7.813803          3.386592     1.586483  1.000000  1.515478
100000    7.050572          3.162426     1.499977  1.000000  1.480131


enter image description here

Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running

I had the same issue, but I have resolved it the next:

1) Install jdk1.8...

2) In AndroidStudio File->Project Structure->SDK Location, select your directory where the JDK is located, by default Studio uses embedded JDK but for some reason it produces error=216.

3) Click Ok.

What is the purpose of the "final" keyword in C++11 for functions?

Supplement to Mario Knezovic 's answer:

class IA
  virtual int getNum() const = 0;

class BaseA : public IA
 inline virtual int getNum() const final {return ...};

class ImplA : public BaseA {...};

IA* pa = ...;
ImplA* impla = static_cast<ImplA*>(pa);

//the following line should cause compiler to use the inlined function BaseA::getNum(), 
//instead of dynamic binding (via vtable or something).
//any class/subclass of BaseA will benefit from it

int n = impla->getNum();

The above code shows the theory, but not actually tested on real compilers. Much appreciated if anyone paste a disassembled output.

Why do I get an error instantiating an interface?

You cannot instantiate an abstract class or interface. You must inherit it, if its an abstract class, or implement it if it's an interface. e.g.

private class User : IUser

User u = new User();

How can I represent an 'Enum' in Python?

On 2013-05-10, Guido agreed to accept PEP 435 into the Python 3.4 standard library. This means that Python finally has builtin support for enumerations!

There is a backport available for Python 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4. It's on Pypi as enum34.


>>> from enum import Enum
>>> class Color(Enum):
...     red = 1
...     green = 2
...     blue = 3


>>> print(
>>> print(repr(
< 1>


>>> for color in Color:
...   print(color)

Programmatic access:

>>> Color(1)
>>> Color['blue']

For more information, refer to the proposal. Official documentation will probably follow soon.

TypeError: a bytes-like object is required, not 'str' in python and CSV

I had the same issue with Python3. My code was writing into io.BytesIO().

Replacing with io.StringIO() solved.

how to fire event on file select

Do whatever you want to do after the file loads successfully.just after the completion of your file processing set the value of file control to blank the .change() will always be called even the file name changes or not. like for example you can do this thing and worked for me like charm

  $('#myFile').change(function () {
    LoadFile("myFile");//function to do processing of file.
    $('#myFile').val('');// set the value to empty of myfile control.

How do I change the hover over color for a hover over table in Bootstrap?

Try Bootstrap’s .table-hover class to implement hoverable rows, for example

<table class="table table-hover">

Email and phone Number Validation in android

For check email and phone number you need to do that

public static boolean isValidMobile(String phone) {
    boolean check = false;
    if (!Pattern.matches("[a-zA-Z]+", phone)) {
        if (phone.length() < 9 || phone.length() > 13) {
            // if(phone.length() != 10) {
            check = false;
            // txtPhone.setError("Not Valid Number");
        } else {
            check = android.util.Patterns.PHONE.matcher(phone).matches();
    } else {
        check = false;
    return check;

public static boolean isEmailValid(String email) {
    boolean check;
    Pattern p;
    Matcher m;

    String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    p = Pattern.compile(EMAIL_STRING);

    m = p.matcher(email);
    check = m.matches();

    return check;

String enter_mob_or_email="";//1234567890 or [email protected]
if (isValidMobile(enter_mob_or_email)) {// Phone number is valid

}else isEmailValid(enter_mob_or_email){//Email is valid

}else{// Not valid email or phone number


What exactly is an instance in Java?

I think that Object = Instance. Reference is a "link" to an Object.

Car c = new Car();

variable c stores a reference to an object of type Car.

How to Cast Objects in PHP

I think that the best approach is to just create a new instance of a class and than assign the object. Here's what I would do:

public function ($someVO) {

     $someCastVO = new SomeVO();
     $someCastVO = $someVO;
     $someCastVO->SomePropertyInVO = "123";


Doing this will give you code hinting in most IDEs and help ensure you are using the correct properties.

Declaring variables inside loops, good practice or bad practice?

It's a very good practice, as all above answer provide very good theoretical aspect of the question let me give a glimpse of code, i was trying to solve DFS over GEEKSFORGEEKS, i encounter the optimization problem...... If you try to solve the code declaring the integer outside the loop will give you Optimization Error..

stack<int> st;
cout<<s<<" ";
int flag=0;
int top=0;
    top =;
    for(int i=0;i<g[top].size();i++){
        if(vis[g[top][i]] != 1){
            cout<<g[top][i]<<" ";

Now put integers inside the loop this will give you correct answer...

stack<int> st;
cout<<s<<" ";
// int flag=0;
// int top=0;
    int top =;
    int flag = 0;
    for(int i=0;i<g[top].size();i++){
        if(vis[g[top][i]] != 1){
            cout<<g[top][i]<<" ";

this completely reflect what sir @justin was saying in 2nd comment.... try this here just give it a shot.... you will get it.Hope this help.

How could I convert data from string to long in c#

You can also use long.TryParse and long.Parse.

long l1;
l1 = long.Parse("1100.25");
long.TryParse("1100.25", out l1);

How to create an exit message

I got here searching for a way to execute some code whenever the program ends.
Found this:

Kernel.at_exit { puts "sayonara" }
# do whatever
# [...]
# call #exit or #abort or just let the program end
# calling #exit! will skip the call

Called multiple times will register multiple handlers.

Remote Connections Mysql Ubuntu

You are using ubuntu 12 (quite old one)

First, Open the /etc/mysql/mysql.conf.d/mysqld.cnf file (/etc/mysql/my.cnf in Ubuntu 14.04 and earlier versions

Under the [mysqld] Locate the Line, bind-address = And change it to, bind-address = or comment it

Then, Restart the Ubuntu MysQL Server systemctl restart mysql.service

Now Ubuntu Server will allow remote access to the MySQL Server, But still you need to configure MySQL users to allow access from any host.

User must be 'username'@'%' with all the required grants

To make sure that, MySQL server listens on all interfaces, run the netstat command as follows.

netstat -tulnp | grep mysql

Hope this works !

Null vs. False vs. 0 in PHP

In PHP you can use === and !== operators to check not only if the values are equal but also if their types match. So for example: 0 == false is true, but 0 === false is false. The same goes for != versus !==. Also in case you compare null to the other two using the mentioned operators, expect similar results.

Now in PHP this quality of values is usually used when returning a value which sometimes can be 0 (zero), but sometimes it might be that the function failed. In such cases in PHP you return false and you have to check for these cases using the identity operator ===. For example if you are searching for a position of one string inside the other and you're using strpos(), this function will return the numeric position which can be 0 if the string is found at the very beginning, but if the string is not found at all, then strpos() will return false and you have to take this into account when dealing with the result.

If you will use the same technique in your functions, anybody familiar with the standard PHP library will understand what is going on and how to check if the returned value is what is wanted or did some error occur while processing. The same actually goes for function params, you can process them differently depending on if they are arrays or strings or what not, and this technique is used throughout PHP heavily too, so everybody will get it quite easily. So I guess that's the power.

How to get on scroll events?

// @HostListener('scroll', ['$event']) // for scroll events of the current element
@HostListener('window:scroll', ['$event']) // for window scroll events
onScroll(event) {


<div (scroll)="onScroll($event)"></div>

A TypeScript GUID class?

There is an implementation in my TypeScript utilities based on JavaScript GUID generators.

Here is the code:

class Guid {_x000D_
  static newGuid() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
      var r = Math.random() * 16 | 0,_x000D_
        v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
      return v.toString(16);_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
  var id = Guid.newGuid();_x000D_

Please note the following:

C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.

JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).

The project cannot be built until the build path errors are resolved.

just check if any unnecessary Jars are added in your library or not. if yes, then simply remove that jars from your library and clean your project once. Its worked for me.

Best way to test if a row exists in a MySQL table

In my research, I can find the result getting on following speed.

select * from table where condition=value
(1 total, Query took 0.0052 sec)

select exists(select * from table where condition=value)
(1 total, Query took 0.0008 sec)

select count(*) from table where condition=value limit 1) 
(1 total, Query took 0.0007 sec)

select exists(select * from table where condition=value limit 1)
(1 total, Query took 0.0006 sec) 

Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

I needed a package from github that was written in typscript. I did a git pull of the most recent version from the master branch into the root of my main project. I then went into the directory and did an npm install so that the gulp commands would work that generates ES5 modules. Anyway, to make the long story short, my build process was trying to build files from this new folder so I had to move it out of my root. This was causing these same errors.

How to embed matplotlib in pyqt - for Dummies

For those looking for a dynamic solution to embed Matplotlib in PyQt5 (even plot data using drag and drop). In PyQt5 you need to use super on the main window class to accept the drops. The dropevent function can be used to get the filename and rest is simple:

def dropEvent(self,e):
        This function will enable the drop file directly on to the 
        main window. The file location will be stored in the self.filename
        if e.mimeData().hasUrls:
            for url in e.mimeData().urls():
                if op_sys == 'Darwin':
                    fname = str(NSURL.URLWithString_(str(url.toString())).filePathURL().path())
                    fname = str(url.toLocalFile())
            self.filename = fname
            print("GOT ADDRESS:",self.filename)
            e.ignore() # just like above functions  

For starters the reference complete code gives this output: enter image description here

How do I check to see if my array includes an object?

This ...

horse = Horse.find(:first,:offset=>rand(Horse.count))
unless @suggested_horses.exists?(
   @suggested_horses<< horse

Should probably be this ...

horse = Horse.find(:first,:offset=>rand(Horse.count))
unless @suggested_horses.include?(horse)
   @suggested_horses<< horse

Popup Message boxes


Here is the code to a method I call whenever I want an information box to pop up, it hogs the screen until it is accepted:

import javax.swing.JOptionPane;

public class ClassNameHere

    public static void infoBox(String infoMessage, String titleBar)
        JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + titleBar, JOptionPane.INFORMATION_MESSAGE);

The first JOptionPane parameter (null in this example) is used to align the dialog. null causes it to center itself on the screen, however any java.awt.Component can be specified and the dialog will appear in the center of that Component instead.

I tend to use the titleBar String to describe where in the code the box is being called from, that way if it gets annoying I can easily track down and delete the code responsible for spamming my screen with infoBoxes.

To use this method call:



For a an in depth description of how to use JavaFX dialogs see: JavaFX Dialogs (official) by code.makery. They are much more powerful and flexible than Swing dialogs and capable of far more than just popping up messages.

As above I'll post a small example of how you could use JavaFX dialogs to achieve the same result

import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.application.Platform;

public class ClassNameHere

    public static void infoBox(String infoMessage, String titleBar)
        /* By specifying a null headerMessage String, we cause the dialog to
           not have a header */
        infoBox(infoMessage, titleBar, null);

    public static void infoBox(String infoMessage, String titleBar, String headerMessage)
        Alert alert = new Alert(AlertType.INFORMATION);

One thing to keep in mind is that JavaFX is a single threaded GUI toolkit, which means this method should be called directly from the JavaFX application thread. If you have another thread doing work, which needs a dialog then see these SO Q&As: JavaFX2: Can I pause a background Task / Service? and Platform.Runlater and Task Javafx.

To use this method call:




Remove object from a list of objects in python

If you know the array location you can can pass it into itself. If you are removing multiple items I suggest you remove them in reverse order.

#Setup array
array = [55,126,555,2,36]
#Remove 55 which is in position 0

Add spaces between the characters of a string in Java?

A simple way can be to split the string on each character and join the parts using space as the delimiter.


public class Main {
    public static void main(String[] args) {
        String s = "JAYARAM";
        s = String.join(" ", s.split(""));



Twitter Bootstrap inline input with dropdown

Daniel Farrell's Bootstrap Combobox does the job perfectly. Here's an example from his GitHub repository.

  // bonus: add a placeholder_x000D_
  $('.combobox').attr('placeholder', 'For example, start typing "Pennsylvania"');_x000D_
<link rel="stylesheet" href="">_x000D_
<link rel="stylesheet" href="">_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<select class="combobox form-control">_x000D_
  <option value="PA">Pennsylvania</option>_x000D_
  <option value="CT">Connecticut</option>_x000D_
  <option value="NY">New York</option>_x000D_
  <option value="MD">Maryland</option>_x000D_
  <option value="VA">Virginia</option>_x000D_

As an added bonus, I've included a placeholder in script since applying it to the markup does not hold.

How to detect input type=file "change" for the same file?

Inspiring from @braitsch I have used the following in my AngularJS2 input-file-component

<input id="file" onclick="onClick($event) onchange="onChange($event)" type="file" accept="*/*" />

export class InputFile {


    fileChange = new EventEmitter();

    onClick(event) {''
        let files  =;
            this.file = files[0];
        else { this.file = null}

Here the onClick(event) rescued me :-)

Task vs Thread differences



Thread represents an actual OS-level thread, with its own stack and kernel resources. (technically, a CLR implementation could use fibers instead, but no existing CLR does this) Thread allows the highest degree of control; you can Abort() or Suspend() or Resume() a thread (though this is a very bad idea), you can observe its state, and you can set thread-level properties like the stack size, apartment state, or culture.

The problem with Thread is that OS threads are costly. Each thread you have consumes a non-trivial amount of memory for its stack, and adds additional CPU overhead as the processor context-switch between threads. Instead, it is better to have a small pool of threads execute your code as work becomes available.

There are times when there is no alternative Thread. If you need to specify the name (for debugging purposes) or the apartment state (to show a UI), you must create your own Thread (note that having multiple UI threads is generally a bad idea). Also, if you want to maintain an object that is owned by a single thread and can only be used by that thread, it is much easier to explicitly create a Thread instance for it so you can easily check whether code trying to use it is running on the correct thread.


ThreadPool is a wrapper around a pool of threads maintained by the CLR. ThreadPool gives you no control at all; you can submit work to execute at some point, and you can control the size of the pool, but you can't set anything else. You can't even tell when the pool will start running the work you submit to it.

Using ThreadPool avoids the overhead of creating too many threads. However, if you submit too many long-running tasks to the threadpool, it can get full, and later work that you submit can end up waiting for the earlier long-running items to finish. In addition, the ThreadPool offers no way to find out when a work item has been completed (unlike Thread.Join()), nor a way to get the result. Therefore, ThreadPool is best used for short operations where the caller does not need the result.


Finally, the Task class from the Task Parallel Library offers the best of both worlds. Like the ThreadPool, a task does not create its own OS thread. Instead, tasks are executed by a TaskScheduler; the default scheduler simply runs on the ThreadPool.

Unlike the ThreadPool, Task also allows you to find out when it finishes, and (via the generic Task) to return a result. You can call ContinueWith() on an existing Task to make it run more code once the task finishes (if it's already finished, it will run the callback immediately). If the task is generic, ContinueWith() will pass you the task's result, allowing you to run more code that uses it.

You can also synchronously wait for a task to finish by calling Wait() (or, for a generic task, by getting the Result property). Like Thread.Join(), this will block the calling thread until the task finishes. Synchronously waiting for a task is usually bad idea; it prevents the calling thread from doing any other work, and can also lead to deadlocks if the task ends up waiting (even asynchronously) for the current thread.

Since tasks still run on the ThreadPool, they should not be used for long-running operations, since they can still fill up the thread pool and block new work. Instead, Task provides a LongRunning option, which will tell the TaskScheduler to spin up a new thread rather than running on the ThreadPool.

All newer high-level concurrency APIs, including the Parallel.For*() methods, PLINQ, C# 5 await, and modern async methods in the BCL, are all built on Task.


The bottom line is that Task is almost always the best option; it provides a much more powerful API and avoids wasting OS threads.

The only reasons to explicitly create your own Threads in modern code are setting per-thread options, or maintaining a persistent thread that needs to maintain its own identity.

Clear the cache in JavaScript

or you can just read js file by server with file_get_contets and then put in echo in the header the js contents

How to get the PID of a process by giving the process name in Mac OS X ?

Try this one:

echo "$(ps -ceo pid=,comm= | awk '/firefox/ { print $1; exit }')"

The ps command produces output like this, with the PID in the first column and the executable name (only) in the second column:

bookworm% ps -ceo pid=,comm=
    1 launchd
   10 kextd
   11 UserEventAgent
   12 mDNSResponder
   13 opendirectoryd
   14 notifyd
   15 configd

...which awk processes, printing the first column (pid) and exiting after the first match.

JPA Query selecting only specific columns without using Criteria Query?

Yes, like in plain sql you could specify what kind of properties you want to select:

SELECT i.firstProperty, i.secondProperty FROM ObjectName i WHERE

Executing this query will return a list of Object[], where each array contains the selected properties of one object.

Another way is to wrap the selected properties in a custom object and execute it in a TypedQuery:

String query = "SELECT NEW CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();

Examples can be found in this article.

UPDATE 29.03.2018:


@PatrickLeitermann for me its giving "Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate class ***" exception . how to solve this ?

I guess you’re using JPA in the context of a Spring application, don't you? Some other people had exactly the same problem and their solution was adding the fully qualified name (e. g. com.example.CustomObject) after the SELECT NEW keywords.

Maybe the internal implementation of the Spring data framework only recognizes classes annotated with @Entity or registered in a specific orm file by their simple name, which causes using this workaround.

How do I redirect output to a variable in shell?

Create a function calling it as the command you want to invoke. In this case, I need to use the ruok command.

Then, call the function and assign its result into a variable. In this case, I am assigning the result to the variable health.

function ruok {
  echo ruok | nc *ip* 2181

health=echo ruok *ip*

Declaring an enum within a class

  1. If Color is something that is specific to just Cars then that is the way you would limit its scope. If you are going to have another Color enum that other classes use then you might as well make it global (or at least outside Car).

  2. It makes no difference. If there is a global one then the local one is still used anyway as it is closer to the current scope. Note that if you define those function outside of the class definition then you'll need to explicitly specify Car::Color in the function's interface.

What are forward declarations in C++?

Because C++ is parsed from the top down, the compiler needs to know about things before they are used. So, when you reference:

int add( int x, int y )

in the main function the compiler needs to know it exists. To prove this try moving it to below the main function and you'll get a compiler error.

So a 'Forward Declaration' is just what it says on the tin. It's declaring something in advance of its use.

Generally you would include forward declarations in a header file and then include that header file in the same way that iostream is included.

How to destroy JWT Tokens on logout?

You can add "issue time" to token and maintain "last logout time" for each user on the server. When you check token validity, also check "issue time" be after "last logout time".

How do I create a URL shortener?

Here is a Node.js implementation that is likely to generate a highly random seven-character string.

It uses Node.js crypto to generate a highly random 25 charset rather than randomly selecting seven characters.

var crypto = require("crypto");
exports.shortURL = new function () {
    this.getShortURL = function () {
        var sURL = '',
            _rand = crypto.randomBytes(25).toString('hex'),
            _base = _rand.length;
        for (var i = 0; i < 7; i++)
            sURL += _rand.charAt(Math.floor(Math.random() * _rand.length));
        return sURL;

Splitting a dataframe string column into multiple different columns

A very direct way is to just use read.table on your character vector:

> read.table(text = text, sep = ".", colClasses = "character")
   V1 V2  V3  V4
1   F US CLE V13
2   F US CA6 U13
3   F US CA6 U13
4   F US CA6 U13
5   F US CA6 U13
6   F US CA6 U13
7   F US CA6 U13
8   F US CA6 U13
9   F US  DL U13
10  F US  DL U13
11  F US  DL U13
12  F US  DL Z13
13  F US  DL Z13

colClasses needs to be specified, otherwise F gets converted to FALSE (which is something I need to fix in "splitstackshape", otherwise I would have recommended that :) )

Update (> a year later)...

Alternatively, you can use my cSplit function, like this:

cSplit(, "text", ".")
#     text_1 text_2 text_3 text_4
#  1:      F     US    CLE    V13
#  2:      F     US    CA6    U13
#  3:      F     US    CA6    U13
#  4:      F     US    CA6    U13
#  5:      F     US    CA6    U13
#  6:      F     US    CA6    U13
#  7:      F     US    CA6    U13
#  8:      F     US    CA6    U13
#  9:      F     US     DL    U13
# 10:      F     US     DL    U13
# 11:      F     US     DL    U13
# 12:      F     US     DL    Z13
# 13:      F     US     DL    Z13

Or, separate from "tidyr", like this:

library(tidyr) %>% separate(text, into = paste("V", 1:4, sep = "_"))
#    V_1 V_2 V_3 V_4
# 1    F  US CLE V13
# 2    F  US CA6 U13
# 3    F  US CA6 U13
# 4    F  US CA6 U13
# 5    F  US CA6 U13
# 6    F  US CA6 U13
# 7    F  US CA6 U13
# 8    F  US CA6 U13
# 9    F  US  DL U13
# 10   F  US  DL U13
# 11   F  US  DL U13
# 12   F  US  DL Z13
# 13   F  US  DL Z13

Add placeholder text inside UITextView in Swift?

Swift - I wrote a class that inherited UITextView and I added a UILabel as a subview to act as a placeholder.

  import UIKit
  class HintedTextView: UITextView {

      @IBInspectable var hintText: String = "hintText" {
              hintLabel.text = hintText

      private lazy var hintLabel: UILabel = {
          let label = UILabel()
          label.font = UIFont.systemFontOfSize(16)
          label.textColor = UIColor.lightGrayColor()
          label.translatesAutoresizingMaskIntoConstraints = false
          return label

      override init(frame: CGRect, textContainer: NSTextContainer?) {
          super.init(frame: frame, textContainer: textContainer)

      required init?(coder aDecoder: NSCoder) {
         super.init(coder: aDecoder)

      override func prepareForInterfaceBuilder() {

      private func setupView() {

        translatesAutoresizingMaskIntoConstraints = false
        delegate = self
        font = UIFont.systemFontOfSize(16)



           hintLabel.leftAnchor.constraintEqualToAnchor(leftAnchor, constant: 4),
           hintLabel.rightAnchor.constraintEqualToAnchor(rightAnchor, constant: 8),
           hintLabel.topAnchor.constraintEqualToAnchor(topAnchor, constant: 4),

      override func layoutSubviews() {


How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

Four fewer characters, but 2 more ms

# 52.4 ms ± 352 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

# 50 ms ± 423 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

I'd probably use axis=1

How do I use the new computeIfAbsent function?

Another example. When building a complex map of maps, the computeIfAbsent() method is a replacement for map's get() method. Through chaining of computeIfAbsent() calls together, missing containers are constructed on-the-fly by provided lambda expressions:

  // Stores regional movie ratings
  Map<String, Map<Integer, Set<String>>> regionalMovieRatings = new TreeMap<>();

  // This will throw NullPointerException!
  regionalMovieRatings.get("New York").get(5).add("Boyhood");

  // This will work
    .computeIfAbsent("New York", region -> new TreeMap<>())
    .computeIfAbsent(5, rating -> new TreeSet<>())

How to make grep only match if the entire line matches?

I needed this feature, but also wanted to make sure I did not return lines with a prefix before the ABB.log:

  • ABB.log
  • ABB.log.122
  • ABB.log.123
  • 123ABB.log

grep "\WABB.log$" -w a.tmp

Rails 4 - Strong Parameters - Nested Objects

I found this suggestion useful in my case:

  def product_params
    params.require(:product).permit(:name).tap do |whitelisted|
      whitelisted[:data] = params[:product][:data]

Check this link of Xavier's comment on github.

This approach whitelists the entire params[:measurement][:groundtruth] object.

Using the original questions attributes:

  def product_params
    params.require(:measurement).permit(:name, :groundtruth).tap do |whitelisted|
      whitelisted[:groundtruth] = params[:measurement][:groundtruth]

open existing java project in eclipse

Eclipse does not have internal Subversion connectivity. After you've downloaded and unzipped Eclipse, you have to install a Subversion plug-in. Check with the other developers as to which Subversion plug-in you're using. Subclipse is one Subversion plug-in.

After you've installed the Subversion plug-in, you have to give Eclipse the repository information in the SVN Repositories view of the SVN Repositories perspective. One of the other developers should have that information.

Finally, you check out the project from Subversion, by left clicking on the Package Explorer, selecting New -> Project, and in the New Project wizard,left clicking on SVN -> Checkout projects from SVN.

Data binding for TextBox

You can't databind to a property and then explictly assign a value to the databound property.

Detecting a mobile browser

I advise you check out

In a nutshell, if you import a tiny JS file:

<script type='text/javascript' src="//"></script>

you will be left with a JSON object that looks like:

 "complete_device_name":"Google Nexus 7",

(that's assuming you are using a Nexus 7, of course) and you will be able to do things like:

if(WURFL.form_factor == "Tablet"){

This is what you are looking for.

Disclaimer: I work for the company that offers this free service. Thanks.

SQL Server: Null VS Empty String

NULL is a non value, like undefined. '' is a empty string with 0 characters.
The value of a string in database depends of your value in your UI, but generally, it's an empty string '' if you specify the parameter in your query or stored procedure.

How to embed a SWF file in an HTML page?

I use, it helps to embed media content and avoid the IE "click to activate" problem.

Dynamically adding properties to an ExpandoObject

dynamic x = new ExpandoObject();
x.NewProp = string.Empty;


var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);

Setting property 'source' to 'org.eclipse.jst.jee.server:JSFTut' did not find a matching property

Update to the latest release

Since this commit, this is is fixed in the development version of Tomcat. And now in released versions 9.0.13, 8.5.35, and 7.0.92.

From the 9.0.13 changelog:

Ignore an attribute named source on Context elements provided by StandardContext. This is to suppress warnings generated by the Eclipse / Tomcat integration provided by Eclipse. Based on a patch by mdfst13. (markt)

There are similar entries in the 7.0.92 and 8.5.35 changelogs.

The effect of this change is to suppress a warning when a source attribute is declared on a Context element in either server.xml or a context.xml. Since those are the two places that Eclipse puts such an attribute, that fixes this particular issue.

TL;DR: update to the latest Tomcat version in its branch, e.g. 9.0.13 or newer.

Date Format in Swift

I solved my problem to the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'(e.g 2018-06-15T00:00:00.000Z) with this:

func formatDate(date: String) -> String {
   let dateFormatterGet = DateFormatter()
   dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

   let dateFormatter = DateFormatter()
   dateFormatter.dateStyle = .medium
   dateFormatter.timeStyle = .none
   //    dateFormatter.locale = Locale(identifier: "en_US") //uncomment if you don't want to get the system default format.

   let dateObj: Date? = date)

   return dateFormatter.string(from: dateObj!)

How do you Sort a DataTable given column and direction?

DataTables have an overloaded Select method that you can you to do this. See here:

But the return val of the Select call is not a DataTable but an array of RowData objects. If you want to return a DataTable from your function you will have to build it from scratch based on that data array. Here is a post that addresses and provides a sample for both issues:

How do I run a batch file from my Java Application?

This code will execute two commands.bat that exist in the path C:/folders/folder.

Runtime.getRuntime().exec("cd C:/folders/folder & call commands.bat");

Which port we can use to run IIS other than 80?

you can configure IIS in IIS Mgr to use EVERY port between 1 and 65535 as long it is not used by any other application

Retrieve list of tasks in a queue in Celery

I've come to the conclusion the best way to get the number of jobs on a queue is to use rabbitmqctl as has been suggested several times here. To allow any chosen user to run the command with sudo I followed the instructions here (I did skip editing the profile part as I don't mind typing in sudo before the command.)

I also grabbed jamesc's grep and cut snippet and wrapped it up in subprocess calls.

from subprocess import Popen, PIPE
p1 = Popen(["sudo", "rabbitmqctl", "list_queues", "-p", "[name of your virtula host"], stdout=PIPE)
p2 = Popen(["grep", "-e", "^celery\s"], stdin=p1.stdout, stdout=PIPE)
p3 = Popen(["cut", "-f2"], stdin=p2.stdout, stdout=PIPE)
print("number of jobs on queue: %i" % int(p3.communicate()[0]))

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

You can get also get this error trying to drop a non-existing foreign key. So when dropping foreign keys, always make sure they actually exist.

If the foreign key does exist, and you are still getting this error try the following:


// Drop the foreign key here!


This always does the trick for me :)

How can I check the current status of the GPS receiver?

With LocationManager you can getLastKnownLocation() after you getBestProvider(). This gives you a Location object, which has the methods getAccuracy() in meters and getTime() in UTC milliseconds

Does this give you enough info?

Or perhaps you could iterate over the LocationProviders and find out if each one meetsCriteria( ACCURACY_COARSE )

Run PowerShell command from command prompt (no ps1 script)

This works from my Windows 10's cmd.exe prompt

powershell -ExecutionPolicy Bypass -Command "Import-Module C:\Users\william\ps1\TravelBook; Get-TravelBook Hawaii"

This example shows

  1. how to chain multiple commands
  2. how to import module with module path
  3. how to run a function defined in the module
  4. No need for those fancy "&".

How to delete an array element based on key?

You don't say what language you're using, but looking at that output, it looks like PHP output (from print_r()).
If so, just use unset():


How to communicate between iframe and the parent site?

You can also use

postMessage(message, '*');

How do I break a string across more than one line of code in JavaScript?

I tried a number of the above suggestions but got an ILLEGAL character warning in Chrome code inspector. The following worked for me (only tested in Chrome though!)

alert('stuff on line 1\\nstuff on line 2);

comes out like...

stuff on line 1
stuff on line 2

NOTE the double backslash!!...this seems to be important!

Use grep --exclude/--include syntax to not grep through certain files

The --binary-files=without-match option to GNU grep gets it to skip binary files. (Equivalent to the -I switch mentioned elsewhere.)

(This might require a recent version of grep; 2.5.3 has it, at least.)

What's the purpose of SQL keyword "AS"?

The use is more obvious if you don't use 'SELECT *' (which is a bad habit you should get out of):

SELECT t1.colA, t2.colB, t3.colC FROM alongtablename AS t1, anotherlongtablename AS t2, yetanotherlongtablename AS t3 WHERE t1.colD = t2.colE...

Notepad++ cached files location

I lost somehow my temporary notepad++ files, they weren't showing in tabs. So I did some search in appdata folder, and I found all my temporary files there. It seems that they are stored there for a long time.