Programs & Examples On #Bayesian

Bayesian refers to methods in probability and statistics named after Thomas Bayes (ca. 1702–1761), in particular methods related to statistical inference

What are advantages of Artificial Neural Networks over Support Vector Machines?

Judging from the examples you provide, I'm assuming that by ANNs, you mean multilayer feed-forward networks (FF nets for short), such as multilayer perceptrons, because those are in direct competition with SVMs.

One specific benefit that these models have over SVMs is that their size is fixed: they are parametric models, while SVMs are non-parametric. That is, in an ANN you have a bunch of hidden layers with sizes h1 through hn depending on the number of features, plus bias parameters, and those make up your model. By contrast, an SVM (at least a kernelized one) consists of a set of support vectors, selected from the training set, with a weight for each. In the worst case, the number of support vectors is exactly the number of training samples (though that mainly occurs with small training sets or in degenerate cases) and in general its model size scales linearly. In natural language processing, SVM classifiers with tens of thousands of support vectors, each having hundreds of thousands of features, is not unheard of.

Also, online training of FF nets is very simple compared to online SVM fitting, and predicting can be quite a bit faster.

EDIT: all of the above pertains to the general case of kernelized SVMs. Linear SVM are a special case in that they are parametric and allow online learning with simple algorithms such as stochastic gradient descent.

How to getElementByClass instead of GetElementById with JavaScript?

Modern browsers have support for document.getElementsByClassName. You can see the full breakdown of which vendors provide this functionality at caniuse. If you're looking to extend support into older browsers, you may want to consider a selector engine like that found in jQuery or a polyfill.

Older Answer

You'll want to check into jQuery, which will allow the following:

$(".classname").hide(); // hides everything with class 'classname'

Google offers a hosted jQuery source-file, so you can reference it and be up-and-running in moments. Include the following in your page:

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

How to handle authentication popup with Selenium WebDriver using Java

Don't use firefox profile and try below code:

driver.get("http://UserName:[email protected]");

If you're implementing it in IE browser, there are certain things which you need to do.

In case your authentication server requires username with domain like "domainuser" you need to add double slash / to the url:

//localdomain\user:[email protected]

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

As mentioned in the comments, the Starting Guide is the place to start with Java 11 and JavaFX 11.

The key to work as you did before Java 11 is to understand that:

  • JavaFX 11 is not part of the JDK anymore
  • You can get it in different flavors, either as an SDK or as regular dependencies (maven/gradle).
  • You will need to include it to the module path of your project, even if your project is not modular.

JavaFX project

If you create a regular JavaFX default project in IntelliJ (without Maven or Gradle) I'd suggest you download the SDK from here. Note that there are jmods as well, but for a non modular project the SDK is preferred.

These are the easy steps to run the default project:

  1. Create a JavaFX project
  2. Set JDK 11 (point to your local Java 11 version)
  3. Add the JavaFX 11 SDK as a library. The URL could be something like /Users/<user>/Downloads/javafx-sdk-11/lib/. Once you do this you will notice that the JavaFX classes are now recognized in the editor.

JavaFX 11 Project

  1. Before you run the default project, you just need to add these to the VM options:

    --module-path /Users/<user>/Downloads/javafx-sdk-11/lib --add-modules=javafx.controls,javafx.fxml

  2. Run


If you use Maven to build your project, follow these steps:

  1. Create a Maven project with JavaFX archetype
  2. Set JDK 11 (point to your local Java 11 version)
  3. Add the JavaFX 11 dependencies.


Once you do this you will notice that the JavaFX classes are now recognized in the editor.

JavaFX 11 Maven project

You will notice that Maven manages the required dependencies for you: it will add javafx.base and for javafx.controls, but most important, it will add the required classifier based on your platform. In my case, Mac.

This is why your jars org.openjfx:javafx-controls:11 are empty, because there are three possible classifiers (windows, linux and mac platforms), that contain all the classes and the native implementation.

In case you still want to go to your .m2 repo and take the dependencies from there manually, make sure you pick the right one (for instance .m2/repository/org/openjfx/javafx-controls/11/javafx-controls-11-mac.jar)

  1. Replace default maven plugins with those from here.

  2. Run mvn compile javafx:run, and it should work.

Similar works as well for Gradle projects, as explained in detail here.


The mentioned Getting Started guide contains updated documentation and sample projects for IntelliJ:

Copy file(s) from one project to another using post build event...VS2010

xcopy "$(ProjectDir)Views\Home\Index.cshtml" "$(SolutionDir)MEFMVCPOC\Views\Home"

and if you want to copy entire folders:

xcopy /E /Y "$(ProjectDir)Views" "$(SolutionDir)MEFMVCPOC\Views"

Update: here's the working version

xcopy "$(ProjectDir)Views\ModuleAHome\Index.cshtml" "$(SolutionDir)MEFMVCPOC\Views\ModuleAHome\" /Y /I

Here are some commonly used switches with xcopy:

  • /I - treat as a directory if copying multiple files.
  • /Q - Do not display the files being copied.
  • /S - Copy subdirectories unless empty.
  • /E - Copy empty subdirectories.
  • /Y - Do not prompt for overwrite of existing files.
  • /R - Overwrite read-only files.

How do I make flex box work in safari?

Just tRy this

display: -webkit-box;   /* OLD - iOS 6-, Safari 3.1-6, BB7 */
display: -ms-flexbox;  /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */
display: flex;         /* NEW, Spec - Firefox, Chrome, Opera */

this worked for me

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property


import the RouterModule See also

  imports: [RouterModule],



import { provideRouter, RouterConfig } from '@angular/router';

export const routes: RouterConfig = [

export const APP_ROUTER_PROVIDERS = [provideRouter(routes)];


import { bootstrap } from '@angular/platform-browser-dynamic';
import { APP_ROUTER_PROVIDERS } from './app.routes';

bootstrap(AppComponent, [APP_ROUTER_PROVIDERS]);


Your code is missing

    directives: [ROUTER_DIRECTIVES],

You can't use directives like routerLink or router-outlet without making them known to your component.

While directive names were changed to be case-sensitive in Angular2, elements still use - in the name like <router-outlet> to be compatible with the web-components spec which require a - in the name of custom elements.

register globally

To make ROUTER_DIRECTIVES globally available, add this provider to bootstrap(...):

provide(PLATFORM_DIRECTIVES, {useValue: [ROUTER_DIRECTIVES], multi: true})

then it's no longer necessary to add ROUTER_DIRECTIVES to each component.

Sharing url link does not show thumbnail image on facebook

The answers above are good and they should fix most of the problems you have. But to see the errors directly from facebook you can use the link

that way you're sure of the steps you need to take.

I found out the URL for the og:image meta has to be an absolute url

How to trigger an event in input text after I stop typing/writing?

In my thinking a user stops writing when he doesn't keep focus on that input. For this you have a function called "blur" which does stuff like

How do I copy SQL Azure database to my local development server?

Regarding the " I couldn't get the SSIS import / export to work as I got the error 'Failure inserting into the read-only column "id"'. This can be gotten around by specifying in the mapping screen that you do want to allow Identity elements to be inserted.

After that, everything worked fine using SQL Import/Export wizard to copy from Azure to local database.

I only had SQL Import/Export Wizard that comes with SQL Server 2008 R2 (worked fine), and Visual Studio 2012 Express to create local database.

Service has zero application (non-infrastructure) endpoints

I just ran into this issue and checked all of the above answers to make sure I wasn't missing anything obvious. Well, I had a semi-obvious issue. My casing of my classname in code and the classname I used in the configuration file didn't match.

For example: if the class name is CalculatorService and the configuration file refers to Calculatorservice ... you will get this error.

Number of days in particular month of particular year?

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

 * 44. Return the number of days in a month
 * , where month and year are given as input.
public class ex44 {
    public static void dateReturn(int m,int y)
        int m1=m;
        int y1=y;
        String str=" "+ m1+"-"+y1;
        SimpleDateFormat sd=new SimpleDateFormat("MM-yyyy");

        try {
            Date d=sd.parse(str);
            Calendar c=Calendar.getInstance();
        } catch (ParseException e) {
            // TODO Auto-generated catch block

    public static void main(String[] args) {



Assign format of DateTime with data annotations?

If your data field is already a DateTime datatype, you don't need to use [DataType(DataType.Date)] for the annotation; just use:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]

on the jQuery, use datepicker for you calendar

    $(document).ready(function () {

on your HTML, use EditorFor helper:

    @Html.EditorFor(model => model.StartDate)

jQuery load more data on scroll

I spent some time trying to find a nice function to wrap a solution. Anyway, ended up with this which I feel is a better solutions when loading multiple content on a single page or across a site.


function ifViewLoadContent(elem, LoadContent)
            var top_of_element = $(elem).offset().top;
            var bottom_of_element = $(elem).offset().top + $(elem).outerHeight();
            var bottom_of_screen = $(window).scrollTop() + window.innerHeight;
            var top_of_screen = $(window).scrollTop();

            if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
            if(!$(elem).hasClass("ImLoaded"))   {
            else {
               return false;

You can then call the function using window on scroll (for example, you could also bind it to a click etc. as I also do, hence the function):

To use:

$(window).scroll(function (event) {
        ifViewLoadContent("#AjaxDivOne", "someFile/somecontent.html"); 

        ifViewLoadContent("#AjaxDivTwo", "someFile/somemorecontent.html"); 

This approach should also work for scrolling divs etc. I hope it helps, in the question above you could use this approach to load your content in sections, maybe append and thereby dribble feed all that image data rather than bulk feed.

I used this approach to reduce the overhead on It died the trick, if you look at the site and inspect element etc. you can see impact on page load in Chrome (as an example).

Npm install failed with "cannot run in wd"

The documentation says (also here):

If npm was invoked with root privileges, then it will change the uid to the user account or uid specified by the user config, which defaults to nobody. Set the unsafe-perm flag to run scripts with root privileges.

Your options are:

  1. Run npm install with the --unsafe-perm flag:

    [sudo] npm install --unsafe-perm
  2. Add the unsafe-perm flag to your package.json:

    "config": {
  3. Don't use the preinstall script to install global modules, install them separately and then run the regular npm install without root privileges:

    sudo npm install -g coffee-script node-gyp
    npm install


Get column index from label in a data frame

match("B", names(df))

Can work also if you have a vector of names.

Wait for shell command to complete

Either link the shell to an object, have the batch job terminate the shell object (exit) and have the VBA code continue once the shell object = Nothing?

Or have a look at this: Capture output value from a shell command in VBA?

How to restart ADB manually from Android Studio


Go to: Tools -> Android -> Android Device Monitor

see the Device tab, under many icons, last one is drop-down arrow.

Open it.

At the bottom: RESET ADB.

Tomcat: How to find out running tomcat version

Another option is view release notes from tomcat,applicable to linux/window


CSS content property: is it possible to insert HTML instead of Text?

Unfortunately, this is not possible. Per the spec:

Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing).

In other words, for string values this means the value is always treated literally. It is never interpreted as markup, regardless of the document language in use.

As an example, using the given CSS with the following HTML:

<h1 class="header">Title</h1>

... will result in the following output:

<a href="#top">Back</a>Title

this in equals method

this refers to the current instance of the class (object) your equals-method belongs to. When you test this against an object, the testing method (which is equals(Object obj) in your case) will check wether or not the object is equal to the current instance (referred to as this).

An example:

Object obj = this; this.equals(obj); //true   Object obj = this; new Object().equals(obj); //false 

How to change the port number for Asp.Net core app?

All the other answer accounts only for http URLs. If the URL is https, then do as follows,

  1. Open launchsettings.json under Properties of the API project.

    enter image description here

  2. Change the sslPort under iisSettings -> iisExpress

A sample launchsettings.json will look as follows

  "iisSettings": {
    "iisExpress": {
      "applicationUrl": "http://localhost:12345",
      "sslPort": 98765 <== Change_This

Bootstrap 4 - Glyphicons migration?

You can use both Font Awesome and Github Octicons as a free alternative for Glyphicons.

Bootstrap 4 also switched from Less to Sass, so you might integerate the font's Sass (SCSS) into you build process, to create a single CSS file for your projects.

Also see to find out how to set up your tooling:

  1. Download and install Node, which we use to manage our dependencies.
  2. Navigate to the root /bootstrap directory and run npm install to install our local dependencies listed in package.json.
  3. Install Ruby, install Bundler with gem install bundler, and finally run bundle install. This will install all Ruby dependencies, such as Jekyll and plugins.

Font Awesome

  1. Download the files at
  2. Copy the font-awesome/scss folder into your /bootstrap folder
  3. Open your SCSS /bootstrap/bootstrap.scss and write down the following SCSS code at the end of this file:

    $fa-font-path: "../fonts"; @import "../font-awesome/scss/font-awesome.scss";

  4. Notice that you also have to copy the font file from font-awesome/fonts to dist/fonts or any other public folder set by $fa-font-path in the previous step

  5. Run: npm run dist to recompile your code with Font-Awesome

Github Octicons

  1. Download the files at
  2. Copy the octicons folder into your /bootstrap folder
  3. Open your SCSS /bootstrap/bootstrap.scss and write down the following SCSS code at the end of this file:

    $fa-font-path: "../fonts"; @import "../octicons/octicons/octicons.scss";

  4. Notice that you also have to copy the font file from font-awesome/fonts to dist/fonts or any other public folder set by $fa-font-path in the previous step

  5. Run: npm run dist to recompile your code with Octicons


On the Bootstrap website you can read:

Includes over 250 glyphs in font format from the Glyphicon Halflings set. Glyphicons Halflings are normally not available for free, but their creator has made them available for Bootstrap free of cost. As a thank you, we only ask that you include a link back to Glyphicons whenever possible.

As I understand you can use these 250 glyphs free of cost restricted for Bootstrap but not limited to version 3 exclusive. So you can use them for Bootstrap 4 too.

  1. Copy the fonts files from:
  2. Copy the file into your bootstrap/scss folder
  3. Open your scss /bootstrap/bootstrap.scss and write down the following SCSS code at the end of this file:
$bootstrap-sass-asset-helper: false;
$icon-font-name: 'glyphicons-halflings-regular';
$icon-font-svg-id: 'glyphicons_halflingsregular';
$icon-font-path: '../fonts/';
@import "glyphicons";
  1. Run: npm run dist to recompile your code with Glyphicons

Notice that Bootstrap 4 requires the post CSS Autoprefixer for compiling. When you are using a static Sass compiler to compile your CSS you should have to run the Autoprefixer afterwards.

You can find out more about mixing with the Bootstrap 4 SCSS in here.

You can also use Bower to install the fonts above. Using Bower Font Awesome installs your files in bower_components/components-font-awesome/ also notice that Github Octicons sets the octicons/octicons/octicons-.scss as the main file whilst you should use octicons/octicons/sprockets-octicons.scss.

All the above will compile all your CSS code including into a single file, which requires only one HTTP request. Alternatively you can also load the Font-Awesome font from CDN, which can be fast too in many situations. Both fonts on CDN also include the font files (using data-uri's, possible not supported for older browsers). So consider which solution best fits your situation depending on among others browsers to support.

For Font Awesome paste the following code into the <head> section of your site's HTML:

<link href="" rel="stylesheet">

Also try Yeoman generator to scaffold out a front-end Bootstrap 4 Web app to test Bootstrap 4 with Font Awesome or Github Octicons.

Android emulator doesn't take keyboard input - SDK tools rev 20

Look for the hidden .android folder in your user home folder. You might rename or delete this folder, recreate your AVD, and restart the emulator. It could be there is a .ini file in that folder that has that setting munged.

How to normalize a signal to zero mean and unit variance?

You can determine the mean of the signal, and just subtract that value from all the entries. That will give you a zero mean result.

To get unit variance, determine the standard deviation of the signal, and divide all entries by that value.

Find index of last occurrence of a substring in a string

If you don't wanna use rfind then this will do the trick/

def find_last(s, t):
    last_pos = -1
    while True:
        pos = s.find(t, last_pos + 1)
        if pos == -1:
            return last_pos
            last_pos = pos

Checking to see if one array's elements are in another array in PHP

There's little wrong with using array_intersect() and count() (instead of empty).

For example:

$bFound = (count(array_intersect($criminals, $people))) ? true : false;

How to hide 'Back' button on navigation bar on iPhone?

try this one - self.navigationController?.navigationItem.hidesBackButton = true

Octave/Matlab: Adding new elements to a vector

As mentioned before, the use of x(end+1) = newElem has the advantage that it allows you to concatenate your vector with a scalar, regardless of whether your vector is transposed or not. Therefore it is more robust for adding scalars.

However, what should not be forgotten is that x = [x newElem] will also work when you try to add multiple elements at once. Furthermore, this generalizes a bit more naturally to the case where you want to concatenate matrices. M = [M M1 M2 M3]

All in all, if you want a solution that allows you to concatenate your existing vector x with newElem that may or may not be a scalar, this should do the trick:


Simple way to find if two different lists contain exactly the same elements?

Solution for case when two lists have the same elements, but different order:

public boolean isDifferentLists(List<Integer> listOne, List<Integer> listTwo) {
    if(isNullLists(listOne, listTwo)) {
        return false;

    if (hasDifferentSize(listOne, listTwo)) {
        return true;

    List<Integer> listOneCopy = Lists.newArrayList(listOne);
    List<Integer> listTwoCopy = Lists.newArrayList(listTwo);

    return CollectionUtils.isNotEmpty(listOneCopy);

private boolean isNullLists(List<Integer> listOne, List<Integer> listTwo) {
    return listOne == null && listTwo == null;

private boolean hasDifferentSize(List<Integer> listOne, List<Integer> listTwo) {
    return (listOne == null && listTwo != null) || (listOne != null && listTwo == null) || (listOne.size() != listTwo.size());

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.


<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->


#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;

#page-content-wrapper {
  width: 100%;

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;

    #sidebar-wrapper {
      left: 0;
    } {
      position: relative;
      left: 250px;
    } #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;



How to launch jQuery Fancybox on page load?

Alex's answer is great. but It is importanting to note that that calls the default fancybox style. If you have your own custom rules, you should just call .trigger click on that specific anchor

$(document).ready(function() {
    'padding':          0,
    'cyclic':       true,
    'width':        625,
    'height':       350,
    'padding':      0, 
    'margin':      0, 
    'speedIn':      300,
    'speedOut':     300,
    'transitionIn': 'elastic',
    'transitionOut': 'elastic',
    'easingIn':     'swing',
    'easingOut':    'swing',
    'titleShow' : false

Convert datatable to JSON in C#

Convert datatable to JSON using

 public static object DataTableToJSON(DataTable table)
        var list = new List<Dictionary<string, object>>();

        foreach (DataRow row in table.Rows)
            var dict = new Dictionary<string, object>();

            foreach (DataColumn col in table.Columns)
                dict[col.ColumnName] = (Convert.ToString(row[col]));
        JavaScriptSerializer serializer = new JavaScriptSerializer();

        return serializer.Serialize(list);

Syntax error on print with Python 3

Because in Python 3, print statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old print statement. So you have to write it as

print("Hello World")

But if you write this in a program and someone using Python 2.x tries to run it, they will get an error. To avoid this, it is a good practice to import print function:

from __future__ import print_function

Now your code works on both 2.x & 3.x.

Check out below examples also to get familiar with print() function.

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

Source: What’s New In Python 3.0?

How to change credentials for SVN repository in Eclipse?

Delete the .keyring file under the location: configuration\org.eclipse.core.runtime, and after that, you will be invited to prompt your new svn account. for me it worked.

Python - Check If Word Is In A String

Using regex is a solution, but it is too complicated for that case.

You can simply split text into list of words. Use split(separator, num) method for that. It returns a list of all the words in the string, using separator as the separator. If separator is unspecified it splits on all whitespace (optionally you can limit the number of splits to num).

list_of_words = mystring.split()
if word in list_of_words:
    print 'success'

This will not work for string with commas etc. For example:

mystring = "One,two and three"
# will split into ["One,two", "and", "three"]

If you also want to split on all commas etc. use separator argument like this:

# whitespace_chars = " \t\n\r\f" - space, tab, newline, return, formfeed
list_of_words = mystring.split( \t\n\r\f,.;!?'\"()")
if word in list_of_words:
    print 'success'

Toggle input disabled attribute using jQuery

Another simple option that updates on a click of the checkbox.


<input type="checkbox" id="checkbox/>
<input disabled type="submit" id="item"/>


$('#checkbox').click(function() {
    if (this.checked) {
        $('#item').prop('disabled', false); // If checked enable item       
    } else {
        $('#item').prop('disabled', true); // If checked disable item                   

In action: link

I have created a table in hive, I would like to know which directory my table is created in?




I prefer formatted because it is more human readable format

Will iOS launch my app into the background if it was force-quit by the user?


You can achieve this using the new PushKit framework, introduced in iOS 8. Though PushKit is used for VoIP. So your usage should be for VoIP related otherwise there is risk of app rejection. (See this answer).


The documentation has been clarified for iOS8. The documentation can be read here. Here is a relevant excerpt:

Use this method to process incoming remote notifications for your app. Unlike the application:didReceiveRemoteNotification: method, which is called only when your app is running in the foreground, the system calls this method when your app is running in the foreground or background. In addition, if you enabled the remote notifications background mode, the system launches your app (or wakes it from the suspended state) and puts it in the background state when a push notification arrives. However, the system does not automatically launch your app if the user has force-quit it. In that situation, the user must relaunch your app or restart the device before the system attempts to launch your app automatically again.

Although this was not made clear by the WWDC video, a quick search on the developer forums turned this up: (login required)

Also keep in mind that if you kill your app from the app switcher (i.e. swiping up to kill the app) then the OS will never relaunch the app regardless of push notification or background fetch. In this case the user has to manually relaunch the app once and then from that point forward the background activities will be invoked. -pmarcos

That post was by an Apple employee so I think i can trust that this information is correct.

So it looks like when the app is killed from the app switcher (by swiping up), the app will never be launched, even for scheduled background fetches.

Twitter Bootstrap vs jQuery UI?

I have on several projects.

The biggest difference in my opinion

  • jQuery UI is fallback safe, it works correctly and looks good in old browsers, where Bootstrap is based on CSS3 which basically means GREAT in new browsers, not so great in old

  • Update frequency: Bootstrap is getting some great big updates with awesome new features, but sadly they might break previous code, so you can't just install bootstrap and update when there is a new major release, it basically requires a lot of new coding

  • jQuery UI is based on good html structure with transformations from JavaScript, while Bootstrap is based on visually and customizable inline structure. (calling a widget in JQUERY UI, defining it in Bootstrap)

So what to choose?

That always depends on the type of project you are working on. Is cool and fast looking widgets better, or are your users often using old browsers?

I always end up using both, so I can use the best of both worlds.

Here are the links to both frameworks, if you decide to use them.

  1. jQuery UI
  2. Bootstrap

scroll image with continuous scrolling using marquee tag

Try this:

<marquee behavior="" Height="200px"  direction="up" scroll onmouseover="this.setAttribute('scrollamount', 0, 0);this.stop();" onmouseout="this.setAttribute('scrollamount', 3, 0);this.start();" scrollamount="3" valign="center">

    <img src="images/a.jpg">
        <img src="images/a.jpg">
        <img src="images/a.jpg">
        <img src="images/a.jpg">
        <img src="images/a.jpg">
        <img src="images/a.jpg">

Deep copy an array in Angular 2 + TypeScript

you can use use JQuery for deep copying :

var arr =[['abc'],['xyz']];
var newArr = $.extend(true, [], arr);

console.log(arr); //arr still has [['abc'],['xyz']]

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

This solved my problem: Kotlin Code:

val fragmentTransaction = activity.supportFragmentManager.beginTransaction()
fragmentTransaction.add(dialogFragment, tag)

How is commitAllowingStateLoss() is different than commit() ?

As per documentation:

Like commit() but allows the commit to be executed after an activity's state is saved.

P.S: you can show Fragment Dialogs or can load fragments by this method. Applicable for both.

Find running median from a stream of integers

Here is my simple but efficient algorithm (in C++) for calculating running median from a stream of integers:


using namespace std;

void runningMedian(std::ifstream& ifs, std::ofstream& ofs, const unsigned bufSize) {
    if (bufSize < 1)
        throw exception("Wrong buffer size.");
    bool evenSize = bufSize % 2 == 0 ? true : false;
    list<int> q;
    vector<int> nums;
    int n;
    unsigned count = 0;
    while (ifs.good()) {
        ifs >> n;
        auto ub = std::upper_bound(nums.begin(), nums.end(), n);
        nums.insert(ub, n);
        if (nums.size() >= bufSize) {
            auto it = std::find(nums.begin(), nums.end(), q.front());
            if (evenSize)
                ofs << count << ": " << (static_cast<double>(nums[nums.size() / 2 - 1] +
                static_cast<double>(nums[nums.size() / 2]))) / 2.0 << '\n';
                ofs << count << ": " << static_cast<double>(nums[nums.size() / 2]);

The bufferSize specifies the size of the numbers sequence, on which the running median must be calculated. When reading numbers from the input stream ifs the vector of the size bufferSize is maintained in sorted order. The median is calculated by taking the middle of the sorted vector, if bufferSize is odd, or the sum of the two middle elements divided by 2, when bufferSize is even. Additinally, I maintain a list of last bufferSize elements read from input. When a new element is added, I put it in the right place in sorted vector and remove from the vector the element added bufferSize steps before (the value of the element retained in the front of the list). In the same time I remove the old element from the list: every new element is placed on the back of the list, every old element is removed from the front. After reaching the bufferSize, both the list and the vector stop to grow, and every insertion of a new element is compensated be deletion of an old element, placed in the list bufferSize steps before. Note, I do not care, whether I remove from the vector exactly the element, placed bufferSize steps before, or just an element that has the same value. For the value of median it does not matter. All calculated median values are output in the output stream.

How to place two divs next to each other?

here is the solution:

#wrapper {
    width: 500px;
    border: 1px solid black;
    overflow: auto; /* so the size of the wrapper is alway the size of the longest content */
#first {
    float: left;
    width: 300px;
    border: 1px solid red;
#second {
    border: 1px solid green;
    margin: 0 0 0 302px; /* considering the border you need to use a margin so the content does not float under the first div*/

your demo updated;

Return anonymous type results?

Now I realize that the compiler won't let me return a set of anonymous types since it's expecting Dogs, but is there a way to return this without having to create a custom type?

Use use object to return a list of Anonymous types without creating a custom type. This will work without the compiler error (in .net 4.0). I returned the list to the client and then parsed it on JavaScript:

public object GetDogsWithBreedNames()
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select new
                            Name = d.Name,
                            BreedName = b.BreedName
    return result;

Can HTML checkboxes be set to readonly?

What none of you are thinking about here is that you are all using JavaScript, which can be very easily bypassed by any user.

Simply disabling it disables all JQuery/Return False statements.

Your only option for readonly checkboxes is server side.

Display them, let them change them but don't accept the new post data from them.

C++ compile time error: expected identifier before numeric constant

Initializations with (...) in the class body is not allowed. Use {..} or = .... Unfortunately since the respective constructor is explicit and vector has an initializer list constructor, you need a functional cast to call the wanted constructor

vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);

As an alternative you can use constructor initializer lists

 Attribute():name(5), val(5, 0) {}

Access host database from a docker container

From Docker 17.06 onwards, a special Mac-only DNS name is available in docker containers that resolves to the IP address of the host. It is:


The documentation is here:

OpenCV in Android Studio

The below steps for using Android OpenCV sdk in Android Studio. This is a simplified version of this(1) SO answer.

  1. Download latest OpenCV sdk for Android from and decompress the zip file.
  2. Import OpenCV to Android Studio, From File -> New -> Import Module, choose sdk/java folder in the unzipped opencv archive.
  3. Update build.gradle under imported OpenCV module to update 4 fields to match your project build.gradle a) compileSdkVersion b) buildToolsVersion c) minSdkVersion and d) targetSdkVersion.
  4. Add module dependency by Application -> Module Settings, and select the Dependencies tab. Click + icon at bottom, choose Module Dependency and select the imported OpenCV module.
    • For Android Studio v1.2.2, to access to Module Settings : in the project view, right-click the dependent module -> Open Module Settings
  5. Copy libs folder under sdk/native to Android Studio under app/src/main.
  6. In Android Studio, rename the copied libs directory to jniLibs and we are done.

Step (6) is since Android studio expects native libs in app/src/main/jniLibs instead of older libs folder. For those new to Android OpenCV, don't miss below steps

  • include static{ System.loadLibrary("opencv_java"); } (Note: for OpenCV version 3 at this step you should instead load the library opencv_java3.)
  • For step(5), if you ignore any platform libs like x86, make sure your device/emulator is not on that platform.

OpenCV written is in C/C++. Java wrappers are

  1. Android OpenCV SDK - maintained Android Java wrapper. I suggest this one.
  2. OpenCV Java - maintained auto generated desktop Java wrapper.
  3. JavaCV - Popular Java wrapper maintained by independent developer(s). Not Android specific. This library might get out of sync with OpenCV newer versions.

Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation

This happens when JDK and JRE have different versions installed on your system. Update the JDK with the matching version of JRE. Also verify that System variable path has bin value from same JDK version.

How to get text and a variable in a messagebox

As has been suggested, using the string.format method is nice and simple and very readable.

In the " + " is used for addition and the " & " is used for string concatenation.

In your example:

MsgBox("Variable = " + variable)


MsgBox("Variable = " & variable)

I may have been a bit quick answering this as it appears these operators can both be used for concatenation, but recommended use is the "&", source

maybe call



Use string interpolation (vs2015 onwards I believe):

MsgBox($"Variable = {variable}")

message box in jquery

If you don't wont use jquery.ui(that is highly recommended), you can take a look at Block.UI plugin.

Redraw datatables after using ajax to refresh the table content?

Use this:

var table = $(selector).dataTables();


var table = $(selector).DataTables();

Get table names using SELECT statement in MySQL

There is yet another simpler way to get table names

SHOW TABLES FROM <database_name>

callback to handle completion of pipe

I found an a bit different solution of my problem regarding this context. Thought worth sharing.

Most of the example create readStreams from file. But in my case readStream has to be created from JSON string coming from a message pool.

var jsonStream = through2.obj(function(chunk, encoding, callback) {
                    this.push(JSON.stringify(chunk, null, 4) + '\n');
// message.value --> value/text to write in write.txt 
var writeStream = sftp.createWriteStream("/path/to/write/write.txt");

//"close" event didn't work for me!
writeStream.on( 'close', function () {
    console.log( "- done!" );

//"finish" event didn't work for me either!
writeStream.on( 'close', function () {
    console.log( "- done!"

// finally this worked for me!
jsonStream.on('data', function(data) {
    var toString =;
    console.log('type of data:', toString);
    console.log( "- file transferred" );

jsonStream.pipe( writeStream );

How to convert color code into media.brush?

What version of WPF are you using? I tried in both 3.5 and 4.0, and Fill="#FF000000" should work fine in a in the XAML. There is another syntax, however, if it doesn't. Here's a 3.5 XAML that I tested with two different ways. Better yet would be to use a resource.

<Window x:Class="WpfApplication2.MainWindow"
    Title="MainWindow" Height="350" Width="525">
    <Rectangle Height="100" HorizontalAlignment="Left" Margin="100,12,0,0" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="200" Fill="#FF00AE00" />
    <Rectangle Height="100" HorizontalAlignment="Left" Margin="100,132,0,0" Name="rectangle2" Stroke="Black" VerticalAlignment="Top" Width="200" >
            <SolidColorBrush Color="#FF00AE00" />

Using .NET, how can you find the mime type of a file based on the file signature not the extension

Hello I have adapted Winista.MimeDetect project into .net core/framework with fallback into urlmon.dll Fell free to use it: nuget package.

   var mimeTypes = new MimeTypes();

   //usage by filepath
   var mimeType1 = mimeTypes.GetMimeTypeFromFile(filePath);

importing go files in same folder

No import is necessary as long as you declare both a.go and b.go to be in the same package. Then, you can use go run to recognize multiple files with:

$ go run a.go b.go

Defining Z order of views of RelativeLayout in Android

childView.bringToFront() didn't work for me, so I set the Z translation of the least recently added item (the one that was overlaying all other children) to a negative value like so:


see for more

Mysql adding user for remote access

Follow instructions (steps 1 to 3 don't needed in windows):

  1. Find mysql config to edit:

    /etc/mysql/my.cnf (Mysql 5.5)

    /etc/mysql/conf.d/mysql.cnf (Mysql 5.6+)

  2. Find bind-address= in config file change bind-address= (you can set bind address to one of your interface ips or like me use

  3. Restart mysql service run on console: service restart mysql

  4. Create a user with a safe password for remote connection. To do this run following command in mysql (if you are linux user to reach mysql console run mysql and if you set password for root run mysql -p):

     ON *.* TO 'remote'@'%' 
     IDENTIFIED BY 'safe_password' 

Now you should have a user with name of user and password of safe_password with capability of remote connect.

jquery.ajax Access-Control-Allow-Origin

refer the above link for more details on Cross domain resource sharing.

you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.

sample below:

ajax call:

$(document).ready(function () {
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            url: "<your middle man service url here>/GetQuote?callback=?",
            data: { symbol: 'ctsh' },
            dataType: "jsonp",                
            jsonpCallback: 'fnsuccesscallback'

service (asmx) which will return jsonp:

    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public void GetQuote(String symbol,string callback)

        WebProxy myProxy = new WebProxy("<proxy url here>", true);

        myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
        StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
        SQ.Proxy = myProxy;
        String result = SQ.GetQuote(symbol);
        StringBuilder sb = new StringBuilder();
        JavaScriptSerializer js = new JavaScriptSerializer();
        sb.Append(callback + "(");
        Context.Response.ContentType = "application/json";

BAT file: Open new cmd window and execute a command in there

You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.

What I found out was to use the K switch like this:

start cmd /k echo Hello, World!

start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.

You can also use the /C switch for something similar.

start cmd /C pause

This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.

Use the following in your batch file:

start cmd.exe /c "more-batch-commands-here"


start cmd.exe /k "more-batch-commands-here"

/c Carries out the command specified by string and then terminates

/k Carries out the command specified by string but remains

The /c and /k options controls what happens once your command finishes running. With /c the terminal window will close automatically, leaving your desktop clean. With /k the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.

Consult the cmd.exe documentation using cmd /? for more details.

Escaping Commands with White Spaces

The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.


Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt

Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"

Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""


How to load image (and other assets) in Angular an project?

Being specific to Angular2 to 5, we can bind image path using property binding as below. Image path is enclosed by the single quotation marks.

Sample example

<img [src]="'assets/img/klogo.png'" alt="image">

C++: Converting Hexadecimal to Decimal

This should work as well.

#include <ctype.h>
#include <string.h>

template<typename T = unsigned int>
T Hex2Int(const char* const Hexstr, bool* Overflow)
    if (!Hexstr)
        return false;
    if (Overflow)
        *Overflow = false;

    auto between = [](char val, char c1, char c2) { return val >= c1 && val <= c2; };
    size_t len = strlen(Hexstr);
    T result = 0;

    for (size_t i = 0, offset = sizeof(T) << 3; i < len && (int)offset > 0; i++)
        if (between(Hexstr[i], '0', '9'))
            result = result << 4 ^ Hexstr[i] - '0';
        else if (between(tolower(Hexstr[i]), 'a', 'f'))
            result = result << 4 ^ tolower(Hexstr[i]) - ('a' - 10); // Remove the decimal part;
        offset -= 4;
    if (((len + ((len % 2) != 0)) << 2) > (sizeof(T) << 3) && Overflow)
        *Overflow = true;
    return result;

The 'Overflow' parameter is optional, so you can leave it NULL.


auto result = Hex2Int("C0ffee", NULL);
auto result2 = Hex2Int<long>("DeadC0ffe", NULL);

Initialise numpy array of unknown length

a = np.empty(0)
for x in y:
    a = np.append(a, x)

How do you change the server header returned by nginx?

Are you asking about the Server header value in the response? You can try changing that with an add_header directive, but I'm not sure if it'll work.

Linux command: How to 'find' only text files?

Here's a simplified version with extended explanation for beginners like me who are trying to learn how to put more than one command in one line.

If you were to write out the problem in steps, it would look like this:

// For every file in this directory
// Check the filetype
// If it's an ASCII file, then print out the filename

To achieve this, we can use three UNIX commands: find, file, and grep.

find will check every file in the directory.

file will give us the filetype. In our case, we're looking for a return of 'ASCII text'

grep will look for the keyword 'ASCII' in the output from file

So how can we string these together in a single line? There are multiple ways to do it, but I find that doing it in order of our pseudo-code makes the most sense (especially to a beginner like me).

find ./ -exec file {} ";" | grep 'ASCII'

Looks complicated, but not bad when we break it down:

find ./ = look through every file in this directory. The find command prints out the filename of any file that matches the 'expression', or whatever comes after the path, which in our case is the current directory or ./

The most important thing to understand is that everything after that first bit is going to be evaluated as either True or False. If True, the file name will get printed out. If not, then the command moves on.

-exec = this flag is an option within the find command that allows us to use the result of some other command as the search expression. It's like calling a function within a function.

file {} = the command being called inside of find. The file command returns a string that tells you the filetype of a file. Regularly, it would look like this: file mytextfile.txt. In our case, we want it to use whatever file is being looked at by the find command, so we put in the curly braces {} to act as an empty variable, or parameter. In other words, we're just asking for the system to output a string for every file in the directory.

";" = this is required by find and is the punctuation mark at the end of our -exec command. See the manual for 'find' for more explanation if you need it by running man find.

| grep 'ASCII' = | is a pipe. Pipe take the output of whatever is on the left and uses it as input to whatever is on the right. It takes the output of the find command (a string that is the filetype of a single file) and tests it to see if it contains the string 'ASCII'. If it does, it returns true.

NOW, the expression to the right of find ./ will return true when the grep command returns true. Voila.

How do I delete NuGet packages that are not referenced by any project in my solution?

You can use Package Manager Console with command: Uninstall-Package PackageId to remove it, or just delete package folder from 'packages' folder under solution folder. More information about Package Manager Console you can find here:

Detecting scroll direction

Simple code

// Events
$(document).on('mousewheel DOMMouseScroll', "element", function(e) {
    let delta = e.originalEvent.wheelDelta;
    if (delta > 0 || e.originalEvent.detail < 0) upScrollFunction();
    if (delta < 0 || e.originalEvent.detail > 0) donwScrollFunction();

Why shouldn't `&apos;` be used to escape single quotes?

&quot; is valid in both HTML5 and HTML4.

&apos; is valid in HTML5, but not HTML4. However, most browsers support &apos; for HTML4 anyway.

Calculating text width

My solution

$.fn.textWidth = function(){
    var self = $(this),
        children = self.children(),
        calculator = $('<span style="display: inline-block;" />'),

    width = children.parent().width(); // parent = the calculator wrapper
    return width;

Basically an improvement over Rune's, that doesn't use .html so lightly

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

MySQL - How to select data by string length

select * from table order by length(column);

Documentation on the length() function, as well as all the other string functions, is available here.

The meaning of NoInitialContextException error

Is a JNDI problem. You will see that exception if the InitialContext class has neither default properties for the JNDI service provider nor explicitly configured server properties.

Set the Context.INITIAL_CONTEXT_FACTORY environment property to the class name of the initial context implementation that you are using. This class must be available to your program in the classpath.


How to know which version of Symfony I have?

if you are in app_dev, you can find symfony version at the bottom left corner of the page

Storing Objects in HTML5 localStorage

Here some extented version of the code posted by @danott

It'll also implement delete value from localstorage and shows how to adds a Getter and Setter layer so instead of

localstorage.setItem(preview, true)

you can write

config.preview = true

Okay here were go:

var PT=Storage.prototype

if (typeof PT._setItem >='u') PT._setItem = PT.setItem;
PT.setItem = function(key, value)
  if (typeof value >='u')//..ndefined
    this._setItem(key, JSON.stringify(value));

if (typeof PT._getItem >='u') PT._getItem = PT.getItem;
PT.getItem = function(key)
  var ItemData = this._getItem(key)
    return JSON.parse(ItemData);
    return ItemData;

// Aliases for localStorage.set/getItem 
get =   localStorage.getItem.bind(localStorage)
set =   localStorage.setItem.bind(localStorage)

// Create ConfigWrapperObject
var config = {}

// Helper to create getter & setter
function configCreate(PropToAdd){
    Object.defineProperty( config, PropToAdd, {
      get: function ()      { return (  get(PropToAdd)      ) },
      set: function (val)   {           set(PropToAdd,  val ) }

// Usage Part
// Create properties

// Config Data transfer
config.preview = true


// delete
config.preview = undefined

Well you may strip the aliases part with .bind(...). However I just put it in since it's really good to know about this. I tooked me hours to find out why a simple get = localStorage.getItem; don't work

Check file extension in upload form in PHP

Personally,I prefer to use preg_match() function:

if(preg_match("/\.(gif|png|jpg)$/", $filename))

or in_array()

$exts = array('gif', 'png', 'jpg'); 
if(in_array(end(explode('.', $filename)), $exts)

With in_array() can be useful if you have a lot of extensions to validate and perfomance question. Another way to validade file images: you can use @imagecreatefrom*(), if the function fails, this mean the image is not valid.

For example:

function testimage($path)
   if(!preg_match("/\.(png|jpg|gif)$/",$path,$ext)) return 0;
   $ret = null;
       case 'png': $ret = @imagecreatefrompng($path); break;
       case 'jpeg': $ret = @imagecreatefromjpeg($path); break;
       // ...
       default: $ret = 0;

   return $ret;


$valid = testimage('foo.png');

Assuming that foo.png is a PHP-script file with .png extension, the above function fails. It can avoid attacks like shell update and LFI.

Unit testing void methods?

Test its side-effects. This includes:

  • Does it throw any exceptions? (If it should, check that it does. If it shouldn't, try some corner cases which might if you're not careful - null arguments being the most obvious thing.)
  • Does it play nicely with its parameters? (If they're mutable, does it mutate them when it shouldn't and vice versa?)
  • Does it have the right effect on the state of the object/type you're calling it on?

Of course, there's a limit to how much you can test. You generally can't test with every possible input, for example. Test pragmatically - enough to give you confidence that your code is designed appropriately and implemented correctly, and enough to act as supplemental documentation for what a caller might expect.

Write-back vs Write-Through caching?

Write-back and write-through describe policies when a write hit occurs, that is when the cache has the requested information. In these examples, we assume a single processor is writing to main memory with a cache.

Write-through: The information is written to the cache and memory, and the write finishes when both have finished. This has the advantage of being simpler to implement, and the main memory is always consistent (in sync) with the cache (for the uniprocessor case - if some other device modifies main memory, then this policy is not enough), and a read miss never results in writes to main memory. The obvious disadvantage is that every write hit has to do two writes, one of which accesses slower main memory.

Write-back: The information is written to a block in the cache. The modified cache block is only written to memory when it is replaced (in effect, a lazy write). A special bit for each cache block, the dirty bit, marks whether or not the cache block has been modified while in the cache. If the dirty bit is not set, the cache block is "clean" and a write miss does not have to write the block to memory.

The advantage is that writes can occur at the speed of the cache, and if writing within the same block only one write to main memory is needed (when the previous block is being replaced). The disadvantages are that this protocol is harder to implement, main memory can be not consistent (not in sync) with the cache, and reads that result in replacement may cause writes of dirty blocks to main memory.

The policies for a write miss are detailed in my first link.

These protocols don't take care of the cases with multiple processors and multiple caches, as is common in modern processors. For this, more complicated cache coherence mechanisms are required. Write-through caches have simpler protocols since a write to the cache is immediately reflected in memory.

Good resources:

How to convert column with string type to int form in pyspark data frame?

Another way to do it is using the StructField if you have multiple fields that needs to be modified.


from pyspark.sql.types import StructField,IntegerType, StructType,StringType



 |-- CLICK_FLG: string (nullable = true)
 |-- OPEN_FLG: string (nullable = true)
 |-- I1_GNDR_CODE: string (nullable = true)
 |-- TRW_INCOME_CD_V4: string (nullable = true)
 |-- ASIAN_CD: integer (nullable = true)
 |-- I1_INDIV_HHLD_STATUS_CODE: string (nullable = true)


 |-- CLICK_FLG: integer (nullable = true)
 |-- OPEN_FLG: integer (nullable = true)
 |-- I1_GNDR_CODE: string (nullable = true)
 |-- TRW_INCOME_CD_V4: string (nullable = true)
 |-- ASIAN_CD: integer (nullable = true)
 |-- I1_INDIV_HHLD_STATUS_CODE: integer (nullable = true)

This is slightly a long procedure to cast , but the advantage is that all the required fields can be done.

It is to be noted that if only the required fields are assigned the data type, then the resultant dataframe will contain only those fields which are changed.

Remove an item from array using UnderscoreJS

You can use reject method of Underscore, below will return a new array which won't have array with particular match

arr = _.reject(arr, function(objArr){ return == 3; });

A completely free agile software process tool Trello is free for unlimited users. Period.

You almost definitely don't need "Sub-cards". Use the checklists instead, or if you REALLY need sub-cards, don't have a parent sub-card. Just name the tickets something like "Epic - Story A" or "Story - task Z" or whatever.

Another idea is to create two boards (did I mention you can have unlimited boards for free too?). One for your epics and one for your stories. Call one your product management board and the other your sprint board, or whatever you like.

I'm not sure what you need different roles for - but, people aren't crazy - they know their job. As a startup if you already have problems getting people to not do crazy things (Where you need to restrict their permissions) you have much much bigger issues.

The point is that you need a SMALL tool to help you track stuff. Not a super rigid tool that makes you work in a super specific way. As a new (I assume?) startup, you should let your process grow into a tool. Don't beef up your process to fit a tool.

Show a div with Fancybox

Simple: e.g. if div id 'mydiv'{href: "#mydiv"});

This also makes JS code functional which is inside div.

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';

How to use the read command in Bash?

Typical usage might look like:

echo -e "hello1\nhello2\nhello3" | while read str ; do
    echo "$((++i)): $str"

and output

1: hello1
2: hello2
3: hello3

How to get previous page url using jquery

Easy as pie.

$(document).ready(function() {
   var referrer =  document.referrer;

Hope it helps. It is not always available though.

How can I get just the first row in a result set AFTER ordering?

In 12c, here's the new way:

select bla
  from bla
 where bla
 order by finaldate desc
 fetch first 1 rows only; 

How nice is that!

Concept behind putting wait(),notify() methods in Object class

These methods works on the locks and locks are associated with Object and not Threads. Hence, it is in Object class.

The methods wait(), notify() and notifyAll() are not only just methods, these are synchronization utility and used in communication mechanism among threads in Java.

For more detailed explanation, please visit :

SQL Inner Join On Null Values

Basically you want to join two tables together where their QID columns are both not null, correct? However, you aren't enforcing any other conditions, such as that the two QID values (which seems strange to me, but ok). Something as simple as the following (tested in MySQL) seems to do what you want:


This gives you every non-null row in Y joined to every non-null row in X.

Update: Rico says he also wants the rows with NULL values, why not just:


Bootstrap 3 Align Text To Bottom of Div

The easiest way I have tested just add a <br> as in the following:

<div class="col-sm-6">
    <br><h3><p class="text-center">Some Text</p></h3>

The only problem is that a extra line break (generated by that <br>) is generated when the screen gets smaller and it stacks. But it is quick and simple.

How do I enable saving of filled-in fields on a PDF form?

In Acrobat, click on the "Advanced" tab, then click on "Enable Features in Adobe Reader." This should do the trick.

Fatal error: Call to undefined function mb_strlen()

The function mb_strlen() is not enabled by default in PHP. Please read the manual for installation details:

Using FileUtils in eclipse

For selenium automation users

  1. Download Library file from
  2. Extract
  3. Right click on the proj name from the explorer >> Build path >>Config Build Path

Efficient way of having a function only execute once in a loop

If the condition check needs to happen only once you are in the loop, having a flag signaling that you have already run the function helps. In this case you used a counter, a boolean variable would work just as fine.

signal = False
count = 0 
def callme(): 
     print "I am being called"  
while count < 2: 
     if signal == False : 
         signal = True
     count +=1

how to use List<WebElement> webdriver

Try the following code:

By mySelector = By.xpath("/html/body/div[1]/div/section/div/div[2]/form[1]/div/ul/li");
List<WebElement> myElements = driver.findElements(mySelector);
for(WebElement e : myElements) {

It will returns with the whole content of the <li> tags, like:

<a class="extra">Vše</a> (950)</li>

But you can easily get the number now from it, for example by using split() and/or substring().

Best HTML5 markup for sidebar

Update 17/07/27: As this is the most-voted answer, I should update this to include current information locally (with links to the references).

From the spec [1]:

The aside element represents a section of a page that consists of content that is tangentially related to the content of the parenting sectioning content, and which could be considered separate from that content. Such sections are often represented as sidebars in printed typography.

Great! Exactly what we're looking for. In addition, it is best to check on <section> as well.

The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content. Each section should be identified, typically by including a heading (h1-h6 element) as a child of the section element.


A general rule is that the section element is appropriate only if the element’s contents would be listed explicitly in the document’s outline.

Excellent. Just what we're looking for. As opposed to <article> [2] which is for "self-contained" content, <section> allows for related content that isn't stand-alone, or generic enough for a <div> element.

As such, the spec seems to suggest that using Option 1, <aside> with <section> children is best practice.



HTML CSS Invisible Button

you must use the following properties for a button element to make it transparent.

Transparent Button With No Text

button {

    background: transparent;
    border: none !important;

Transparent Button With Visible Text

button {

    background: transparent;
    border: none !important;

and use absolute position to position the element.

For Example

you have the button element under a div. Use position : relative on div and position: absolute on the button to position it within the div.

here is a working JSFiddle

here is an updated JSFiddle that displays only text from the button.

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

Version 1.3.0 has flaw IMO.
Downgrade to version 1.2.3 fixes my problem.

I'm on

  • Laravel 5.1
  • PHP 5.6.40

Downgrade to Version 1.2.3

Get $_POST from multiple checkboxes

Set the name in the form to check_list[] and you will be able to access all the checkboxes as an array($_POST['check_list'][]).

Here's a little sample as requested:

<form action="test.php" method="post">
    <input type="checkbox" name="check_list[]" value="value 1">
    <input type="checkbox" name="check_list[]" value="value 2">
    <input type="checkbox" name="check_list[]" value="value 3">
    <input type="checkbox" name="check_list[]" value="value 4">
    <input type="checkbox" name="check_list[]" value="value 5">
    <input type="submit" />
if(!empty($_POST['check_list'])) {
    foreach($_POST['check_list'] as $check) {
            echo $check; //echoes the value set in the HTML form for each checked checkbox.
                         //so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
                         //in your case, it would echo whatever $row['Report ID'] is equivalent to.

Javascript Array inside Array - how can I call the child array name?

In that case you don't want to insert size and color inside an array, but into an object

var options = { 
    'size': size,
    'color': color

Afterwards you can access the sets of keys by

var keys = Object.keys( options );

How to Clear Console in Java?

Try this code


public class CLS {
    public static void main(String... arg) throws IOException, InterruptedException {
        new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();

Now when the Java process is connected to a console, it will clear the console.

How to set specific window (frame) size in java swing?

Try this, but you can adjust frame size with bounds and edit title.

package co.form.Try;

import javax.swing.JFrame;

public class Form {

    public static void main(String[] args) {
        JFrame obj =new JFrame();
        obj.setTitle("Application Form");



What is the maximum length of data I can put in a BLOB column in MySQL?

A BLOB can be 65535 bytes maximum. If you need more consider using a MEDIUMBLOB for 16777215 bytes or a LONGBLOB for 4294967295 bytes.

Hope, it will help you.

Set object property using reflection

I have just published a Nuget package that allows setting up not only the first level Properties but also nested properties in the given object in any depth.

Here is the package

Sets the value of a property of an object by its path from the root.

The object can be a complex object and the property can be multi level deep nested property or it can be a property directly under the root. ObjectWriter will find the property using the property path parameter and update its value. Property path is the appended names of the properties visited from root to the end node property which we want to set, delimited by the delimiter string parameter.


For setting up the properties directly under the object root:

Ie. LineItem class has an int property called ItemId

LineItem lineItem = new LineItem();

ObjectWriter.Set(lineItem, "ItemId", 13, delimiter: null);

For setting up nested property multiple levels below the object root:

Ie. Invite class has a property called State, which has a property called Invite (of Invite type), which has a property called Recipient, which has a property called Id.

To make things even more complex, the State property is not a reference type, it is a struct.

Here is how you can set the Id property (to string value of “outlook”) at the bottom of the object tree in a single line.

Invite invite = new Invite();

ObjectWriter.Set(invite, "State_Invite_Recipient_Id", "outlook", delimiter: "_");

Invalid default value for 'dateAdded'

mysql version 5.5 set datetime default value as CURRENT_TIMESTAMP will be report error you can update to version 5.6 , it set datetime default value as CURRENT_TIMESTAMP

Subtract two dates in Java

Edit 2018-05-28 I have changed the example to use Java 8's Time API:

LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);
Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
long diffDays = diff.toDays();

When do you use varargs in Java?

Varargs is the feature added in java version 1.5.

Why to use this?

  1. What if, you don't know the number of arguments to pass for a method?
  2. What if, you want to pass unlimited number of arguments to a method?

How this works?

It creates an array with the given arguments & passes the array to the method.

Example :

public class Solution {

    public static void main(String[] args) {

    public static void add(int... s){
        int sum=0;
        for(int num:s)
        System.out.println("sum is "+sum );


Output :


sum is 12


sum is 21

adb connection over tcp not working now

This answer is late, but hopefully it helps others.

I have had the same experience of not being able to connect. Rebooting phone and PC does not help. I found the fix at: at the bottom of the page.

Basically you follow these steps:

  1. Connect phone with usb cable to PC.
  2. Issue command: adb usb
  3. Issue command: adb tcpip 5555
  4. Issue command: adb connect

Where is your phone's IP address.

Couldn't connect to server

Just try:

sudo service mongod restart 

PHP: Read Specific Line From File

I searched for a one line solution to read specific line from a file. Here my solution:

echo file('dayInt.txt')[1]

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points


Now try:

plot sin(x) with points pointtype 5


You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

Correct Semantic tag for copyright info - html5

it is better to include it in a <small> tag The HTML <small> tag is used for specifying small print.

Small print (also referred to as "fine print" or "mouseprint") usually refers to the part of a document that contains disclaimers, caveats, or legal restrictions, such as copyrights. And this tag is supported in all major browsers.

 <small>&copy; Copyright 2058, Example Corporation</small>

How to set the matplotlib figure default size in ipython notebook?

If you don't have this file, you can create one by following the readme and typing

ipython profile create

WPF Check box: Check changed handling

A simple and proper way I've found to Handle Checked/Unchecked events using MVVM pattern is the Following, with Caliburn.Micro :

 <CheckBox IsChecked="{Binding IsCheckedBooleanProperty}" Content="{DynamicResource DisplayContent}" cal:Message.Attach="[Event Checked] = [Action CheckBoxClicked()]; [Event Unchecked] = [Action CheckBoxClicked()]" />

And implement a Method CheckBoxClicked() in the ViewModel, to do stuff you want.

pandas groupby sort within groups

Here's other example of taking top 3 on sorted order, and sorting within the groups:

In [43]: import pandas as pd                                                                                                                                                       

In [44]:  df = pd.DataFrame({"name":["Foo", "Foo", "Baar", "Foo", "Baar", "Foo", "Baar", "Baar"], "count_1":[5,10,12,15,20,25,30,35], "count_2" :[100,150,100,25,250,300,400,500]})

In [45]: df                                                                                                                                                                        
   count_1  count_2  name
0        5      100   Foo
1       10      150   Foo
2       12      100  Baar
3       15       25   Foo
4       20      250  Baar
5       25      300   Foo
6       30      400  Baar
7       35      500  Baar

### Top 3 on sorted order:
In [46]: df.groupby(["name"])["count_1"].nlargest(3)                                                                                                                               
Baar  7    35
      6    30
      4    20
Foo   5    25
      3    15
      1    10
dtype: int64

### Sorting within groups based on column "count_1":
In [48]: df.groupby(["name"]).apply(lambda x: x.sort_values(["count_1"], ascending = False)).reset_index(drop=True)
   count_1  count_2  name
0       35      500  Baar
1       30      400  Baar
2       20      250  Baar
3       12      100  Baar
4       25      300   Foo
5       15       25   Foo
6       10      150   Foo
7        5      100   Foo

jQuery Validate Plugin - Trigger validation of single field

For some reason, some of the other methods don't work until the field has been focused/blured/changed, or a submit has been attempted... this works for me.


Had to dig through the jquery.validate script to find it...

Highcharts - how to have a chart with dynamic height?

Alternatively, you can directly use javascript's window.onresize

As example, my code (using scriptaculos) is :

window.onresize = function (){
    var w = $("form").getWidth() + "px";
    $('gfx').setStyle( { width : w } );

Where form is an html form on my webpage and gfx the highchart graphics.

Regular Expression to get all characters before "-"

You could just use another non-regex based method. Someone gave the suggestion of using Substring, but you could also use Split:

string testString = "my-string";
string[] splitString = testString.Split("-");
string resultingString = splitString[0]; //my

See for another good example.

How to create an empty R vector to add new items

I've also seen

x <- {}

Now you can concatenate or bind a vector of any dimension to x

rbind(x, 1:10)
cbind(x, 1:10)
c(x, 10)

Catching access violation exceptions?

Not the exception handling mechanism, But you can use the signal() mechanism that is provided by the C.

> man signal

     11    SIGSEGV      create core image    segmentation violation

Writing to a NULL pointer is probably going to cause a SIGSEGV signal

JavaScript adding decimal numbers issue

function add(){
    var first=parseFloat($("#first").val());
    var second=parseFloat($("#second").val());


200 PORT command successful. Consider using PASV. 425 Failed to establish connection

You are using the FTP in an active mode.

Setting up the FTP in the active mode can be cumbersome nowadays due to firewalls and NATs.

It's likely because of your local firewall or NAT that the server was not able to connect back to your client to establish data transfer connection.

Or your client is not aware of its external IP address and provides an internal address instead to the server (in PORT command), which the server is obviously not able to use. But it should not be the case, as vsftpd by default rejects data transfer address not identical to source address of FTP control connection (the port_promiscuous directive).

See my article Network Configuration for Active Mode.

If possible, you should use a passive mode as it typically requires no additional setup on a client-side. That's also what the server suggested you by "Consider using PASV". The PASV is an FTP command used to enter the passive mode.

Unfortunately Windows FTP command-line client (the ftp.exe) does not support passive mode at all. It makes it pretty useless nowadays.

Use any other 3rd party Windows FTP command-line client instead. Most other support the passive mode.

For example WinSCP FTP client defaults to the passive mode and there's a guide available for converting Windows FTP script to WinSCP script.

(I'm the author of WinSCP)

Running code in main thread from another thread

There is another simple way, if you don't have an access to the Context.

1). Create a handler from the main looper:

Handler uiHandler = new Handler(Looper.getMainLooper());

2). Implement a Runnable interface:

Runnable runnable = new Runnable() { // your code here }

3). Post your Runnable to the uiHandler:;

That's all ;-) Have fun with threads, but don't forget to synchronize them.

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

I fixed this problem employing the two procedures of :

  1. In Eclipse->'Project' menu -> 'Java Compiler' -> set 'Compiler compliance level' = 1.6 check on 'Use default compliance settings' Set 'Generated .class compatibility' = 1.6 Set 'Source compatibilty' = 1.6

  2. Then go to 'Windows' menu --> 'Preferences' -->'Java' , expand 'Java' --> 'Compiler' -->Set 'Compiler compliance level' = 1.6

Hint: Source compatibility must be equal to or less than compliance level.

How to add text at the end of each line in Vim?

This will do it to every line in the file:


If you want to do a subset of lines instead of the whole file, you can specify them in place of the %.

One way is to do a visual select and then type the :. It will fill in :'<,'> for you, then you type the rest of it (Notice you only need to add s/$/,/)


TensorFlow: "Attempting to use uninitialized value" in variable initialization

There is another the error happening which related to the order when calling initializing global variables. I've had the sample of code has similar error FailedPreconditionError (see above for traceback): Attempting to use uninitialized value W

def linear(X, n_input, n_output, activation = None):
    W = tf.Variable(tf.random_normal([n_input, n_output], stddev=0.1), name='W')
    b = tf.Variable(tf.constant(0, dtype=tf.float32, shape=[n_output]), name='b')
    if activation != None:
        h = tf.nn.tanh(tf.add(tf.matmul(X, W),b), name='h')
        h = tf.add(tf.matmul(X, W),b, name='h')
    return h

from tensorflow.python.framework import ops
g = tf.get_default_graph()
print([ for op in g.get_operations()])
with tf.Session() as sess:
    # RUN INIT
    # But W hasn't in the graph yet so not know to initialize 
    # EVAL then error
    print(linear(np.array([[1.0,2.0,3.0]]).astype(np.float32), 3, 3).eval())

You should change to following

from tensorflow.python.framework import ops
g = tf.get_default_graph()
print([ for op in g.get_operations()])
with tf.Session() as 
    l = linear(np.array([[1.0,2.0,3.0]]).astype(np.float32), 3, 3)
    # RUN INIT
    print([ for op in g.get_operations()])

How to add local jar files to a Maven project?

To install third party jar, Please call the command like below

mvn install:install-file -DgroupId= -DartifactId= -Dversion= -Dpackaging=jar -Dfile=path

How to make HTML element resizable using pure Javascript?

I just created a CodePen that shows how this can be done pretty easily using ES6.

Basically, here is the class that does this.

let getPropertyValue = function(style, prop) {
  let value = style.getPropertyValue(prop);
  value = value ? value.replace(/[^0-9.]/g, '') : '0';
  return parseFloat(value);

let getElementRect = function(element) {
  let style = window.getComputedStyle(element, null);
  return {
    x: getPropertyValue(style, 'left'),
    y: getPropertyValue(style, 'top'),
    width: getPropertyValue(style, 'width'),
    height: getPropertyValue(style, 'height')

class Resizer {
    constructor(wrapper, element, options) {
        this.wrapper = wrapper;
        this.element = element;
        this.options = options;
        this.offsetX = 0;
        this.offsetY = 0;
        this.handle = document.createElement('div');
        this.handle.setAttribute('class', 'drag-resize-handlers');
        this.handle.setAttribute('data-direction', 'br');
        this.wrapper.appendChild(this.handle); =; =; =; =; = 'relative'; = 0; = 0;
        this.onResize = this.resizeHandler.bind(this);
        this.onStop = this.stopResize.bind(this);
        this.handle.addEventListener('mousedown', this.initResize.bind(this));

    initResize(event) {
        this.stopResize(event, true);
        this.handle.addEventListener('mousemove', this.onResize);
        this.handle.addEventListener('mouseup', this.onStop);

    resizeHandler(event) {
        this.offsetX = event.clientX - (this.wrapper.offsetLeft + this.handle.offsetLeft);
        this.offsetY = event.clientY - (this.wrapper.offsetTop + this.handle.offsetTop);
        let wrapperRect = getElementRect(this.wrapper);
        let elementRect = getElementRect(this.element); = (wrapperRect.width + this.offsetX) + 'px'; = (wrapperRect.height + this.offsetY) + 'px'; = (elementRect.width + this.offsetX) + 'px'; = (elementRect.height + this.offsetY) + 'px';

    stopResize(event, nocb) {
        this.handle.removeEventListener('mousemove', this.onResize); 
        this.handle.removeEventListener('mouseup', this.onStop);

class Dragger {
    constructor(wrapper, element, options) {
        this.wrapper = wrapper;
        this.options = options;
        this.element = element;
        this.element.draggable = true;
        this.element.setAttribute('draggable', true);
        this.element.addEventListener('dragstart', this.dragStart.bind(this));

    dragStart(event) {
        let wrapperRect = getElementRect(this.wrapper);
        var x = wrapperRect.x - parseFloat(event.clientX);
        var y = wrapperRect.y - parseFloat(event.clientY);
        event.dataTransfer.setData("text/plain", + ',' + x + ',' + y);

    dragStop(event, prevX, prevY) {
        var posX = parseFloat(event.clientX) + prevX;
        var posY = parseFloat(event.clientY) + prevY; = posX + 'px'; = posY + 'px';

class DragResize {
    constructor(element, options) {
        options = options || {};
        this.wrapper = document.createElement('div');
        this.wrapper.setAttribute('class', 'tooltip drag-resize');
        if (element.parentNode) {
          element.parentNode.insertBefore(this.wrapper, element);
        element.resizer = new Resizer(this.wrapper, element, options);
        element.dragger = new Dragger(this.wrapper, element, options);

document.body.addEventListener('dragover', function (event) {
    return false;

document.body.addEventListener('drop', function (event) {
    var dropData = event.dataTransfer.getData("text/plain").split(',');
    var element = document.getElementById(dropData[0]);
    element.dragger.dragStop(event, parseFloat(dropData[1]), parseFloat(dropData[2]));
    return false;

Bootstrap Modal sitting behind backdrop

Just remove the backdrop, insert this code in your css file

.modal-backdrop {
      /* bug fix - no overlay */    
      display: none;    

throwing exceptions out of a destructor

I am in the group that considers that the "scoped guard" pattern throwing in the destructor is useful in many situations - particularly for unit tests. However, be aware that in C++11, throwing in a destructor results in a call to std::terminate since destructors are implicitly annotated with noexcept.

Andrzej Krzemienski has a great post on the topic of destructors that throw:

He points out that C++11 has a mechanism to override the default noexcept for destructors:

In C++11, a destructor is implicitly specified as noexcept. Even if you add no specification and define your destructor like this:

  class MyType {
        public: ~MyType() { throw Exception(); }            // ...

The compiler will still invisibly add specification noexcept to your destructor. And this means that the moment your destructor throws an exception, std::terminate will be called, even if there was no double-exception situation. If you are really determined to allow your destructors to throw, you will have to specify this explicitly; you have three options:

  • Explicitly specify your destructor as noexcept(false),
  • Inherit your class from another one that already specifies its destructor as noexcept(false).
  • Put a non-static data member in your class that already specifies its destructor as noexcept(false).

Finally, if you do decide to throw in the destructor, you should always be aware of the risk of a double-exception (throwing while the stack is being unwind because of an exception). This would cause a call to std::terminate and it is rarely what you want. To avoid this behaviour, you can simply check if there is already an exception before throwing a new one using std::uncaught_exception().

Server cannot set status after HTTP headers have been sent IIS7.5

You are actually trying to redirect a page which has some response to throw. So first you keep the information you have throw in a buffer using response.buffer = true in beginning of the page and then flush it when required using response.flush this error will get fixed

Why does overflow:hidden not work in a <td>?

I'm not familiar with the specific issue, but you could stick a div, etc inside the td and set overflow on that.

jQuery - Detecting if a file has been selected in the file input

You should be able to attach an event handler to the onchange event of the input and have that call a function to set the text in your span.

<script type="text/javascript">
  $(function() {
     $("input:file").change(function (){
       var fileName = $(this).val();

You may want to add IDs to your input and span so you can select based on those to be specific to the elements you are concerned with and not other file inputs or spans in the DOM.

Filter items which array contains any of given values

Whilst this an old question, I ran into this problem myself recently and some of the answers here are now deprecated (as the comments point out). So for the benefit of others who may have stumbled here:

A term query can be used to find the exact term specified in the reverse index:

  "query": {
   "term" : { "tags" : "a" }

From the documenation

Alternatively you can use a terms query, which will match all documents with any of the items specified in the given array:

  "query": {
   "terms" : { "tags" : ["a", "c"]}

One gotcha to be aware of (which caught me out) - how you define the document also makes a difference. If the field you're searching in has been indexed as a text type then Elasticsearch will perform a full text search (i.e using an analyzed string).

If you've indexed the field as a keyword then a keyword search using a 'non-analyzed' string is performed. This can have a massive practical impact as Analyzed strings are pre-processed (lowercased, punctuation dropped etc.) See (

To avoid these issues, the string field has split into two new types: text, which should be used for full-text search, and keyword, which should be used for keyword search. (

HTML favicon won't show on google chrome

It doesn't look like Chrome allows you to display the favicon in the address bar...

I've also seen it done like this. Don't know if it would make a difference or not.

<link rel="icon" href="/favicon.ico" />

How to update column value in laravel

Version 1:

// Update data of question values with $data from formulay
$Q1 = Question::find($id);

Version 2:

$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';

In case of answered question you can use them:

$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';

How to select a directory and store the location using tkinter in Python

This code may be helpful for you.

from tkinter import filedialog
from tkinter import *
root = Tk()
folder_selected = filedialog.askdirectory()

Call JavaScript function on DropDownList SelectedIndexChanged Event:

You can use the ScriptManager.RegisterStartupScript(); to call any of your javascript event/Client Event from the server. For example, to display a message using javascript's alert();, you can do this:

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
Response.write("<script>alert('This is my message');</script>");
 //----or alternatively and to be more proper
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "alert('This is my message')", true);

To be exact for you, do this...

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "CalcTotalAmt();", true);

change <audio> src with javascript

If you are storing metadata in a tag use data attributes eg.

<li id="song1" data-value="song1.ogg"><button onclick="updateSource()">Item1</button></li>

Now use the attribute to get the name of the song

var audio = document.getElementById('audio');
audio.src='audio/ogg/' + document.getElementById('song1').getAttribute('data-value');

Formatting floats in a numpy array

You can use round function. Here some example

numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53,   8.13,   3.97,  10.08])

IF you want change just display representation, I would not recommended to alter printing format globally, as it suggested above. I would format my output in place.

>>a=np.array([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01])
>>> print([ "{:0.2f}".format(x) for x in a ])
['21.53', '8.13', '3.97', '10.08']

How to ssh connect through python Paramiko with ppk public key

@VonC's answer to a duplicate question:

If, as commented, Paraminko does not support PPK key, the official solution, as seen here, would be to use PuTTYgen.

But you can also use the Python library CkSshKey to make that same conversion directly in your program.

See "Convert PuTTY Private Key (ppk) to OpenSSH (pem)"

import sys
import chilkat

key = chilkat.CkSshKey()

#  Load an unencrypted or encrypted PuTTY private key.

#  If  your PuTTY private key is encrypted, set the Password
#  property before calling FromPuttyPrivateKey.
#  If your PuTTY private key is not encrypted, it makes no diffference
#  if Password is set or not set.

#  First load the .ppk file into a string:

keyStr = key.loadText("putty_private_key.ppk")

#  Import into the SSH key object:
success = key.FromPuttyPrivateKey(keyStr)
if (success != True):

#  Convert to an encrypted or unencrypted OpenSSH key.

#  First demonstrate converting to an unencrypted OpenSSH key

bEncrypt = False
unencryptedKeyStr = key.toOpenSshPrivateKey(bEncrypt)
success = key.SaveText(unencryptedKeyStr,"unencrypted_openssh.pem")
if (success != True):

How to hide scrollbar in Firefox?

For webkit use following:

::-webkit-scrollbar {
    width: 0px;  /* remove scrollbar space */
    background: transparent;  /* optional: just make scrollbar invisible */

For Mozilla Firefox use following code:

@-moz-document url-prefix() {
    html,body{overflow: hidden !important;}

and if scrolling does not work then add

element {overflow-y: scroll;}

to specific element

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

$start_date = new DateTime();

Notice: Trying to get property of non-object error

This is because $pjs is an one-element-array of objects, so first you should access the array element, which is an object and then access its attributes.

echo $pjs[0]->player_name;

Actually dump result that you pasted tells it very clearly.

Converting an int to a binary string representation in Java?

This should be quite simple with something like this :

public static String toBinary(int number){
    StringBuilder sb = new StringBuilder();

    if(number == 0)
        return "0";
        number = number / 2;

    return sb.reverse().toString();


How can I get the current date and time in UTC or GMT in Java?

Here is what seems to be incorrect in Jon Skeet's answer. He said:

java.util.Date is always in UTC. What makes you think it's in local time? I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly using Date.toString() which also uses the local timezone.

However, the code:

System.out.println(new java.util.Date().getHours() + " hours");

gives the local hours, not GMT (UTC hours), using no Calendar and no SimpleDateFormat at all.

That is why is seems something is incorrect.

Putting together the responses, the code:

                           .get(Calendar.HOUR_OF_DAY) + " Hours");

shows the GMT hours instead of the local hours -- note that getTime.getHours() is missing because that would create a Date() object, which theoretically stores the date in GMT, but gives back the hours in the local time zone.

How to check whether a Storage item is set?

Best and Safest way i can suggest is this,

if(, 'infiniteScrollEnabled')){
    // init variable/set default variable for item
    localStorage.setItem("infiniteScrollEnabled", true);

This passes through ESLint's no-prototype-builtins rule.

How can I upgrade specific packages using pip and a requirements file?

If you only want to upgrade one specific package called somepackage, the command you should use in recent versions of pip is

pip install --upgrade --upgrade-strategy only-if-needed somepackage

This is very useful when you develop an application in Django that currently will only work with a specific version of Django (say Django=1.9.x) and want to upgrade some dependent package with a bug-fix/new feature and the upgraded package depends on Django (but it works with, say, any version of Django after 1.5).

The default behavior of pip install --upgrade django-some-package would be to upgrade Django to the latest version available which could otherwise break your application, though with the --upgrade-strategy only-if-needed dependent packages will now only be upgraded as necessary.

Keep overflow div scrolled to bottom unless user scrolls up

In 2020, you can use css snap, but before Chrome 81 the layout change will not trigger re-snap, a pure css chat ui works on Chrome 81, also you can check Can I use CSS snap.

This demo will snap the last element if visible, scroll to bottom to see the effect.

.container {
  overflow-y: scroll;
  overscroll-behavior-y: contain;
  scroll-snap-type: y proximity;

.container > div > div:last-child {
  scroll-snap-align: end;

.container > div > div {
  background: lightgray;
  height: 3rem;
  font-size: 1.5rem;
.container > div > div:nth-child(2n) {
  background: gray;
<div class="container" style="height:6rem">

enter image description here


use scroll-snap-type: y proximity;, scroll up easier.

Excel VBA Run-time Error '32809' - Trying to Understand it

I have removed all ActiveX controls from sheet and now it works smoothly without any error messages. That's my solution.

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

How can I rename a conda environment?

You can rename your Conda env by just renaming the env folder. Here is the proof:

Conda env renaming

You can find your Conda env folder inside of C:\ProgramData\Anaconda3\envs or you can enter conda env list to see the list of conda envs and its location.

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

SSSSSS is microseconds. Let us say the time is 10:30:22 (Seconds 22) and 10:30:22.1 would be 22 seconds and 1/10 of a second . Extending the same logic , 10:32.22.000132 would be 22 seconds and 132/1,000,000 of a second, which is nothing but microseconds.

Read lines from a file into a Bash array

The simplest way to read each line of a file into a bash array is this:

IFS=$'\n' read -d '' -r -a lines < /etc/passwd

Now just index in to the array lines to retrieve each line, e.g.

printf "line 1: %s\n" "${lines[0]}"
printf "line 5: %s\n" "${lines[4]}"

# all lines
echo "${lines[@]}"

How to convert an int to a hex string?

This will convert an integer to a 2 digit hex string with the 0x prefix:

strHex = "0x%0.2X" % 255

onMeasure custom view explanation

If you don't need to change something onMeasure - there's absolutely no need for you to override it.

Devunwired code (the selected and most voted answer here) is almost identical to what the SDK implementation already does for you (and I checked - it had done that since 2009).

You can check the onMeasure method here :

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
            getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));

public static int getDefaultSize(int size, int measureSpec) {
    int result = size;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);

    switch (specMode) {
    case MeasureSpec.UNSPECIFIED:
        result = size;
    case MeasureSpec.AT_MOST:
    case MeasureSpec.EXACTLY:
        result = specSize;
    return result;

Overriding SDK code to be replaced with the exact same code makes no sense.

This official doc's piece that claims "the default onMeasure() will always set a size of 100x100" - is wrong.

How do I compile a .cpp file on Linux?

You'll need to compile it using:

g++ inputfile.cpp -o outputbinary

The file you are referring has a missing #include <cstdlib> directive, if you also include that in your file, everything shall compile fine.

oracle.jdbc.driver.OracleDriver ClassNotFoundException

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Just add the ojdbc14.jar to your classpath.

The following are the steps that are given below to add ojdbc14.jar in eclipse:

1) Inside your project

2) Libraries

3) Right click on JRE System Library

4) Build Path

5) Select Configure Build Path

6) Click on Add external JARs...

7) C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib

8) Here you will get ojdbc14.jar

9) select here

10) open

11) ok

save and run the program you will get output.

Simple check for SELECT query empty result


SELECT * FROM service s WHERE s.service_id = ?;

    PRINT 'no rows!'

C free(): invalid pointer

From where did you get the idea that you need to free(token) and free(tk)? You don't. strsep() doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc() (or similar), so free()ing them is undefined behavior. You only need to free(s) when you are done with the entire string.

Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup() and free() altogether by simply writing char *s = p;.

How can I execute PHP code from the command line?

If you're going to do PHP in the command line, I recommend you install phpsh, a decent PHP shell. It's a lot more fun.

Anyway, the php command offers two switches to execute code from the command line:

-r <code>        Run PHP <code> without using script tags <?..?>
-R <code>        Run PHP <code> for every input line

You can use php's -r switch as such:

php -r 'echo function_exists("foo") ? "yes" : "no";'

The above PHP command above should output no and returns 0 as you can see:

>>> php -r 'echo function_exists("foo") ? "yes" : "no";'
>>> echo $? # print the return value of the previous command

Another funny switch is php -a:

-a               Run as interactive shell

It's sort of lame compared to phpsh, but if you don't want to install the awesome interactive shell for PHP made by Facebook to get tab completion, history, and so on, then use -a as such:

>>> php -a
Interactive shell

php > echo function_exists("foo") ? "yes" : "no";
php >

If it doesn't work on your box like on my boxes (tested on Ubuntu and Arch Linux), then probably your PHP setup is fuzzy or broken. If you run this command:

php -i | grep 'API'

You should see:

Server API => Command Line Interface

If you don't, this means that maybe another command will provides the CLI SAPI. Try php-cli; maybe it's a package or a command available in your OS.

If you do see that your php command uses the CLI (command-line interface) SAPI (Server API), then run php -h | grep code to find out which crazy switch - as this hasn't changed for year- allows to run code in your version/setup.

Another couple of examples, just to make sure it works on my boxes:

>>> php -r 'echo function_exists("sg_load") ? "yes" : "no";'
>>> php -r 'echo function_exists("print_r") ? "yes" : "no";'

Also, note that it is possible that an extension is loaded in the CLI and not in the CGI or Apache SAPI. It is likely that several PHP SAPIs use different php.ini files, e.g., /etc/php/cli/php.ini vs. /etc/php/cgi/php.ini vs. /etc/php/apache/php.ini on a Gentoo Linux box. Find out which ini file is used with php -i | grep ini.

Convert StreamReader to byte[]

You can use this code: You shouldn't use this code:

byte[] bytes = streamReader.CurrentEncoding.GetBytes(streamReader.ReadToEnd());

Please see the comment to this answer as to why. I will leave the answer, so people know about the problems with this approach, because I didn't up till now.

How to automatically update an application without ClickOnce?

A Lay men's way is

on Main() rename the executing assembly file .exe to some thing else check date and time of created. and the updated file date time and copy to the application folder.

//Rename he executing file
System.IO.FileInfo file = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);

System.IO.File.Move(file.FullName, file.DirectoryName + "\\" + file.Name.Replace(file.Extension,"") + "-1" + file.Extension);

then do the logic check and copy the new file to executing folder

How do I encrypt and decrypt a string in python?

Although its very old, but I thought of sharing another idea to do this:

from Crypto.Cipher import AES    
from Crypto.Hash import SHA256

password = ("anything")    
hash_obj ='utf-8'))    
hkey = hash_obj.digest()

def encrypt(info):
    msg = info
    BLOCK_SIZE = 16
    PAD = "{"
    padding = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PAD
    cipher =, AES.MODE_ECB)
    result = cipher.encrypt(padding(msg).encode('utf-8'))
    return result  

msg = "Hello stackoverflow!"
cipher_text = encrypt(msg)

def decrypt(info):
    msg = info
    PAD = "{"
    decipher =, AES.MODE_ECB)
    pt = decipher.decrypt(msg).decode('utf-8')
    pad_index = pt.find(PAD)
    result = pt[: pad_index]
    return result

plaintext = decrypt(cipher_text)


> b'\xcb\x0b\x8c\xdc#\n\xdd\x80\xa6|\xacu\x1dEg;\x8e\xa2\xaf\x80\xea\x95\x80\x02\x13\x1aem\xcb\xf40\xdb'

> Hello stackoverflow!

How to use NULL or empty string in SQL




Open Bootstrap Modal from code-behind

This method of opening the Modal would not display the Modal for me. I found this as a work arround.

I removed:

 ScriptManager.RegisterStartupScript(this,this.GetType(),"Pop", "openModal();", true);

Than I added an asp:label named lblJavaScript and in code behind call:

lblJavaScript.Text = "<script language=\"JavaScript\">openModal()</script>";

Now the Modal will display.

Change image onmouseover

I know someone answered this the same way, but I made my own research, and I wrote this before to see that answer. So: I was looking for something simple with inline JavaScript, with just on the img, without "wrapping" it into the a tag (so instead of the document.MyImage, I used this.src)

src="ico/view.png" alt="hover effect" />

It works on all currently updated browsers; IE 11 (and I also tested it in the Developer Tools of IE from IE5 and above), Chrome, Firefox, Opera, Edge.

Confused about __str__ on list in Python

Because of the infinite superiority of Python over Java, Python has not one, but two toString operations.

One is __str__, the other is __repr__

__str__ will return a human readable string. __repr__ will return an internal representation.

__repr__ can be invoked on an object by calling repr(obj) or by using backticks `obj`.

When printing lists as well as other container classes, the contained elements will be printed using __repr__.

"E: Unable to locate package python-pip" on Ubuntu 18.04

You might have python 3 pip installed already. Instead of pip install you can use pip3 install.

Commit history on remote repository

This is what worked for me:

git fetch --all 
git log production/master

Note that this fetches from ALL remotes, i.e. potentially you "have to clone 2GB worth of objects just to look through the commit logs".

What does "control reaches end of non-void function" mean?

The compiler cannot tell from that code if the function will ever reach the end and still return something. To make that clear, replace the last else if(...) with just else.

SoapFault exception: Could not connect to host

A misconfigured service leaves the default namespace with

This means the connection to the wsdl will work, but the function call will fail.


SoapClient->__doRequest('', '', 2, 0)

To remediate this, you must explicitly set the location using __setLocation()

$this->soapClient = new \SoapClient(WS_URL);

Creating columns in listView and add items

Your first problem is that you are passing -3 to the 2nd parameter of Columns.Add. It needs to be -2 for it to auto-size the column. Source: (look at the comments on the code example at the bottom)

private void initListView()
    // Add columns
    lvRegAnimals.Columns.Add("Id", -2,HorizontalAlignment.Left);
    lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
    lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);

You can also use the other overload, Add(string). E.g:


Reference for more overloads:

Second, to add items to the ListView, you need to create instances of ListViewItem and add them to the listView's Items collection. You will need to use the string[] constructor.

var item1 = new ListViewItem(new[] {"id123", "Tom", "24"});
var item2 = new ListViewItem(new[] {person.Id, person.Name, person.Age});

You can also store objects in the item's Tag property.

item2.Tag = person;

And then you can extract it

var person = item2.Tag as Person;

Let me know if you have any questions and I hope this helps!

How to flush route table in windows?

You can open a command prompt and do a

route print

and see your current routing table.

You can modify it by

route add    d.d.d.d mask m.m.m.m g.g.g.g 
route delete d.d.d.d mask m.m.m.m g.g.g.g 
route change d.d.d.d mask m.m.m.m g.g.g.g

these seem to work

I run a ping d.d.d.d -t change the route and it changes. (my test involved routing to a dead route and the ping stopped)

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

We have 1 MB - 3 KB RAM = 2^23 - 3*2^13 bits = 8388608 - 24576 = 8364032 bits available.

We are given 10^6 numbers in a 10^8 range. This gives an average gap of ~100 < 2^7 = 128

Let's first consider the simpler problem of fairly evenly spaced numbers when all gaps are < 128. This is easy. Just store the first number and the 7-bit gaps:

(27 bits) + 10^6 7-bit gap numbers = 7000027 bits required

Note repeated numbers have gaps of 0.

But what if we have gaps larger than 127?

OK, let's say a gap size < 127 is represented directly, but a gap size of 127 is followed by a continuous 8-bit encoding for the actual gap length:

 10xxxxxx xxxxxxxx                       = 127 .. 16,383
 110xxxxx xxxxxxxx xxxxxxxx              = 16384 .. 2,097,151


Note this number representation describes its own length so we know when the next gap number starts.

With just small gaps < 127, this still requires 7000027 bits.

There can be up to (10^8)/(2^7) = 781250 23-bit gap number, requiring an extra 16*781,250 = 12,500,000 bits which is too much. We need a more compact and slowly increasing representation of gaps.

The average gap size is 100 so if we reorder them as [100, 99, 101, 98, 102, ..., 2, 198, 1, 199, 0, 200, 201, 202, ...] and index this with a dense binary Fibonacci base encoding with no pairs of zeros (for example, 11011=8+5+2+1=16) with numbers delimited by '00' then I think we can keep the gap representation short enough, but it needs more analysis.

Bootstrap carousel resizing image

I had the same problem. You have to use all the images with same height and width. you can simply change it using paint application from windows using the resize option in the home section and then use CSS to resize the image. Maybe this problem occurs because the the width and height attribute inside the tag is not responding.

How to make an input type=button act like a hyperlink and redirect using a get request?

You can make <button> tag to do action like this:

<a href="">
   <button>Visit Google</button>


<a href="">
   <input type="button" value="Visit Google" />

It's simple and no javascript required!


This approach is not valid from HTML structure. But, it works on many modern browser. See following reference :

How can I remove a character from a string using JavaScript?

In C# (Sharp), you can make an empty character as '\0'. Maybe you can do this:

String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + char.length);
mystring.replaceAt(4, '\0')

Search on google or surf on the interent and check if javascript allows you to make empty characters, like C# does. If yes, then learn how to do it, and maybe the replaceAt function will work at last, and you'll achieve what you want!

Finally that 'r' character will be removed!

How to set the color of an icon in Angular Material?

In the component.css or app.css add Icon Color styles

.material-icons.color_green { color: #00FF00; }
.material-icons.color_white { color: #FFFFFF; }

In the component.html set the icon class

<mat-icon class="material-icons color_green">games</mat-icon>
<mat-icon class="material-icons color_white">cloud</mat-icon>

ng build

Array.push() and unique items

Your logic is saying, "if this item exists already, then add it." It should be the opposite of that.

Change it to...

if (this.items.indexOf(item) == -1) {

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

I was getting the same error when I used this code to update the record:

@mysqli_query($dbc,$query or die()))

After removing or die, it started working properly.

How to insert values into the database table using VBA in MS access

You can't run two SQL statements into one like you are doing.

You can't "execute" a select query.

db is an object and you haven't set it to anything: (e.g. set db = currentdb)

In VBA integer types can hold up to max of 32767 - I would be tempted to use Long.

You might want to be a bit more specific about the date you are inserting:

INSERT INTO Test (Start_Date) VALUES ('#" & format(InDate, "mm/dd/yyyy") & "#' );"

Short form for Java if statement

name = city.getName()!=null?city.getName():"N/A"

How do I declare an array of undefined or no initial size?

Try to implement dynamic data structure such as a linked list

set dropdown value by text using jquery

$("#HowYouKnow option[value='" + theText + "']").attr('selected', 'selected'); // added single quotes

Set attribute without value

Not sure if this is really beneficial or why I prefer this style but what I do (in vanilla js) is:


This will add the attribute in all lowercase without a value or remove it if it already exists on the element.

How can I get name of element with jQuery?

You should use attr('name') like this


you should use an id selector, if you use a class selector you encounter problems because a collection is returned

How to get my activity context?

The best and easy way to get the activity context is putting .this after the name of the Activity. For example: If your Activity's name is SecondActivity, its context will be SecondActivity.this

How do you create a UIImage View Programmatically - Swift

Swift 4:

First create an outlet for your UIImageView

@IBOutlet var infoImage: UIImageView!

Then use the image property in UIImageView

infoImage.image = UIImage(named: "icons8-info-white")

Some projects cannot be imported because they already exist in the workspace error in Eclipse

go to .project file in your project and change the name of the project in name tag

C# DateTime to UTC Time without changing the time

You can use the overloaded constructor of DateTime:

DateTime utcDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, DateTimeKind.Utc);

Read file content from S3 bucket with boto3

When you want to read a file with a different configuration than the default one, feel free to use either directly or the copy-pasted code:

def s3_read(source, profile_name=None):
    Read a file from an S3 source.

    source : str
        Path starting with s3://, e.g. 's3://bucket-name/key/'
    profile_name : str, optional
        AWS profile

    content : bytes

        Botocore is not able to find your credentials. Either specify
        profile_name or add the environment variables AWS_ACCESS_KEY_ID,
    session = boto3.Session(profile_name=profile_name)
    s3 = session.client('s3')
    bucket_name, key =
    s3_object = s3.get_object(Bucket=bucket_name, Key=key)
    body = s3_object['Body']

Print PDF directly from JavaScript

Here is a function to print a PDF from an iframe.

You just need to pass the URL of the PDF to the function. It will create an iframe and trigger print once the PDF is load.

Note that the function doesn't destroy the iframe. Instead, it reuses it each time the function is call. It's hard to destroy the iframe because it is needed until the printing is done, and the print method doesn't has callback support (as far as I know).

printPdf = function (url) {
  var iframe = this._printIframe;
  if (!this._printIframe) {
    iframe = this._printIframe = document.createElement('iframe');
    document.body.appendChild(iframe); = 'none';
    iframe.onload = function() {
      setTimeout(function() {
      }, 1);

  iframe.src = url;

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

Here is another one - ? - Unicode U+141E / CANADIAN SYLLABICS GLOTTAL STOP

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

Basically It is used in HeapOverflows or other reversing type Problems i.e. If you want to change a 64 bit ELF to 32 bit ELF and it is showing error while converting.

You can simply run the commands

apt-get install gcc-multilib g++-multilib

which will update your libraries Packages upgraded:

The following additional packages will be installed: g++-8-multilib gcc-8-multilib lib32asan5 lib32atomic1 lib32gcc-8-dev lib32gomp1 lib32itm1 lib32mpx2 lib32quadmath0 lib32stdc++-8-dev lib32ubsan1 libc-dev-bin libc6 libc6-dbg libc6-dev libc6-dev-i386 libc6-dev-x32 libc6-i386 libc6-x32 libx32asan5 libx32atomic1 libx32gcc-8-dev libx32gcc1 libx32gomp1 libx32itm1 libx32quadmath0 libx32stdc++-8-dev libx32stdc++6 libx32ubsan1 Suggested packages: lib32stdc++6-8-dbg libx32stdc++6-8-dbg glibc-doc The following NEW packages will be installed: g++-8-multilib g++-multilib gcc-8-multilib gcc-multilib lib32asan5 lib32atomic1 lib32gcc-8-dev lib32gomp1 lib32itm1 lib32mpx2 lib32quadmath0 lib32stdc++-8-dev lib32ubsan1 libc6-dev-i386 libc6-dev-x32 libc6-x32 libx32asan5 libx32atomic1 libx32gcc-8-dev libx32gcc1 libx32gomp1 libx32itm1 libx32quadmath0 libx32stdc++-8-dev libx32stdc++6 libx32ubsan1

similar to this will be shown to your terminal

How to beautify JSON in Python?

With jsonlint (like xmllint):

aptitude install python-demjson
jsonlint -f foo.json

Python IndentationError: unexpected indent

You can't mix tab and spaces for identation. Best practice is to convert all tabs to spaces.

How to fix this? Well just delete all the spaces/tabs before each line and convert them uniformly either to tabs OR spaces, but don't mix. Best solution: enable in your Editor the option to convert automagically any tabs to spaces.

Also be aware that your actual problem may lie in the lines before this block, and python throws the error here, because of a leading invalid indentation which doesn't match the following identations!