Programs & Examples On #Pixelformat

Android: Unable to add window. Permission denied for this window type

I did manage to finally display a window on the lock screen with the use of TYPE_SYSTEM_OVERLAY instead of TYPE_KEYGUARD_DIALOG. This works as expected and adds the window on the lock screen.

The problem with this is that the window is added on top of everything it possibly can. That is, the window will even appear on top of your keypad/pattern lock in case of secure lock screens. In the case of an unsecured lock screen, it will appear on top of the notification tray if you open it from the lock screen.

For me, that is unacceptable. I hope that this may help anybody else facing this problem.

Unable to add window -- token null is not valid; is your activity running?

You need to pass your activity in the constructor

 PopupWindow popupWindow = new PopupWindow(YourActivity.this)

Creating a system overlay window (always on top)

It uses permission "android.permission.SYSTEM_ALERT_WINDOW" full tutorial on this link :

how to play video from url

Try Exoplayer2

It is highly customisable

    private void initializePlayer() {
         player = ExoPlayerFactory.newSimpleInstance(
             new DefaultRenderersFactory(this),
             new DefaultTrackSelector(), new DefaultLoadControl());


         player.seekTo(currentWindow, playbackPosition);

Uri uri = Uri.parse(getString(R.string.media_url_mp3));
     MediaSource mediaSource = buildMediaSource(uri);
     player.prepare(mediaSource, true, false);

private MediaSource buildMediaSource(Uri uri) {
  return new ExtractorMediaSource.Factory(
      new DefaultHttpDataSourceFactory("exoplayer-codelab")).

public void onStart() {
 if (Util.SDK_INT > 23) {

Check this url for more details

Convert an image to grayscale

"I want a Bitmap d, that is grayscale. I do see a consructor that includes System.Drawing.Imaging.PixelFormat, but I don't understand how to use that."

Here is how to do this

Bitmap grayScaleBP = new 
         System.Drawing.Bitmap(2, 2, System.Drawing.Imaging.PixelFormat.Format16bppGrayScale);

EDIT: To convert to grayscale

             Bitmap c = new Bitmap("fromFile");
             Bitmap d;
             int x, y;

             // Loop through the images pixels to reset color.
             for (x = 0; x < c.Width; x++)
                 for (y = 0; y < c.Height; y++)
                     Color pixelColor = c.GetPixel(x, y);
                     Color newColor = Color.FromArgb(pixelColor.R, 0, 0);
                     c.SetPixel(x, y, newColor); // Now greyscale
            d = c;   // d is grayscale version of c  

Faster Version from switchonthecode follow link for full analysis:

public static Bitmap MakeGrayscale3(Bitmap original)
   //create a blank bitmap the same size as original
   Bitmap newBitmap = new Bitmap(original.Width, original.Height);

   //get a graphics object from the new image
   using(Graphics g = Graphics.FromImage(newBitmap)){

       //create the grayscale ColorMatrix
       ColorMatrix colorMatrix = new ColorMatrix(
          new float[][] 
             new float[] {.3f, .3f, .3f, 0, 0},
             new float[] {.59f, .59f, .59f, 0, 0},
             new float[] {.11f, .11f, .11f, 0, 0},
             new float[] {0, 0, 0, 1, 0},
             new float[] {0, 0, 0, 0, 1}

       //create some image attributes
       using(ImageAttributes attributes = new ImageAttributes()){

           //set the color matrix attribute

           //draw the original image on the new image
           //using the grayscale color matrix
           g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
                       0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);
   return newBitmap;

WPF Image Dynamically changing Image source during runtime

I can think of two things:

First, try loading the image with:

string strUri2 = String.Format(@"pack://application:,,,/MyAseemby;component/resources/main titles/{0}", CurrenSelection.TitleImage);
imgTitle.Source = new BitmapImage(new Uri(strUri2));

Maybe the problem is with WinForm's image resizing, if the image is stretched set Stretch on the image control to "Uniform" or "UnfirofmToFill".

Second option is that maybe the image is not aligned to the pixel grid, you can read about it on my blog at

Setting WPF image source in code

There's also a simpler way. If the image is loaded as a resource in the XAML, and the code in question is the codebehind for that XAML:

Here's the resource dictionary for a XAML file - the only line you care about is the ImageBrush with the key "PosterBrush" - the rest of the code is just to show context

            <ImageBrush x:Key="PosterBrush" ImageSource="..\Resources\Images\EmptyPoster.jpg" Stretch="UniformToFill"/>


Now, in the code behind, you can just do this

ImageBrush posterBrush = (ImageBrush)Resources["PosterBrush"];

Amazon Linux: apt-get: command not found

Try to install your application by using yum command yum install application_name

ImportError: No module named pandas

I fixed the same problem with the below commands... Type python on your terminal. If you see python version 2.x then run these two commands to install pandas:

sudo python -m pip install wheel


sudo python -m pip install pandas

Else if you see python version 3.x then run these two commands to install pandas:

sudo python3 -m pip install wheel


sudo python3 -m pip install pandas

Good Luck!

how to get a list of dates between two dates in java

java9 features you can calculate like this

public  List<LocalDate> getDatesBetween (
 LocalDate startDate, LocalDate endDate) {

   return startDate.datesUntil(endDate)

Check whether an array is empty

echo "false";

How can I display a messagebox in ASP.NET?

This method works fine for me:

private void alert(string message)
    Response.Write("<script>alert('" + message + "')</script>");


protected void Page_Load(object sender, EventArgs e)
    alert("Hello world!");

And when your page load yo will see something like this:

enter image description here

I'm using .NET Framework 4.5 in Firefox.

What was the strangest coding standard rule that you were forced to follow?

A buddy of mine encountered this rule while working at a government job. The use of ++ (pre or post) was completely banned. The reason: Different compilers might interpret it differently.

Determine direct shared object dependencies of a Linux binary?

You can use readelf to explore the ELF headers. readelf -d will list the direct dependencies as NEEDED sections.

 $ readelf -d elfbin

Dynamic section at offset 0xe30 contains 22 entries:
  Tag        Type                         Name/Value
 0x0000000000000001 (NEEDED)             Shared library: []
 0x0000000000000001 (NEEDED)             Shared library: []
 0x000000000000000c (INIT)               0x400520
 0x000000000000000d (FINI)               0x400758

How do I define a method which takes a lambda as a parameter in Java 8?

Here's roughly how C# handles this problem (but expressed as Java code). Something like this could handle almost all your needs:

import static org.util.function.Functions.*;

public class Test {

    public static void main(String[] args)
        Test.invoke((a, b) -> a + b);       

    public static void invoke(Func2<Integer, Integer, Integer> func)
        System.out.println(func.apply(5, 6));

package org.util.function;

public interface Functions {

    public interface Action {
        public void apply();

    public interface Action1<T1> {
        public void apply(T1 arg1);

    public interface Action2<T1, T2> {
        public void apply(T1 arg1, T2 arg2);

    public interface Action3<T1, T2, T3> {
        public void apply(T1 arg1, T2 arg2, T3 arg3);

    public interface Action4<T1, T2, T3, T4> {
        public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4);

    public interface Action5<T1, T2, T3, T4, T5> {
        public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);

    public interface Action6<T1, T2, T3, T4, T5, T6> {
        public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);

    public interface Action7<T1, T2, T3, T4, T5, T6, T7> {
        public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);

    public interface Action8<T1, T2, T3, T4, T5, T6, T7, T8> {
        public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);

    public interface Func<TResult> {
        public TResult apply();

    public interface Func1<T1, TResult> {
        public TResult apply(T1 arg1);

    public interface Func2<T1, T2, TResult> {
        public TResult apply(T1 arg1, T2 arg2);

    public interface Func3<T1, T2, T3, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3);

    public interface Func4<T1, T2, T3, T4, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4);

    public interface Func5<T1, T2, T3, T4, T5, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);

    public interface Func6<T1, T2, T3, T4, T5, T6, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);

    public interface Func7<T1, T2, T3, T4, T5, T6, T7, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);

    public interface Func8<T1, T2, T3, T4, T5, T6, T7, T8, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);

Java 8 LocalDate Jackson format

As of 2020 and Jackson 2.10.1 there's no need for any special code, it's just a matter of telling Jackson what you want:

ObjectMapper objectMapper = new ObjectMapper();

// Register module that knows how to serialize java.time objects
// Provided by jackson-datatype-jsr310
objectMapper.registerModule(new JavaTimeModule());

// Ask Jackson to serialize dates as String (ISO-8601 by default)

This has already been mentioned in this answer, I'm adding a unit test verifying the functionality:

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.Data;
import org.junit.jupiter.api.Test;

import java.time.LocalDate;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class LocalDateSerializationTest {

    static class TestBean {
        // Accept default ISO-8601 format
        LocalDate birthDate;
        // Use custom format
        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
        LocalDate birthDateWithCustomFormat;

    void serializeDeserializeTest() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();

        // Register module that knows how to serialize java.time objects
        objectMapper.registerModule(new JavaTimeModule());

        // Ask Jackson to serialize dates as String (ISO-8601 by default)

        // The JSON string after serialization
        String json = "{\"birthDate\":\"2000-01-02\",\"birthDateWithCustomFormat\":\"03/02/2001\"}";

        // The object after deserialization
        TestBean object = new TestBean();
        object.setBirthDate(LocalDate.of(2000, 1, 2));
        object.setBirthDateWithCustomFormat(LocalDate.of(2001, 2, 3));

        // Assert serialization
        assertEquals(json, objectMapper.writeValueAsString(object));

        // Assert deserialization
        assertEquals(object, objectMapper.readValue(json, TestBean.class));

TestBean uses Lombok to generate the boilerplate for the bean.

How to check if a file contains a specific string using Bash

I done this, seems to work fine

if grep $SearchTerm $FileToSearch; then
   echo "$SearchTerm found OK"
   echo "$SearchTerm not found"

"This project is incompatible with the current version of Visual Studio"

If the message

This project is incompatible with the current version of Visual Studio

is due to an attempt to open a project targeting .Net 4.5, then the "solution" or workaround is to edit the .csproj file and change the TargetFrameworkVersion from "v4.5" to "v4.0". That at least allows the project to be loaded, although it may result in compiler errors if the program is dependent on 4.5 features.

How to enable GZIP compression in IIS 7.5

GZip Compression can be enabled directly through IIS.

First, open up IIS,

go to the website you are hoping to tweak and hit the Compression page. If Gzip is not installed, you will see something like the following:


“The dynamic content compression module is not installed.” We should fix this. So we go to the “Turn Windows features on or off” and select “Dynamic Content Compression” and click the OK button.

Now if we go back to IIS, we should see that the compression page has changed. At this point we need to make sure the dynamic compression checkbox is checked and we’re good to go. Compression is enabled and our dynamic content will be Gzipped.

Testing - Check if GZIP Compression is Enabled

To test whether compression is working or not, use the developer tools in Chrome or Firebug for Firefox and ensure the HTTP response header is set:

Content-Encoding: gzip

Get current cursor position in a textbox

Here's one possible method.

function isMouseInBox(e) {
  var textbox = document.getElementById('textbox');

  // Box position & sizes
  var boxX = textbox.offsetLeft;
  var boxY = textbox.offsetTop;
  var boxWidth = textbox.offsetWidth;
  var boxHeight = textbox.offsetHeight;

  // Mouse position comes from the 'mousemove' event
  var mouseX = e.pageX;
  var mouseY = e.pageY;
  if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
    if(mouseY>=boxY && mouseY<=boxY+boxHeight){
       // Mouse is in the box
       return true;

document.addEventListener('mousemove', function(e){

Python creating a dictionary of lists

You can use setdefault:

d = dict()
a = ['1', '2']
for i in a:
    for j in range(int(i), int(i) + 2): 
        d.setdefault(j, []).append(i)

print d  # prints {1: ['1'], 2: ['1', '2'], 3: ['2']}

The rather oddly-named setdefault function says "Get the value with this key, or if that key isn't there, add this value and then return it."

As others have rightly pointed out, defaultdict is a better and more modern choice. setdefault is still useful in older versions of Python (prior to 2.5).

Could not instantiate mail function. Why this error occurring

Check with your host to see if they have any hourly limits to emails being sent.

Android WebView not loading URL

Did you added the internet permission in your manifest file ? if not add the following line.

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

hope this will help you.


Use the below lines.

    public class WebViewDemo extends Activity {

        private WebView webView;

        Activity activity ;
        private ProgressDialog progDailog; 

        public void onCreate(Bundle savedInstanceState) {

            activity = this;

            progDailog =, "Loading","Please wait...", true);

           webView = (WebView) findViewById(;

            webView.setWebViewClient(new WebViewClient(){

                public boolean shouldOverrideUrlLoading(WebView view, String url) {

                    return true;                
                public void onPageFinished(WebView view, final String url) {



How to print a number with commas as thousands separators in JavaScript

Below are two different browser APIs that can transform Numbers into structured Strings. Keep in mind that not all users' machines have a locale that uses commas in numbers. To enforce commas to the output, any "western" locale may be used, such as en-US

var number = 1234567890; // Example number to be converted

?? Mind that javascript has a maximum integer value of 9007199254740991


// default behaviour on a machine with a local that uses commas for numbers
number.toLocaleString(); // "1,234,567,890"

// With custom settings, forcing a "US" locale to guarantee commas in output
var number2 = 1234.56789; // floating point example
number2.toLocaleString('en-US', {maximumFractionDigits:2}) // "1,234.57"


var nf = new Intl.NumberFormat();
nf.format(number); // "1,234,567,890"

From what I checked (Firefox at least) they are both more or less same regarding performance.

Live demo:

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

Although this is an old thread, I got this error as well and the solution that worked for me is not mentioned here.

Simply put, in my case the webcam was still in use on the background, as I saw the LED light being on. I have not yet been able to reproduce the issue, so I'm not sure a simple cv2.VideoCapture(0).release() would have solved it. I'll edit this post if and when I have found it out.

For me a restart of my PC solved the issue, without changing anything to the code.

Passing arrays as parameters in bash

Requirement: Function to find a string in an array.
This is a slight simplification of DevSolar's solution in that it uses the arguments passed rather than copying them.

myarray=('foobar' 'foxbat')

function isInArray() {
  local item=$1
  for one in $@; do
    if [ $one = $item ]; then
      return 0   # found
  return 1       # not found

if isInArray $var ${myarray[@]}; then
  echo "$var found in array"
  echo "$var not found in array"

Change bootstrap navbar background color and font color

Most likely these classes are already defined by Bootstrap, make sure that your CSS file that you want to override the classes with is called AFTER the Bootstrap CSS.

<link rel="stylesheet" href="css/bootstrap.css" /> <!-- Call Bootstrap first -->
<link rel="stylesheet" href="css/bootstrap-override.css" /> <!-- Call override CSS second -->

Otherwise, you can put !important at the end of your CSS like this: color:#ffffff!important; but I would advise against using !important at all costs.

Open Popup window using javascript

Change the window name in your two different calls:

function popitup(url,windowName) {,windowName,'height=200,width=150');
       if (window.focus) {newwindow.focus()}
       return false;

windowName must be unique when you open a new window with same url otherwise the same window will be refreshed.

Can you have multiple $(document).ready(function(){ ... }); sections?

You can use multiple. But you can also use multiple functions inside one document.ready as well:

$(document).ready(function() {
    // Jquery
    $('.test').each(function() {

    // Reqular JS
    function test(word) {

Android and Facebook share intent

Seems in version 4.0.0 of Facebook so many things has changed. This is my code which is working fine. Hope it helps you.

     * Facebook does not support sharing content without using their SDK however
     * it is possible to share URL
     * @param content
     * @param url
    private void shareOnFacebook(String content, String url)
            // TODO: This part does not work properly based on my test
            Intent fbIntent = new Intent(Intent.ACTION_SEND);
            fbIntent.putExtra(Intent.EXTRA_TEXT, content);
            fbIntent.putExtra(Intent.EXTRA_STREAM, url);
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            fbIntent.setComponent(new ComponentName("com.facebook.katana",

        catch (Exception e)
            // User doesn't have Facebook app installed. Try sharing through browser.

        // If we failed (not native FB app installed), try share through SEND
        String sharerUrl = "" + url;
        SupportUtils.doShowUri(this.getActivity(), sharerUrl);

How to get character for a given ascii value

Do you mean "A" (a string) or 'A' (a char)?

int unicode = 65;
char character = (char) unicode;
string text = character.ToString();

Note that I've referred to Unicode rather than ASCII as that's C#'s native character encoding; essentially each char is a UTF-16 code point.

How to change owner of PostgreSql database?


See the Postgresql manual's entry on this for more details.

How does the keyword "use" work in PHP and can I import classes with it?

I agree with Green, Symfony needs namespace, so why not use them ?

This is how an example controller class starts:

namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class WelcomeController extends Controller { ... }

How to pass variable as a parameter in Execute SQL Task SSIS?

In your Execute SQL Task, make sure SQLSourceType is set to Direct Input, then your SQL Statement is the name of the stored proc, with questionmarks for each paramter of the proc, like so:

enter image description here

Click the parameter mapping in the left column and add each paramter from your stored proc and map it to your SSIS variable:

enter image description here

Now when this task runs it will pass the SSIS variables to the stored proc.

Using async/await with a forEach loop

With ES2018, you are able to greatly simplify all of the above answers to:

async function printFiles () {
  const files = await getFilePaths()

  for await (const contents of => fs.readFile(file, 'utf8'))) {

See spec: proposal-async-iteration

2018-09-10: This answer has been getting a lot attention recently, please see Axel Rauschmayer's blog post for further information about asynchronous iteration: ES2018: asynchronous iteration

PHP PDO with foreach and fetch

This is because you are reading a cursor, not an array. This means that you are reading sequentially through the results and when you get to the end you would need to reset the cursor to the beginning of the results to read them again.

If you did want to read over the results multiple times, you could use fetchAll to read the results into a true array and then it would work as you are expecting.

Android lollipop change navigation bar color

Here is how to do it programatically:

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {                

Using Compat library:

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.primary));

Here is how to do it with xml in the values-v21/style.xml folder:

<item name="android:navigationBarColor">@color/your_color</item>

How to beautifully update a JPA entity in Spring Data?

Even better then @Tanjim Rahman answer you can using Spring Data JPA use the method T getOne(ID id)

Customer customerToUpdate = customerRepository.getOne(id);

Is's better because getOne(ID id) gets you only a reference (proxy) object and does not fetch it from the DB. On this reference you can set what you want and on save() it will do just an SQL UPDATE statement like you expect it. In comparsion when you call find() like in @Tanjim Rahmans answer spring data JPA will do an SQL SELECT to physically fetch the entity from the DB, which you dont need, when you are just updating.

Change first commit of project with Git?

If you want to modify only the first commit, you may try git rebase and amend the commit, which is similar to this post: How to modify a specified commit in git?

And if you want to modify all the commits which contain the raw email, filter-branch is the best choice. There is an example of how to change email address globally on the book Pro Git, and you may find this link useful

Include an SVG (hosted on GitHub) in MarkDown

I have a working example with an img-tag, but your images won't display. The difference I see is the content-type.

I checked the github image from your post (the google doc images don't load at all because of connection failures). The image from github is delivered as content-type: text/plain, which won't get rendered as an image by your browser.

The correct content-type value for svg is image/svg+xml. So you have to make sure that svg files set the correct mime type, but that's a server issue.

Try it with and don't forget to specify width and height in the tag.

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

In order to handle arrays with the $resource service, it's suggested that you use the query method. As you can see below, the query method is built to handle arrays.

    { 'get':    {method:'GET'},
      'save':   {method:'POST'},
      'query':  {method:'GET', isArray:true},
      'remove': {method:'DELETE'},
      'delete': {method:'DELETE'} 

User $resource("apiUrl").query();

Reference to a non-shared member requires an object reference occurs when calling public sub

You either have to make the method Shared or use an instance of the class General:

Dim gen = New General()



Public Shared Sub updateDynamics(dynID As Int32)
    ' ... '
End Sub


Drop-down box dependent on the option selected in another drop-down box

I hope the following code will help or solve your problem or you think not that understandable visit


<div class="frmDronpDown">
<div class="row">
    <select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
    <option value="">Select Country</option>
    foreach($results as $country) {
    <option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option>
<div class="row">
    <select name="state" id="state-list" class="demoInputBox">
    <option value="">Select State</option>


<script> function getState(val) { $.ajax({
type: "POST",
url: "get_state.php",
success: function(data){
});} </script>


<?php require_once("dbcontroller.php"); $db_handle = new DBController();if(!empty($_POST["country_id"])) {
$query ="SELECT * FROM states WHERE countryID = '" . $_POST["country_id"] . "'";
$results = $db_handle->runQuery($query); ?> <option value="">Select State</option><?php foreach($results as $state) { ?> <option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option><?php } } ?>

Split string with JavaScript

var wrapper = $(document.body);

strings = [
    "19 51 2.108997",
    "20 47 2.1089"

$.each(strings, function(key, value) {
    var tmp = value.split(" ");
        tmp[0] + " " + tmp[1],
    ], function(key, value) {
        $("<span>" + value + "</span>").appendTo(wrapper);

Java Delegates?

I know this post is old, but Java 8 has added lambdas, and the concept of a functional interface, which is any interface with only one method. Together these offer similar functionality to C# delegates. See here for more info, or just google Java Lambdas.

How to turn off INFO logging in Spark?

You can use setLogLevel

val spark = SparkSession
      .config("spark.master", "local[1]")


Find the paths between two given nodes?

If you want all the paths, use recursion.

Using an adjacency list, preferably, create a function f() that attempts to fill in a current list of visited vertices. Like so:

void allPaths(vector<int> previous, int current, int destination)

    if (current == destination)
        //output all elements of previous, and return

    for (int i = 0; i < neighbors[current].size(); i++)
        allPaths(previous, neighbors[current][i], destination);

int main()
    allPaths(vector<int>(), start, end);

Due to the fact that the vector is passed by value (and thus any changes made further down in the recursive procedure aren't permanent), all possible combinations are enumerated.

You can gain a bit of efficiency by passing the previous vector by reference (and thus not needing to copy the vector over and over again) but you'll have to make sure that things get popped_back() manually.

One more thing: if the graph has cycles, this won't work. (I assume in this case you'll want to find all simple paths, then) Before adding something into the previous vector, first check if it's already in there.

If you want all shortest paths, use Konrad's suggestion with this algorithm.

PHP - Check if the page run on Mobile or Desktop browser

There are many great open source projects that make detection a lot easier. To name two:

  1. PHP mobile detect
  2. WURFL

AngularJS : Initialize service with asynchronous data

You can use JSONP to asynchronously load service data. The JSONP request will be made during the initial page load and the results will be available before your application starts. This way you won't have to bloat your routing with redundant resolves.

You html would look like this:

<script src=""></script>

function MyService {
  this.getData = function(){
MyService.setData = function(data) { = data;

.service('MyService', MyService)

<script src="/some_data.php?jsonp=MyService.setData"></script>

Round to 5 (or other number) in Python

def round_up_to_base(x, base=10):
    return x + (base - x) % base

def round_down_to_base(x, base=10):
    return x - (x % base)

which gives

for base=5:

>>> [i for i in range(20)]
[0, 1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [round_down_to_base(x=i, base=5) for i in range(20)]
[0, 0,  0,  0,  0,  5,  5,  5,  5,  5,  10, 10, 10, 10, 10, 15, 15, 15, 15, 15]

>>> [round_up_to_base(x=i, base=5) for i in range(20)]
[0, 5,  5,  5,  5,  5,  10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20]

for base=10:

>>> [i for i in range(20)]
[0, 1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [round_down_to_base(x=i, base=10) for i in range(20)]
[0, 0,  0,  0,  0,  0,  0,  0,  0,  0,  10, 10, 10, 10, 10, 10, 10, 10, 10, 10]

>>> [round_up_to_base(x=i, base=10) for i in range(20)]
[0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 20, 20, 20, 20, 20, 20, 20, 20, 20]

tested in Python 3.7.9

How to move screen without moving cursor in Vim?

To leave the cursor in the same column when you use Ctrl+D, Ctrl+F, Ctrl+B, Ctrl+U, G, H, M, L, gg

you should define the following option:

:set nostartofline

Delete all files in directory (but not directory) - one liner solution

For deleting all files from directory say "C:\Example"

File file = new File("C:\\Example");      
String[] myFiles;    
if (file.isDirectory()) {
    myFiles = file.list();
    for (int i = 0; i < myFiles.length; i++) {
        File myFile = new File(file, myFiles[i]); 

SystemError: Parent module '' not loaded, cannot perform relative import

if you just run the under the app, just import like

from mymodule import myclass

if you want to call on other folder, use:

from .mymodule import myclass

for example:

+-- app
¦   +--
¦   +--
¦   +--

from .mymodule import myclass

from app import main

So I think the main question of you is how to call app.main.

using lodash .groupBy. how to add your own keys for grouped output?

Isn't it this simple?

var result = _(data)
            .groupBy(x => x.color)
            .map((value, key) => ({color: key, users: value}))

Laravel Eloquent compare date from datetime field

Have you considered using:

where('date', '<', '2014-08-11')

You should avoid using the DATE() function on indexed columns in MySQL, as this prevents the engine from using the index.


As there seems to be some disagreement about the importance of DATE() and indexes, I have created a fiddle that demonstrates the difference, see POSSIBLE KEYS.

How to make String.Contains case insensitive?

You can use:

if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {

This works with any .NET version.

How can I get the Windows last reboot reason

Take a look at the Event Log API. Case a) (bluescreen, user cut the power cord or system hang) causes a note ('system did not shutdown correctly' or something like that) to be left in the 'System' event log the next time the system is rebooted properly. You should be able to access it programmatically using the above API (honestly, I've never used it but it should work).

Access restriction: Is not accessible due to restriction on required library ..\jre\lib\rt.jar

Excellent answer already provide onsite here.

See the summary below:

  1. Go to the Build Path settings in the project properties.
  2. Remove the JRE System Library
  3. Add it back; Select "Add Library" and select the JRE System Library. The default worked for me.

What is the best alternative IDE to Visual Studio

Try out this one: "Pao" at . It's still in development and not up to production use but it's quite unique in features. Basically, all the language constructs, such as assemblies, types, members, statements, expressions are treated as objects and are associated with rich operation options. You can enjoy features usually seen in graphical editors, such as multiple selection, multiple copy-paste, tagging, batch operation and very powerful search capability. It takes some getting used to but eventually might increase productivity. Right now, it only supports form applications though.

Run a php app using tomcat?

Caucho Quercus can run PHP code on the jvm.

PHP: Call to undefined function: simplexml_load_string()

Make sure that you have php-xml module installed and enabled in php.ini.

You can also change response format to json which is easier to handle. In that case you have to only add &format=json to url query string.

$rest_url = "".urlencode($source_url);

And then use json_decode() to retrieve data in your script:

$result = json_decode($content, true);
$fb_like_count = $result['like_count'];

Using sed and grep/egrep to search and replace

My use case was I wanted to replace foo:/Drive_Letter with foo:/bar/baz/xyz In my case I was able to do it with the following code. I was in the same directory location where there were bulk of files.

find . -name "*.library" -print0 | xargs -0 sed -i '' -e 's/foo:\/Drive_Letter:/foo:\/bar\/baz\/xyz/g'

hope that helped.

UPDATE s|foo:/Drive_letter:|foo:/ba/baz/xyz|g

Using crontab to execute script every minute and another every 24 hours

This is the format of /etc/crontab:

# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

I recommend copy & pasting that into the top of your crontab file so that you always have the reference handy. RedHat systems are setup that way by default.

To run something every minute:

* * * * * username /var/www/html/a.php

To run something at midnight of every day:

0 0 * * * username /var/www/html/reset.php

You can either include /usr/bin/php in the command to run, or you can make the php scripts directly executable:

chmod +x file.php

Start your php file with a shebang so that your shell knows which interpreter to use:

// your code here

How to create a XML object from String in Java?

If you can create a string xml you can easily transform it to the xml document object e.g. -

String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";  

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
DocumentBuilder builder;  
try {  
    builder = factory.newDocumentBuilder();  
    Document document = builder.parse(new InputSource(new StringReader(xmlString)));  
} catch (Exception e) {  

You can use the document object and xml parsing libraries or xpath to get back the ip address.

Update value of a nested dictionary of varying depth

@Alex's answer is good, but doesn't work when replacing an element such as an integer with a dictionary, such as update({'foo':0},{'foo':{'bar':1}}). This update addresses it:

import collections
def update(d, u):
    for k, v in u.iteritems():
        if isinstance(d, collections.Mapping):
            if isinstance(v, collections.Mapping):
                r = update(d.get(k, {}), v)
                d[k] = r
                d[k] = u[k]
            d = {k: u[k]}
    return d

update({'k1': 1}, {'k1': {'k2': {'k3': 3}}})

TypeError: worker() takes 0 positional arguments but 1 was given

I get this error whenever I mistakenly create a Python class using def instead of class:

def Foo():
    def __init__(self, x):
        self.x = x
# python thinks we're calling a function Foo which takes 0 args   
a = Foo(x) 

TypeError: Foo() takes 0 positional arguments but 1 was given


How to iterate through two lists in parallel?

You can bundle the nth elements into a tuple or list using comprehension, then pass them out with a generator function.

def iterate_multi(*lists):
    for i in range(min(map(len,lists))):
        yield tuple(l[i] for l in lists)

for l1, l2, l3 in iterate_multi([1,2,3],[4,5,6],[7,8,9]):

Extract digits from a string in Java


This will ignore the decimal points.

eg: if you have an input as 445.3kg the output will be 445.3.

Change input value onclick button - pure javascript or jQuery

This will work fine for you

   <!DOCTYPE html>
    <script src=""></script>

    function myfun(){

        var data=$("#select").val();
    <p>id <input type="text" name="user" id="disp"></p>
    <select id="select" onclick="myfun()">
    <option name="1"value="one">1</option>
    <option name="2"value="two">2</option>
    <option name="3"value="three"></option>

Is it safe to delete the "InetPub" folder?

IIS will create it again AFAIK.

What's the difference between unit tests and integration tests?

A unit test is a test written by the programmer to verify that a relatively small piece of code is doing what it is intended to do. They are narrow in scope, they should be easy to write and execute, and their effectiveness depends on what the programmer considers to be useful. The tests are intended for the use of the programmer, they are not directly useful to anybody else, though, if they do their job, testers and users downstream should benefit from seeing fewer bugs.

Part of being a unit test is the implication that things outside the code under test are mocked or stubbed out. Unit tests shouldn't have dependencies on outside systems. They test internal consistency as opposed to proving that they play nicely with some outside system.

An integration test is done to demonstrate that different pieces of the system work together. Integration tests can cover whole applications, and they require much more effort to put together. They usually require resources like database instances and hardware to be allocated for them. The integration tests do a more convincing job of demonstrating the system works (especially to non-programmers) than a set of unit tests can, at least to the extent the integration test environment resembles production.

Actually "integration test" gets used for a wide variety of things, from full-on system tests against an environment made to resemble production to any test that uses a resource (like a database or queue) that isn't mocked out. At the lower end of the spectrum an integration test could be a junit test where a repository is exercised against an in-memory database, toward the upper end it could be a system test verifying applications can exchange messages.

Python loop counter in a for loop

Use enumerate() like so:

def draw_menu(options, selected_index):
    for counter, option in enumerate(options):
        if counter == selected_index:
            print " [*] %s" % option
            print " [ ] %s" % option    

options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)

Note: You can optionally put parenthesis around counter, option, like (counter, option), if you want, but they're extraneous and not normally included.

How to convert XML to JSON in Python?

One possibility would be to use Objectify or ElementTree from the lxml module. An older version ElementTree is also available in the python xml.etree module as well. Either of these will get your xml converted to Python objects which you can then use simplejson to serialize the object to JSON.

While this may seem like a painful intermediate step, it starts making more sense when you're dealing with both XML and normal Python objects.

Difference between <input type='submit' /> and <button type='submit'>text</button>

With <button>, you can use img tags, etc. where text is

<button type='submit'> text -- can be img etc.  </button>

with <input> type, you are limited to text

Array functions in jQuery

Look into the jQuery functions .grep() and .map()

How can I load webpage content into a div on page load?

You can't inject content from another site (domain) using AJAX. The reason an iFrame is suited for these kinds of things is that you can specify the source to be from another domain.

How do I express "if value is not empty" in the VBA language?

It depends on what you want to test:

  • for a string, you can use If strName = vbNullString or IF strName = "" or Len(strName) = 0 (last one being supposedly faster)
  • for an object, you can use If myObject is Nothing
  • for a recordset field, you could use If isnull(rs!myField)
  • for an Excel cell, you could use If range("B3") = "" or IsEmpty(myRange)

Extended discussion available here (for Access, but most of it works for Excel as well).

How to get the unique ID of an object which overrides hashCode()?

I had the same issue and was not satisfied with any of the answers so far since none of them guaranteed unique IDs.

I too wanted to print object IDs for debugging purposed. I knew there must be some way to do it, because in the Eclipse debugger, it specifies unique IDs for each object.

I came up with a solution based on the fact that the "==" operator for objects only returns true if the two objects are actually the same instance.

import java.util.HashMap;
import java.util.Map;

 *  Utility for assigning a unique ID to objects and fetching objects given
 *  a specified ID
public class ObjectIDBank {

    /**Singleton instance*/
    private static ObjectIDBank instance;

    /**Counting value to ensure unique incrementing IDs*/
    private long nextId = 1;

    /** Map from ObjectEntry to the objects corresponding ID*/
    private Map<ObjectEntry, Long> ids = new HashMap<ObjectEntry, Long>();

    /** Map from assigned IDs to their corresponding objects */
    private Map<Long, Object> objects = new HashMap<Long, Object>();

    /**Private constructor to ensure it is only instantiated by the singleton pattern*/
    private ObjectIDBank(){}

    /**Fetches the singleton instance of ObjectIDBank */
    public static ObjectIDBank instance() {
        if(instance == null)
            instance = new ObjectIDBank();

        return instance;

    /** Fetches a unique ID for the specified object. If this method is called multiple
     * times with the same object, it is guaranteed to return the same value. It is also guaranteed
     * to never return the same value for different object instances (until we run out of IDs that can
     * be represented by a long of course)
     * @param obj The object instance for which we want to fetch an ID
     * @return Non zero unique ID or 0 if obj == null
    public long getId(Object obj) {

        if(obj == null)
            return 0;

        ObjectEntry objEntry = new ObjectEntry(obj);

        if(!ids.containsKey(objEntry)) {
            ids.put(objEntry, nextId);
            objects.put(nextId++, obj);

        return ids.get(objEntry);

     * Fetches the object that has been assigned the specified ID, or null if no object is
     * assigned the given id
     * @param id Id of the object
     * @return The corresponding object or null
    public Object getObject(long id) {
        return objects.get(id);

     * Wrapper around an Object used as the key for the ids map. The wrapper is needed to
     * ensure that the equals method only returns true if the two objects are the same instance
     * and to ensure that the hash code is always the same for the same instance.
    private class ObjectEntry {
        private Object obj;

        /** Instantiates an ObjectEntry wrapper around the specified object*/
        public ObjectEntry(Object obj) {
            this.obj = obj;

        /** Returns true if and only if the objects contained in this wrapper and the other
         * wrapper are the exact same object (same instance, not just equivalent)*/
        public boolean equals(Object other) {
            return obj == ((ObjectEntry)other).obj;

         * Returns the contained object's identityHashCode. Note that identityHashCode values
         * are not guaranteed to be unique from object to object, but the hash code is guaranteed to
         * not change over time for a given instance of an Object.
        public int hashCode() {
            return System.identityHashCode(obj);

I believe that this should ensure unique IDs throughout the lifetime of the program. Note, however, that you probably don't want to use this in a production application because it maintains references to all of the objects for which you generate IDs. This means that any objects for which you create an ID will never be garbage collected.

Since I'm using this for debug purposes, I'm not too concerned with the memory being freed.

You could modify this to allow clearing Objects or removing individual objects if freeing memory is a concern.

How can I print using JQuery

function printResult() {
    var DocumentContainer = document.getElementById('your_div_id');
    var WindowObject ='', "PrintWindow", "width=750,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes");

What is a semaphore?

A semaphore is an object containing a natural number (i.e. a integer greater or equal to zero) on which two modifying operations are defined. One operation, V, adds 1 to the natural. The other operation, P, decreases the natural number by 1. Both activities are atomic (i.e. no other operation can be executed at the same time as a V or a P).

Because the natural number 0 cannot be decreased, calling P on a semaphore containing a 0 will block the execution of the calling process(/thread) until some moment at which the number is no longer 0 and P can be successfully (and atomically) executed.

As mentioned in other answers, semaphores can be used to restrict access to a certain resource to a maximum (but variable) number of processes.

Importing a function from a class in another file?


FILENAME is w/o the suffix

/exclude in xcopy just for a file type

In my case I had to start a list of exclude extensions from the second line because xcopy ignored the first line.

How to use particular CSS styles based on screen size / device

Use @media queries. They serve this exact purpose. Here's an example how they work:

@media (max-width: 800px) {
  /* CSS that should be displayed if width is equal to or less than 800px goes here */

This would work only on devices whose width is equal to or less than 800px.

Read up more about media queries on the Mozilla Developer Network.

convert epoch time to date

EDIT: Okay, so you don't want your local time (which isn't Australia) to contribute to the result, but instead the Australian time zone. Your existing code should be absolutely fine then, although Sydney is currently UTC+11, not UTC+10.. Short but complete test app:

import java.util.*;
import java.text.*;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        Date date = new Date(1318386508000L);
        DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        String formatted = format.format(date);
        formatted = format.format(date);


12/10/2011 02:28:28
12/10/2011 13:28:28

I would also suggest you start using Joda Time which is simply a much nicer date/time API...

EDIT: Note that if your system doesn't know about the Australia/Sydney time zone, it would show UTC. For example, if I change the code about to use TimeZone.getTimeZone("blah/blah") it will show the UTC value twice. I suggest you print TimeZone.getTimeZone("Australia/Sydney").getDisplayName() and see what it says... and check your code for typos too :)

Solving "adb server version doesn't match this client" error

What worked for me:

  1. adb kill-server
  2. Close all chrome://inspect/#devices windows/tabs
  3. adb start-server
  4. adb devices

How can I apply a border only inside a table?

Works for any combination of tbody/thead/tfoot and td/th

table.inner-border {_x000D_
    border-collapse: collapse;_x000D_
    border-spacing: 0;_x000D_
table.inner-border > thead > tr > th,_x000D_
table.inner-border > thead > tr > td,_x000D_
table.inner-border > tbody > tr > th,_x000D_
table.inner-border > tbody > tr > td,_x000D_
table.inner-border > tfoot > tr > th,_x000D_
table.inner-border > tfoot > tr > td {_x000D_
    border-bottom: 1px solid black;_x000D_
    border-right: 1px solid black;_x000D_
table.inner-border > thead > tr > :last-child,_x000D_
table.inner-border > tbody > tr > :last-child,_x000D_
table.inner-border > tfoot > tr > :last-child {_x000D_
    border-right: 0;_x000D_
table.inner-border > :last-child > tr:last-child > td,_x000D_
table.inner-border > :last-child > tr:last-child > th {_x000D_
    border-bottom: 0;_x000D_
<table class="inner-border">_x000D_

Arrays.fill with multidimensional array in Java

In simple words java donot provide such an API. You need to iterate through loop and using fill method you can fill 2D array with one loop.

      int row = 5;
      int col = 6;
      int cache[][]=new int[row][col];
      for(int i=0;i<=row;i++){

Calculate cosine similarity given 2 sentence strings

Try this. Download the file 'numberbatch-en-17.06.txt' from and extract it. The function 'get_sentence_vector' uses a simple sum of word vectors. However it can be improved by using weighted sum where weights are proportional to Tf-Idf of each word.

import math
import numpy as np

std_embeddings_index = {}
with open('path/to/numberbatch-en-17.06.txt') as f:
    for line in f:
        values = line.split(' ')
        word = values[0]
        embedding = np.asarray(values[1:], dtype='float32')
        std_embeddings_index[word] = embedding

def cosineValue(v1,v2):
    "compute cosine similarity of v1 to v2: (v1 dot v2)/{||v1||*||v2||)"
    sumxx, sumxy, sumyy = 0, 0, 0
    for i in range(len(v1)):
        x = v1[i]; y = v2[i]
        sumxx += x*x
        sumyy += y*y
        sumxy += x*y
    return sumxy/math.sqrt(sumxx*sumyy)

def get_sentence_vector(sentence, std_embeddings_index = std_embeddings_index ):
    sent_vector = 0
    for word in sentence.lower().split():
        if word not in std_embeddings_index :
            word_vector = np.array(np.random.uniform(-1.0, 1.0, 300))
            std_embeddings_index[word] = word_vector
            word_vector = std_embeddings_index[word]
        sent_vector = sent_vector + word_vector

    return sent_vector

def cosine_sim(sent1, sent2):
    return cosineValue(get_sentence_vector(sent1), get_sentence_vector(sent2))

I did run for the given sentences and found the following results

s1 = "This is a foo bar sentence ."
s2 = "This sentence is similar to a foo bar sentence ."
s3 = "What is this string ? Totally not related to the other two lines ."

print cosine_sim(s1, s2) # Should give high cosine similarity
print cosine_sim(s1, s3) # Shouldn't give high cosine similarity value
print cosine_sim(s2, s3) # Shouldn't give high cosine similarity value


How to use regex in file find

Use -regex not -name, and be aware that the regex matches against what find would print, e.g. "/home/test/test.log" not "test.log"

Average of multiple columns

Select Req_ID, sum(R1+R2+R3+R4+R5)/5 as Average
from Request
Group by Req_ID;

Gnuplot line types

Until version 4.6

The dash type of a linestyle is given by the linetype, which does also select the line color unless you explicitely set an other one with linecolor.

However, the support for dashed lines depends on the selected terminal:

  1. Some terminals don't support dashed lines, like png (uses libgd)
  2. Other terminals, like pngcairo, support dashed lines, but it is disables by default. To enable it, use set termoption dashed, or set terminal pngcairo dashed ....
  3. The exact dash patterns differ between terminals. To see the defined linetype, use the test command:


set terminal pngcairo dashed
set output 'test.png'
set output


enter image description here

whereas, the postscript terminal shows different dash patterns:

set terminal postscript eps color colortext
set output 'test.eps'
set output

enter image description here

Version 5.0

Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:

  • A new dashtype parameter was introduced:

    To get the predefined dash patterns, use e.g.

    plot x dashtype 2

    You can also specify custom dash patterns like

    plot x dashtype (3,5,10,5),\
         2*x dashtype '.-_'
  • The terminal options dashed and solid are ignored. By default all lines are solid. To change them to dashed, use e.g.

    set for [i=1:8] linetype i dashtype i
  • The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic:

enter image description here

How do I get a file extension in PHP?


$path_info = pathinfo('/foo/bar/baz.bill');

echo $path_info['extension']; // "bill"

Adding files to java classpath at runtime

You coud try with the url of the folder/jar where your updated class resides and use it instead of the default classloader when creating a new thread.

How can I return the difference between two lists?

You can use CollectionUtils from Apache Commons Collections 4.0:

new ArrayList<>(CollectionUtils.subtract(a, b))

In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

I found that if the value passed is a string type, it must be followed by 'px' (i.e. 90px), where if the value is an integer, it will append the px automatically. the width and height properties are more forgiving (either type works).

var x = "90";
var y = "120"
$(selector).css( { left: x, top: y } )        //doesn't work
$(selector).css( { left: x + "px", top: y + "px" } )        //does work

x = 90;
y = 120;
$(selector).css( { left: x, top: y } )        //does work

How do I check for vowels in JavaScript?

function isVowel(char)
  if (char.length == 1)
    var vowels = "aeiou";
    var isVowel = vowels.indexOf(char) >= 0 ? true : false;

    return isVowel;

Basically it checks for the index of the character in the string of vowels. If it is a consonant, and not in the string, indexOf will return -1.

How would one write object-oriented code in C?

You can fake it using function pointers, and in fact, I think it is theoretically possible to compile C++ programs into C.

However, it rarely makes sense to force a paradigm on a language rather than to pick a language that uses a paradigm.

How to set text color to a text view programmatically

TextView tt;
int color = Integer.parseInt("bdbdbd", 16)+0xFF000000;


tt.setBackgroundColor(Integer.parseInt("d4d446", 16)+0xFF000000);




Java/Android String to Color conversion

PL/SQL, how to escape single quote in a string?

Here's a blog post that should help with escaping ticks in strings.

Here's the simplest method from said post:

The most simple and most used way is to use a single quotation mark with two single >quotation marks in both sides.

SELECT 'test single quote''' from dual;

The output of the above statement would be:

test single quote'

Simply stating you require an additional single quote character to print a single quote >character. That is if you put two single quote characters Oracle will print one. The first >one acts like an escape character.

This is the simplest way to print single quotation marks in Oracle. But it will get >complex when you have to print a set of quotation marks instead of just one. In this >situation the following method works fine. But it requires some more typing labour.

How do you specify the Java compiler version in a pom.xml file?

I faced same issue in eclipse neon simple maven java project

But I add below details inside pom.xml file


After right click on project > maven > update project (checked force update)

Its resolve me to display error on project

Hope it's will helpful


Why does the program give "illegal start of type" error?

You have a misplaced closing brace before the return statement.

How to concatenate two numbers in javascript?

I'd prefer the concat way :

const numVar1 = 5;
const numVar2 = 6;
const value = "".concat(numVar1, numVar2);
// or directly with values
const value2 = "".concat(5, 6);

You can also use an array which can help in some use cases :

const value3 = [5, 6, numVar1].join('');

jquery change class name

I think he wants to replace a class name.

Something like this would work:



_csv.Error: field larger than field limit (131072)

Find the cqlshrc file usually placed in .cassandra directory.

In that file append,

field_size_limit = 1000000000

How can I use PHP to dynamically publish an ical file to be read by Google Calendar?

There is an excellent eluceo/ical package that allows you to easily create ics files.

Here is an example usage from docs:

// 1. Create new calendar
$vCalendar = new \Eluceo\iCal\Component\Calendar('');

// 2. Create an event
$vEvent = new \Eluceo\iCal\Component\Event();
$vEvent->setDtStart(new \DateTime('2012-12-24'));
$vEvent->setDtEnd(new \DateTime('2012-12-24'));

// Adding Timezone (optional)

// 3. Add event to calendar

// 4. Set headers
header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename="cal.ics"');

// 5. Output
echo $vCalendar->render();


In my humble experience with postgres 9.6, cascade delete doesn't work in practice for tables that grow above a trivial size.

  • Even worse, while the delete cascade is going on, the tables involved are locked so those tables (and potentially your whole database) is unusable.
  • Still worse, it's hard to get postgres to tell you what it's doing during the delete cascade. If it's taking a long time, which table or tables is making it slow? Perhaps it's somewhere in the pg_stats information? It's hard to tell.

How to make a div have a fixed size?

Thats the natural behavior of the buttons. You could try putting a max-width/max-height on the parent container, but I'm not sure if that would do it.

max-width:something px;
max-height:something px;

The other option would be to use the devlopr tools and see if you can remove the natural padding.

padding: 0;

How to read request body in an core webapi controller?

This is a bit of an old thread, but since I got here, I figured I'd post my findings so that they might help others.

First, I had the same issue, where I wanted to get the Request.Body and do something with that (logging/auditing). But otherwise I wanted the endpoint to look the same.

So, it seemed like the EnableBuffering() call might do the trick. Then you can do a Seek(0,xxx) on the body and re-read the contents, etc.

However, this led to my next issue. I'd get "Synchornous operations are disallowed" exceptions when accessing the endpoint. So, the workaround there is to set the property AllowSynchronousIO = true, in the options. There are a number of ways to do accomplish this (but not important to detail here..)

THEN, the next issue is that when I go to read the Request.Body it has already been disposed. Ugh. So, what gives?

I am using the Newtonsoft.JSON as my [FromBody] parser in the endpiont call. That is what is responsible for the synchronous reads and it also closes the stream when it's done. Solution? Read the stream before it get's to the JSON parsing? Sure, that works and I ended up with this:

 /// <summary>
/// quick and dirty middleware that enables buffering the request body
/// </summary>
/// <remarks>
/// this allows us to re-read the request body's inputstream so that we can capture the original request as is
/// </remarks>
public class ReadRequestBodyIntoItemsAttribute : AuthorizeAttribute, IAuthorizationFilter
    public void OnAuthorization(AuthorizationFilterContext context)
        if (context == null) return;

        // NEW! enable sync IO beacuse the JSON reader apparently doesn't use async and it throws an exception otherwise
        var syncIOFeature = context.HttpContext.Features.Get<IHttpBodyControlFeature>();
        if (syncIOFeature != null)
            syncIOFeature.AllowSynchronousIO = true;

            var req = context.HttpContext.Request;


            // read the body here as a workarond for the JSON parser disposing the stream
            if (req.Body.CanSeek)
                req.Body.Seek(0, SeekOrigin.Begin);

                // if body (stream) can seek, we can read the body to a string for logging purposes
                using (var reader = new StreamReader(
                     encoding: Encoding.UTF8,
                     detectEncodingFromByteOrderMarks: false,
                     bufferSize: 8192,
                     leaveOpen: true))
                    var jsonString = reader.ReadToEnd();

                    // store into the HTTP context Items["request_body"]
                    context.HttpContext.Items.Add("request_body", jsonString);

                // go back to beginning so json reader get's the whole thing
                req.Body.Seek(0, SeekOrigin.Begin);

So now, I can access the body using the HttpContext.Items["request_body"] in the endpoints that have the [ReadRequestBodyIntoItems] attribute.

But man, this seems like way too many hoops to jump through. So here's where I ended, and I'm really happy with it.

My endpoint started as something like:

public async Task<IActionResult> ReceiveSomeData([FromBody] MyJsonObjectType value)
    val bodyString = HttpContext.Items["request_body"];
    // use the body, process the stuff...

But it is much more straightforward to just change the signature, like so:

public async Task<IActionResult> ReceiveSomeData()
    using (var reader = new StreamReader(
           encoding: Encoding.UTF8,
           detectEncodingFromByteOrderMarks: false
        var bodyString = await reader.ReadToEndAsync();

        var value = JsonConvert.DeserializeObject<MyJsonObjectType>(bodyString);

        // use the body, process the stuff...

I really liked this because it only reads the body stream once, and I have have control of the deserialization. Sure, it's nice if ASP.NET core does this magic for me, but here I don't waste time reading the stream twice (perhaps buffering each time), and the code is quite clear and clean.

If you need this functionality on lots of endpoints, perhaps the middleware approaches might be cleaner, or you can at least encapsulate the body extraction into an extension function to make the code more concise.

Anyways, I did not find any source that touched on all 3 aspects of this issue, hence this post. Hopefully this helps someone!

BTW: This was using ASP .NET Core 3.1.

Save file Javascript with file name

Use the filename property like this:

uriContent = "data:application/octet-stream;filename=filename.txt," + 
              encodeURIComponent(codeMirror.getValue());, 'filename.txt');


Apparently, there is no reliable way to do this. See: Is there any way to specify a suggested filename when using data: URI?

MySQL: Quick breakdown of the types of joins

Full Outer join don't exist in mysql , you might need to use a combination of left and right join.

Can I open a dropdownlist using jQuery

I've come across the same problem and I have a solution. A function called ExpandSelect() that emulates mouse clicking on "select" element, it does so by creating an another <select> element that is absolutely posioned and have multiple options visible at once by setting the size attribute. Tested in all major browsers: Chrome, Opera, Firefox, Internet Explorer. Explanation of how it works, along with the code here:

Edit (link was broken).

I've created a project at Google Code, go for the code there:


There is a little difference in GUI when emulating click, but it does not really matter, see it for yourself:

When mouse clicking:


When emulating click:


More screenshots on project's website, link above.

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

By any chance have you tried POST vs post? This support article suggests it can cause problems with IIS:

Not able to launch IE browser using Selenium2 (Webdriver) with Java

For NighwatchJS use:

"ie" : {
  "desiredCapabilities": {
    "browserName": "internet explorer",
    "javascriptEnabled": true,
    "acceptSslCerts": true,
    "allowBlockedContent": true,
    "ignoreProtectedModeSettings": true

Split string to equal length substrings in Java

public String[] splitInParts(String s, int partLength)
    int len = s.length();

    // Number of parts
    int nparts = (len + partLength - 1) / partLength;
    String parts[] = new String[nparts];

    // Break into parts
    int offset= 0;
    int i = 0;
    while (i < nparts)
        parts[i] = s.substring(offset, Math.min(offset + partLength, len));
        offset += partLength;

    return parts;

Getting the textarea value of a ckeditor textarea with javascript

var campaignTitle= CKEDITOR.instances['CampaignTitle'].getData();

python exception message capturing

You have to define which type of exception you want to catch. So write except Exception, e: instead of except, e: for a general exception (that will be logged anyway).

Other possibility is to write your whole try/except code this way:

    with open(filepath,'rb') as f:
        con.storbinary('STOR '+ filepath, f)'File successfully uploaded to '+ FTPADDR)
except Exception, e: # work on python 2.x
    logger.error('Failed to upload to ftp: '+ str(e))

in Python 3.x and modern versions of Python 2.x use except Exception as e instead of except Exception, e:

    with open(filepath,'rb') as f:
        con.storbinary('STOR '+ filepath, f)'File successfully uploaded to '+ FTPADDR)
except Exception as e: # work on python 3.x
    logger.error('Failed to upload to ftp: '+ str(e))

How to redirect a url in NGINX

First make sure you have installed Nginx with the HTTP rewrite module. To install this we need to have pcre-library

How to install pcre library

If the above mentioned are done or if you already have them, then just add the below code in your nginx server block

  if ($host !~* ^www\.) {
    rewrite ^(.*)$ http://www.$host$1 permanent;

To remove www from every request you can use

  if ($host = '' ) {
   rewrite  ^/(.*)$$1  permanent;

so your server block will look like

  server {
            listen       80;
            if ($host !~* ^www\.) {
                    rewrite ^(.*)$ http://www.$host$1 permanent;
            client_max_body_size   10M;
            client_body_buffer_size   128k;

            root       /home/test/test/public;
            passenger_enabled on;
            rails_env production;

            error_page   500 502 503 504  /50x.html;
            location = /50x.html {
                    root   html;

How to get second-highest salary employees in a table

To get the names of the employees with the 2nd highest distinct salary amount you can use.

       DENSE_RANK() OVER (ORDER BY Salary Desc) AS Rnk
FROM Employees
WHERE Rnk=2;

If Salary is indexed the following may well be more efficient though especially if there are many employees.

FROM   Employees
WHERE  Salary = (SELECT MIN(Salary)
                 FROM   (SELECT DISTINCT TOP (2) Salary
                         FROM   Employees
                         ORDER  BY Salary DESC) T);

Test Script

     Name   VARCHAR(50),
     Salary FLOAT

SELECT TOP 1000000,
FROM   sysobjects s1,
       sysobjects s2

  ON Employees(Salary)

FROM   Employees
WHERE  Salary = (SELECT MIN(Salary)
                 FROM   (SELECT DISTINCT TOP (2) Salary
                         FROM   Employees
                         ORDER  BY Salary DESC) T);

     AS (SELECT *,
                DENSE_RANK() OVER (ORDER BY Salary DESC) AS Rnk
         FROM   Employees)
WHERE  Rnk = 2;

FROM   Employees
                 FROM   Employees
                 WHERE  Salary NOT IN (SELECT DISTINCT TOP (1) Salary
                                       FROM   Employees
                                       ORDER  BY Salary DESC)
                 ORDER  BY Salary DESC)

FROM   Employees
WHERE  Salary = (SELECT TOP 1 Salary
                 FROM   (SELECT TOP 2 Salary
                         FROM   Employees
                         ORDER  BY Salary DESC) sel
                 ORDER  BY Salary ASC)  

List of strings to one string

I would go with option A:

String.Join(String.Empty, los.ToArray());

My reasoning is because the Join method was written for that purpose. In fact if you look at Reflector, you'll see that unsafe code was used to really optimize it. The other two also WORK, but I think the Join function was written for this purpose, and I would guess, the most efficient. I could be wrong though...

As per @Nuri YILMAZ without .ToArray(), but this is .NET 4+:

String.Join(String.Empty, los);

How to check if a string is numeric?

To check for all int chars, you can simply use a double negative. if (!searchString.matches("[^0-9]+$")) ...

[^0-9]+$ checks to see if there are any characters that are not integer, so the test fails if it's true. Just NOT that and you get true on success.

Display HTML snippets in HTML

This is a simple trick and I have tried it in Safari and Firefox

    <span><</span>meta property="og:title" content="A very fine cuisine" /><br>
    <span><</span>meta property="og:image" content="" />

It will show like this:

enter image description here

You can see it live Here

What does void do in java?

You mean the tellItLikeItIs method? Yes, you have to specify void to specify that the method doesn't return anything. All methods have to have a return type specified, even if it's void.

It certainly doesn't return a string - look, there are no return statements anywhere. It's not really clear why you think it is returning a string. It's printing strings to the console, but that's not the same thing as returning one from the method.

How do I flush the cin buffer?

cin.get() seems to flush it automatically oddly enough (probably not preferred though, since this is confusing and probably temperamental).

Go / golang time.Now().UnixNano() convert to milliseconds?

As @Jono points out in @OneOfOne's answer, the correct answer should take into account the duration of a nanosecond. Eg:

func makeTimestamp() int64 {
    return time.Now().UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))

OneOfOne's answer works because time.Nanosecond happens to be 1, and dividing by 1 has no effect. I don't know enough about go to know how likely this is to change in the future, but for the strictly correct answer I would use this function, not OneOfOne's answer. I doubt there is any performance disadvantage as the compiler should be able to optimize this perfectly well.


Another way of looking at this is that both time.Now().UnixNano() and time.Millisecond use the same units (Nanoseconds). As long as that is true, OneOfOne's answer should work perfectly well.

Android - Best and safe way to stop thread

This worked for me like this. Introduce a static variable in main activity and regularly check for it how i did was below.

public class MainActivity extends AppCompatActivity {

//This is the static variable introduced in main activity
public static boolean stopThread =false;

  protected void onCreate(Bundle savedInstanceState) {


    Thread thread = new Thread(new Thread1());

    Button stp_thread= findViewById(;

    stp_thread.setOnClickListener(new Button.OnClickListener(){
           public void onClick(View v){
              stopThread = true;



  class Thread1 implements Runnable{

        public void run() {

        while(!MainActivity.stopThread) {
             Do Something here


        process 1 goes here;

        //Below method also could be used
            return ;
        // use this after every line

        process 2 goes here;

        //Below method also could be used
            return ;
        // use this after every line

        process 3 goes here;

        //Below method also could be used
            return ;
        // use this after every line

        process 4 goes here;



How to use PHP string in mySQL LIKE query?

DO it like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");

Do not forget the % at the end

Defining private module functions in python

embedded with closures or functions is one way. This is common in JS although not required for non-browser platforms or browser workers.

In Python it seems a bit strange, but if something really needs to be hidden than that might be the way. More to the point using the python API and keeping things that require to be hidden in the C (or other language) is probably the best way. Failing that I would go for putting the code inside a function, calling that and having it return the items you want to export.

Formatting code in Notepad++

This isn't quite the answer you were looking for, but it's the solution I came to when I had the same question.

I'm a pretty serious Notepad++ user, so don't take this the wrong way. I have started using NetBeans 8 to develop websites in addition to Notepad++ because you can set it to autoformat on save for all your languages, and there are a ton of configuration options for how the formatting looks, down to the most minute detail. You might look into it and find it is a worthy tool to use in conjunction with notepad++. It's also open source, completely free, and has a bunch of plugins and other useful things like automatically compiling Sass if you use that too. It's definitely not as quick as NP++ so it's not great for small edits, but it can be nice for a long coding session.

Simple way to repeat a string

Despite your desire not to use loops, I think you should use a loop.

String repeatString(String s, int repetitions)
    if(repetitions < 0) throw SomeException();

    else if(s == null) return null;

    StringBuilder stringBuilder = new StringBuilder(s.length() * repetitions);

    for(int i = 0; i < repetitions; i++)

    return stringBuilder.toString();

Your reasons for not using a for loop are not good ones. In response to your criticisms:

  1. Whatever solution you use will almost certainly be longer than this. Using a pre-built function only tucks it under more covers.
  2. Someone reading your code will have to figure out what you're doing in that non-for-loop. Given that a for-loop is the idiomatic way to do this, it would be much easier to figure out if you did it with a for loop.
  3. Yes someone might add something clever, but by avoiding a for loop you are doing something clever. That's like shooting yourself in the foot intentionally to avoid shooting yourself in the foot by accident.
  4. Off-by-one errors are also mind-numbingly easy to catch with a single test. Given that you should be testing your code, an off-by-one error should be easy to fix and catch. And it's worth noting: the code above does not contain an off-by-one error. For loops are equally easy to get right.
  5. So don't reuse variables. That's not the for-loop's fault.
  6. Again, so does whatever solution you use. And as I noted before; a bug hunter will probably be expecting you to do this with a for loop, so they'll have an easier time finding it if you use a for loop.

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("");
URL url = new URL(domain + "/files/resource.xml");



Although I am very late to this but after seeing some legitimate questions for those who wanted to use INSERT-SELECT query with GROUP BY clause, I came up with the work around for this.

Taking further the answer of Marcus Adams and accounting GROUP BY in it, this is how I would solve the problem by using Subqueries in the FROM Clause

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT, uid, sb.location, sb.animal, sb.starttime, sb.endtime, sb.entct, 
       sb.inact, sb.inadur, sb.inadist, 
       sb.smlct, sb.smldur, sb.smldist, 
       sb.larct, sb.lardur, sb.lardist, 
       sb.emptyct, sb.emptydur
(SELECT id, uid, location, animal, starttime, endtime, entct, 
       inact, inadur, inadist, 
       smlct, smldur, smldist, 
       larct, lardur, lardist, 
       emptyct, emptydur 
FROM tmp WHERE uid=x
GROUP BY location) as sb
ON DUPLICATE KEY UPDATE entct=sb.entct, inact=sb.inact, ...

Why can't I reference System.ComponentModel.DataAnnotations?

If you don't have it in references (like I did not) you can also add the NuGet System.ComponentModel.Annotations to get the assemblies and resolve the errors. (Adding it here as this answer still top of Google for the error)

How to determine previous page URL in Angular?

I had similar problem when I had wanted to back to previous page. Solution was easier than I could imagine.

<button [routerLink]="['../']">

And it returns to parent url. I hope it will help someone ;)

how to get param in method post spring mvc?

  1. Spring annotations will work fine if you remove enctype="multipart/form-data".

    @RequestParam(value="txtEmail", required=false)
  2. You can even get the parameters from the request object .

  3. Use a form in case the number of attributes are large. It will be convenient. Tutorial to get you started.

  4. Configure the Multi-part resolver if you want to receive enctype="multipart/form-data".

    <bean id="multipartResolver"
        <property name="maxUploadSize" value="250000"/>

Refer the Spring documentation.

How do I programmatically "restart" an Android app?

I have slightly modified Ilya_Gazman answer to use new APIs (IntentCompat is deprecated starting API 26). Runtime.getRuntime().exit(0) seems to be better than System.exit(0).

 public static void triggerRebirth(Context context) {
    PackageManager packageManager = context.getPackageManager();
    Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName());
    ComponentName componentName = intent.getComponent();
    Intent mainIntent = Intent.makeRestartActivityTask(componentName);

Barcode scanner for mobile phone for Website in form

We have an app in Google Play and the App Store that will scan barcodes into a web site. The app is called Scan to Web.

You can even embed a link or button to start the scanner yourself within your web page.

<a href="bwstw://startscanner">Link to start scanner</a>

The developer documentation website for the app covers how to use the app and use JavaScript for processing the barcode scan.

How to check java bit version on Linux?

Go to this JVM online test and run it.

Then check the architecture displayed: x86_64 means you have the 64bit version installed, otherwise it's 32bit.

How to convert DataSet to DataTable

Here is my solution:

DataTable datatable = (DataTable)dataset.datatablename;

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

This line seems to sum up the crux of your problem:

The issue with this is that now you can't call any new methods (only overrides) on the implementing class, as your object reference variable has the interface type.

You are pretty stuck in your current implementation, as not only do you have to attempt a cast, you also need the definition of the method(s) that you want to call on this subclass. I see two options:

1. As stated elsewhere, you cannot use the String representation of the Class name to cast your reflected instance to a known type. You can, however, use a String equals() test to determine whether your class is of the type that you want, and then perform a hard-coded cast:

try {
   String className = "";// really passed in from config
   Class c = Class.forName(className);
   InterfaceType interfaceType = (InterfaceType)c.newInstance();
   if (className.equals("") {
} catch (Exception e) {

This looks pretty ugly, and it ruins the nice config-driven process that you have. I dont suggest you do this, it is just an example.

2. Another option you have is to extend your reflection from just Class/Object creation to include Method reflection. If you can create the Class from a String passed in from a config file, you can also pass in a method name from that config file and, via reflection, get an instance of the Method itself from your Class object. You can then call invoke(, java.lang.Object...)) on the Method, passing in the instance of your class that you created. I think this will help you get what you are after.

Here is some code to serve as an example. Note that I have taken the liberty of hard coding the params for the methods. You could specify them in a config as well, and would need to reflect on their class names to define their Class obejcts and instances.

public class Foo {

    public void printAMessage() {
    System.out.println(toString()+":a message");
    public void printAnotherMessage(String theString) {
        System.out.println(toString()+":another message:" + theString);

    public static void main(String[] args) {
        Class c = null;
        try {
            c = Class.forName("Foo");
            Method method1 = c.getDeclaredMethod("printAMessage", new Class[]{});
            Method method2 = c.getDeclaredMethod("printAnotherMessage", new Class[]{String.class});
            Object o = c.newInstance();
            System.out.println("this is my instance:" + o.toString());
            method2.invoke(o, "this is my message, from a config file, of course");
        } catch (ClassNotFoundException e) {
        } catch (NoSuchMethodException nsme){
        } catch (IllegalAccessException iae) {
        } catch (InstantiationException ie) {
        } catch (InvocationTargetException ite) {

and my output:

this is my instance:Foo@e0cf70
Foo@e0cf70:a message
Foo@e0cf70:another message:this is my message, from a config file, of course

How do I represent a time only value in .NET?

As others have said, you can use a DateTime and ignore the date, or use a TimeSpan. Personally I'm not keen on either of these solutions, as neither type really reflects the concept you're trying to represent - I regard the date/time types in .NET as somewhat on the sparse side which is one of the reasons I started Noda Time. In Noda Time, you can use the LocalTime type to represent a time of day.

One thing to consider: the time of day is not necessarily the length of time since midnight on the same day...

(As another aside, if you're also wanting to represent a closing time of a shop, you may find that you want to represent 24:00, i.e. the time at the end of the day. Most date/time APIs - including Noda Time - don't allow that to be represented as a time-of-day value.)

Best dynamic JavaScript/JQuery Grid

Have a look at as this has a simple to use CRUD which supports 2,4,6,7,9,10 and 12 out of the box (uses Ajax to defender the grid when adding,deleting data and it integrates with jquery.

I would post some examples but on an iPad at the moment.

How do I find which rpm package supplies a file I'm looking for?

You can do this alike here but with your package. In my case, it was lsb_release

Run: yum whatprovides lsb_release


redhat-lsb-core-4.1-24.el7.i686 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-24.el7.x86_64 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-27.el7.i686 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-27.el7.x86_64 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release`

Run to install: yum install redhat-lsb-core

The package name SHOULD be without number and system type so yum packager can choose what is best for him.

Regular expression for decimal number

In .NET, I recommend to dynamically build the regular expression with the decimal separator of the current cultural context:

using System.Globalization;


NumberFormatInfo nfi = NumberFormatInfo.CurrentInfo;
Regex re = new Regex("^(?\\d+(" 
                   + Regex.Escape(nfi.CurrencyDecimalSeparator) 
                   + "\\d{1,2}))$");

You might want to pimp the regexp by allowing 1000er separators the same way as the decimal separator.

How can I open two pages from a single click without using JavaScript?

it is working perfectly by only using html

<p><a href="#"onclick="'');'');">Click to open Google and Yahoo</a></p>

C# - How to get Program Files (x86) on Windows 64 bit

One way would be to look for the "ProgramFiles(x86)" environment variable:

String x86folder = Environment.GetEnvironmentVariable("ProgramFiles(x86)");

What is the HTML tabindex attribute?

When the user presses the tab button the user will be taken through the form in the order 1, 2, and 3 as indicated in the example below.

For example:

Name: <input name="name" tabindex="1"  />
Age: <input name="age" tabindex="3"  />
Email: <input name="email" tabindex="2"  />

Binning column with python pandas

Using numba module for speed up.

On big datasets (500k >) pd.cut can be quite slow for binning data.

I wrote my own function in numba with just in time compilation, which is roughly 16x faster:

from numba import njit

def cut(arr):
    bins = np.empty(arr.shape[0])
    for idx, x in enumerate(arr):
        if (x >= 0) & (x < 1):
            bins[idx] = 1
        elif (x >= 1) & (x < 5):
            bins[idx] = 2
        elif (x >= 5) & (x < 10):
            bins[idx] = 3
        elif (x >= 10) & (x < 25):
            bins[idx] = 4
        elif (x >= 25) & (x < 50):
            bins[idx] = 5
        elif (x >= 50) & (x < 100):
            bins[idx] = 6
            bins[idx] = 7

    return bins

# array([5., 5., 7., 5.])

Optional: you can also map it to bins as strings:

a = cut(df['percentage'].to_numpy())

conversion_dict = {1: 'bin1',
                   2: 'bin2',
                   3: 'bin3',
                   4: 'bin4',
                   5: 'bin5',
                   6: 'bin6',
                   7: 'bin7'}

bins = list(map(conversion_dict.get, a))

# ['bin5', 'bin5', 'bin7', 'bin5']

Speed comparison:

# create dataframe of 8 million rows for testing
dfbig = pd.concat([df]*2000000, ignore_index=True)


# (8000000, 1)

# 38 ms ± 616 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
pd.cut(dfbig['percentage'], bins=bins, labels=labels)

# 215 ms ± 9.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

jQuery: find element by text

Best way in my opinion.

$.fn.findByContentText = function (text) {
    return $(this).contents().filter(function () {
        return $(this).text().trim() == text.trim();

How to convert minutes to hours/minutes and add various time values together using jQuery?

The function below will take as input # of minutes and output time in the following format: Hours:minutes. I used Math.trunc(), which is a new method added in 2015. It returns the integral part of a number by removing any fractional digits.

function display(a){
  var hours = Math.trunc(a/60);
  var minutes = a % 60;
  console.log(hours +":"+ minutes);

display(120); //"2:0"
display(60); //"1:0:
display(100); //"1:40"
display(126); //"2:6"
display(45); //"0:45"

Passing multiple values for same variable in stored procedure

You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.

Split Function Works Great when you are getting One String containing multiple values but when you are passing Multiple values you need to do something like this....


CREATE TYPE dbo.TYPENAME AS TABLE   (     arg int    )  GO 

Stored Procedure to Accept That Type Param

 CREATE PROCEDURE mainValues   @TableParam TYPENAME READONLY  AS     BEGIN     SET NOCOUNT ON;   --Temp table to store split values   declare @tmp_values table (   value nvarchar(255) not null);        --function splitting values     INSERT INTO @tmp_values (value)    SELECT arg FROM @TableParam      SELECT * FROM @tmp_values  --<-- For testing purpose END 


Declare a variable of that type and populate it with your values.

 DECLARE @Table TYPENAME     --<-- Variable of this TYPE   INSERT INTO @Table                --<-- Populating the variable   VALUES (331),(222),(876),(932)  EXECUTE mainValues @Table   --<-- Stored Procedure Executed  


╔═══════╗ ║ value ║ ╠═══════╣ ║   331 ║ ║   222 ║ ║   876 ║ ║   932 ║ ╚═══════╝ 

Read line with Scanner

This code reads the file line by line.

public static void readFileByLine(String fileName) {
  try {
   File file = new File(fileName);
   Scanner scanner = new Scanner(file);
   while (scanner.hasNext()) {
  } catch (FileNotFoundException e) {

You can also set a delimiter as a line separator and then perform the same.


You have to check whether there is a next token available and then read the next token. You will also need to doublecheck the input given to the Scanner. i.e. dico.txt. By default, Scanner breaks its input based on whitespace. Please ensure that the input has the delimiters in right place

UPDATED ANSWER for your comment:

I just tried to create an input file with the content as below


tried to read it with the below just worked fine.

 File file = new File("/home/keerthivasan/Desktop/input.txt");
     Scanner scr = null;
         try {
            scr = new Scanner(file);
                System.out.println("line : ";
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ScannerTest.class.getName()).log(Level.SEVERE, null, ex);


line : a
line : à
line : abaissa
line : abaissable
line : abaissables
line : abaissai
line : abaissaient
line : abaissais
line : abaissait

so, I am sure that this should work. Since you work in Windows ennvironment, The End of Line (EOL) sequence (0x0D 0x0A, \r\n) is actually two ASCII characters, a combination of the CR and LF characters. if you set your Scanner instance to use delimiter as follows, it will pick up probably

 scr = new Scanner(file);

and then do your looping to read lines. Hope this helps!

What is the MySQL JDBC driver connection string?

it's depends on what service you're using.

if you use MySQL Workbench it wold be some thing like this :

jdbc:mysql://"host":"port number"/

String url = "jdbc:mysql://localhost:3306/";

And of course it will be different if you using SSL/SSH.

For more information follow the official link of Jetbriens (intelliJ idea) :

Connecting to a database #

Configuring database connections #

C# Version Of SQL LIKE

Use it like this:

if (lbl.Text.StartWith("hr")==true ) {…}

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

Git Pull vs Git Rebase

git-pull - Fetch from and integrate with another repository or a local branch GIT PULL

Basically you are pulling remote branch to your local, example:

git pull origin master

Will pull master branch into your local repository

git-rebase - Forward-port local commits to the updated upstream head GIT REBASE

This one is putting your local changes on top of changes done remotely by other users. For example:

  • You have committed some changes on your local branch for example called SOME-FEATURE
  • Your friend in the meantime was working on other features and he merged his branch into master

Now you want to see his and your changes on your local branch. So then you checkout master branch:

git checkout master

then you can pull:

git pull origin master

and then you go to your branch:

git checkout SOME-FEATURE

and you can do rebase master to get lastest changes from it and put your branch commits on top:

git rebase master

I hope now it's a bit more clear for you.

How do I set response headers in Flask?

This work for me

from flask import Flask
from flask import Response

app = Flask(__name__)

def home():
    return Response(headers={'Access-Control-Allow-Origin':'*'})

if __name__ == "__main__":

How can I set the default value for an HTML <select> element?

Set selected="selected" where is option value is 3

please see below example

<option selected="selected" value="3" >3</option>

How to wait for a JavaScript Promise to resolve before resuming function?

Another option is to use Promise.all to wait for an array of promises to resolve and then act on those.

Code below shows how to wait for all the promises to resolve and then deal with the results once they are all ready (as that seemed to be the objective of the question); Also for illustrative purposes, it shows output during execution (end finishes before middle).

function append_output(suffix, value) {

function kickOff() {
  let start = new Promise((resolve, reject) => {
    append_output("now", "start")
  let middle = new Promise((resolve, reject) => {
    setTimeout(() => {
      append_output("now", " middle")
      resolve(" middle")
    }, 1000)
  let end = new Promise((resolve, reject) => {
    append_output("now", " end")
    resolve(" end")

  Promise.all([start, middle, end]).then(results => {
      result => append_output("later", result))

<script src=""></script>
Updated during execution: <div id="output_now"></div>
Updated after all have completed: <div id="output_later"></div>

What is the proper way to format a multi-line dict in Python?

Usually, if you have big python objects it's quite hard to format them. I personally prefer using some tools for that.

Here is python-beautifier - that instantly turns your data into customizable style.

How to change row color in datagridview?

Something like the following... assuming the values in the cells are Integers.

foreach (DataGridViewRow dgvr in myDGV.Rows)
  if (dgvr.Cells[7].Value < dgvr.Cells[10].Value)
    dgvr.DefaultCellStyle.ForeColor = Color.Red;

untested, so apologies for any error.

If you know the particular row, you can skip the iteration:

if (myDGV.Rows[theRowIndex].Cells[7].Value < myDGV.Rows[theRowIndex].Cells[10].Value)
  dgvr.DefaultCellStyle.ForeColor = Color.Red;

Formatting ISODate from Mongodb

// from MongoDate object to Javascript Date object

var MongoDate = {sec: 1493016016, usec: 650000};
var dt = new Date("1970-01-01T00:00:00+00:00");

Hibernate: in production?

  • Typically enterprise applications in large organizations run with reduced privileges.

  • Database username may not have DDL privilege for adding columns which requires.

return string with first match Regex

You could embed the '' default in your regex by adding |$:

>>> re.findall('\d+|$', 'aa33bbb44')[0]
>>> re.findall('\d+|$', 'aazzzbbb')[0]
>>> re.findall('\d+|$', '')[0]

Also works with pointed out by others:

>>>'\d+|$', 'aa33bbb44').group()
>>>'\d+|$', 'aazzzbbb').group()
>>>'\d+|$', '').group()

Python naming conventions for modules

I know my solution is not very popular from the pythonic point of view, but I prefer to use the Java approach of one module->one class, with the module named as the class. I do understand the reason behind the python style, but I am not too fond of having a very large file containing a lot of classes. I find it difficult to browse, despite folding.

Another reason is version control: having a large file means that your commits tend to concentrate on that file. This can potentially lead to a higher quantity of conflicts to be resolved. You also loose the additional log information that your commit modifies specific files (therefore involving specific classes). Instead you see a modification to the module file, with only the commit comment to understand what modification has been done.

Summing up, if you prefer the python philosophy, go for the suggestions of the other posts. If you instead prefer the java-like philosophy, create a containing class Nib.

How can I make visible an invisible control with jquery? (hide and show not work)

It's been more than 10 years and not sure if anyone still finding this question or answer relevant.

But a quick workaround is just to wrap the asp control within a html container

<div id="myElement" style="display: inline-block">
   <asp:TextBox ID="textBox1" runat="server"></asp:TextBox>

Whenever the Javascript Event is triggered, if it needs to be an event by the asp control, just wrap the asp control around the div container.

<div id="testG">  
   <asp:Button ID="Button2" runat="server" CssClass="btn" Text="Activate" />

The jQuery Code is below:

$(document).ready(function () {
    $("#testG").click(function () {
                $("#myElement").css("display", "none");

GET URL parameter in PHP

To make sure you're always on the safe side, without getting all kinds of unwanted code insertion use FILTERS:

echo filter_input(INPUT_GET,"link",FILTER_SANITIZE_STRING);

More reading on function filter_input, or check out the description of the different filters

How to annotate MYSQL autoincrement field with JPA annotations

can you check whether you connected to the correct database. as i was faced same issue, but finally i found that i connected to different database.

identity supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

More Info :

Android getText from EditText field

Try this.

EditText text = (EditText)findViewById(;
String  str = text.getText().toString().trim();

How to parse a query string into a NameValueCollection in .NET

    private void button1_Click( object sender, EventArgs e )
        string s = @"p1=6&p2=7&p3=8";
        NameValueCollection nvc = new NameValueCollection();

        foreach ( string vp in Regex.Split( s, "&" ) )
            string[] singlePair = Regex.Split( vp, "=" );
            if ( singlePair.Length == 2 )
                nvc.Add( singlePair[ 0 ], singlePair[ 1 ] );    

forcing web-site to show in landscape mode only

@Golmaal really answered this, I'm just being a bit more verbose.

<style type="text/css">
    #warning-message { display: none; }
    @media only screen and (orientation:portrait){
        #wrapper { display:none; }
        #warning-message { display:block; }
    @media only screen and (orientation:landscape){
        #warning-message { display:none; }


<div id="wrapper">
    <!-- your html for your website -->
<div id="warning-message">
    this website is only viewable in landscape mode

You have no control over the user moving the orientation however you can at least message them. This example will hide the wrapper if in portrait mode and show the warning message and then hide the warning message in landscape mode and show the portrait.

I don't think this answer is any better than @Golmaal , only a compliment to it. If you like this answer, make sure to give @Golmaal the credit.


I've been working with Cordova a lot recently and it turns out you CAN control it when you have access to the native features.

Another Update

So after releasing Cordova it is really terrible in the end. It is better to use something like React Native if you want JavaScript. It is really amazing and I know it isn't pure web but the pure web experience on mobile kind of failed.

How to run the Python program forever?

I have a small script that runs the code at an interval (default 1sec), it pumps out a message to the screen while it's running, and traps an interrupt signal that you can send with CTL-C:

from interruptableLoop import InterruptableLoop

loop=InterruptableLoop(intervalSecs=1) # redundant argument
while loop.ShouldContinue():
   # some python code that I want 
   # to keep on running

When you run the script and then interrupt it you see this output, (the periods pump out on every pass of the loop):

[py36]$ ./
CTL-C to stop   (or $kill -s SIGINT pid)
Exiting at  2018-07-28 14:58:40.359331

    Use to create a permanent loop that can be stopped ...

    ... from same terminal where process was started and is running in foreground: 

    ... from same user account but through a different terminal 
        $ kill -2 <pid> 
        or $ kill -s SIGINT <pid>

import signal
import time
from datetime import datetime as dtt
class InterruptableLoop:
    def __init__(self,intervalSecs=1,printStatus=True):
        if self.printStatus:
            print ("CTL-C to stop\t(or $kill -s SIGINT pid)")
        signal.signal(signal.SIGINT, self._StopRunning)
        signal.signal(signal.SIGQUIT, self._Abort)
        signal.signal(signal.SIGTERM, self._Abort)

    def _StopRunning(self, signal, frame):
        self.shouldContinue = False

    def _Abort(self, signal, frame):

    def ShouldContinue(self):
        if self.shouldContinue and self.printStatus: 
            print( ".",end="",flush=True)
        elif not self.shouldContinue and self.printStatus:
            print ("Exiting at ",
        return self.shouldContinue

How to easily get network path to the file you are working on?

Easiest way to find address path in Excel 2010:

File - info - properties (on right) - (drop-down menu) - advanced properties - general tab

You will get to the same properties box that was so simple to find in Excel 2003.

Launch Pycharm from command line (terminal)

You can launch Pycharm from Mac terminal using the open command. Just type open /path/to/App

Applications$ ls -lrt PyCharm\
total 8
drwxr-xr-x@ 71 amit  admin  2414 Sep 24 11:08 lib
drwxr-xr-x@  4 amit  admin   136 Sep 24 11:08 help
drwxr-xr-x@ 12 amit  admin   408 Sep 24 11:08 plugins
drwxr-xr-x@ 29 amit  admin   986 Sep 24 11:08 license
drwxr-xr-x@  4 amit  admin   136 Sep 24 11:08 skeletons
-rw-r--r--@  1 amit  admin    10 Sep 24 11:08 build.txt
drwxr-xr-x@  6 amit  admin   204 Sep 24 11:12 Contents
drwxr-xr-x@ 14 amit  admin   476 Sep 24 11:12 bin
drwxr-xr-x@ 31 amit  admin  1054 Sep 25 21:43 helpers
/Applications$ open PyCharm\

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

As already mentioned, compiling the app in x64 gives you far more available memory.

But in the case one must build an app in x86, there is a way to raise the memory limit from 1,2GB to 4GB (which is the actual limit for 32 bit processes):

In the VC/bin folder of the Visual Studio installation directory, there must be an editbin.exe file. So in my default installation I find it under

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\editbin.exe

In order to make the program work, maybe you must execute vcvars32.bat in the same directory first. Then a

editbin /LARGEADDRESSAWARE <your compiled exe file>

is enough to let your program use 4GB RAM. <your compiled exe file> is the exe, which VS generated while compiling your project.

If you want to automate this behavior every time you compile your project, use the following Post-Build event for the executed project:

if exist "$(DevEnvDir)..\tools\vsvars32.bat" (
   call "$(DevEnvDir)..\tools\vsvars32.bat"
   editbin /largeaddressaware "$(TargetPath)"

Sidenote: The same can be done with the devenv.exe to let Visual Studio also use 4GB RAM instead of 1.2GB (but first backup the old devenv.exe).

Can I do Android Programming in C++, C?

You can use the Android NDK, but answers should note that the Android NDK app is not free to use and there's no clear open source route to programming Android on Android in an increasingly Android-driven market that began as open source, with Android developer support or the extensiveness of the NDK app, meaning you're looking at abandoning Android as any kind of first steps programming platform without payments.

Note: I consider subscription requests as payments under duress and this is a freemium context which continues to go undefeated by the open source community.

How to parse XML using vba

Add reference Project->References Microsoft XML, 6.0 and you can use example code:

    Dim xml As String

    xml = "<root><person><name>Me </name> </person> <person> <name>No Name </name></person></root> "
    Dim oXml As MSXML2.DOMDocument60
    Set oXml = New MSXML2.DOMDocument60
    oXml.loadXML xml
    Dim oSeqNodes, oSeqNode As IXMLDOMNode

    Set oSeqNodes = oXml.selectNodes("//root/person")
    If oSeqNodes.length = 0 Then
       'show some message
        For Each oSeqNode In oSeqNodes
             Debug.Print oSeqNode.selectSingleNode("name").Text
    End If 

be careful with xml node //Root/Person is not same with //root/person, also selectSingleNode("Name").text is not same with selectSingleNode("name").text

Linux : Search for a Particular word in a List of files under a directory

This is a very frequent task in linux. I use grep -rn '' . all the time to do this. -r for recursive (folder and subfolders) -n so it gives the line numbers, the dot stands for the current directory.

grep -rn '<word or regex>' <location>

do a

man grep 

for more options

Python Pandas - Find difference between two data frames

Accepted answer Method 1 will not work for data frames with NaNs inside, as != I am not sure if this is the best way, but it can be avoided by

df1[~df1.astype(str).apply(tuple, 1).isin(df2.astype(str).apply(tuple, 1))]

It's slower, because it needs to cast data to string, but thanks to this casting ==

Let's go trough the code. First we cast values to string, and apply tuple function to each row.

df1.astype(str).apply(tuple, 1)
df2.astype(str).apply(tuple, 1)

Thanks to that, we get pd.Series object with list of tuples. Each tuple contains whole row from df1/df2. Then we apply isin method on df1 to check if each tuple "is in" df2. The result is pd.Series with bool values. True if tuple from df1 is in df2. In the end, we negate results with ~ sign, and applying filter on df1. Long story short, we get only those rows from df1 that are not in df2.

To make it more readable, we may write it as:

df1_str_tuples = df1.astype(str).apply(tuple, 1)
df2_str_tuples = df2.astype(str).apply(tuple, 1)
df1_values_in_df2_filter = df1_str_tuples.isin(df2_str_tuples)
df1_values_not_in_df2 = df1[~df1_values_in_df2_filter]

InputStream from a URL


final InputStream is = new URL("").openStream();

Adding null values to arraylist

You could create Util class:

public final class CollectionHelpers {
    public static <T> boolean addNullSafe(List<T> list, T element) {
        if (list == null || element == null) {
            return false;

        return list.add(element);

And then use it:

Element element = getElementFromSomeWhere(someParameter);
List<Element> arrayList = new ArrayList<>();
CollectionHelpers.addNullSafe(list, element);

What does the C++ standard state the size of int, long type to be?

In practice there's no such thing. Often you can expect std::size_t to represent the unsigned native integer size on current architecture. i.e. 16-bit, 32-bit or 64-bit but it isn't always the case as pointed out in the comments to this answer.

As far as all the other built-in types go, it really depends on the compiler. Here's two excerpts taken from the current working draft of the latest C++ standard:

There are five standard signed integer types : signed char, short int, int, long int, and long long int. In this list, each type provides at least as much storage as those preceding it in the list.

For each of the standard signed integer types, there exists a corresponding (but different) standard unsigned integer type: unsigned char, unsigned short int, unsigned int, unsigned long int, and unsigned long long int, each of which occupies the same amount of storage and has the same alignment requirements.

If you want to you can statically (compile-time) assert the sizeof these fundamental types. It will alert people to think about porting your code if the sizeof assumptions change.

ngOnInit not being called when Injectable class is Instantiated

import {Injectable, OnInit} from 'angular2/core';
import { RestApiService, RestRequest } from './rest-api.service';
import {Service} from "path/to/service/";

export class MovieDbService implements OnInit {


constructor(private _movieDbRest: RestApiService,
            private instanceMyService : Service ){

   // do evreything like OnInit just on services


   this.userId = this.instanceMyService.getUserId()


How do you read a file into a list in Python?

To summarize a bit from what people have been saying:

f=open('data.txt', 'w') # will make a new file or erase a file of that name if it is present
f=open('data.txt', 'r') # will open a file as read-only
f=open('data.txt', 'a') # will open a file for appending (appended data goes to the end of the file)

If you wish have something in place similar to a try/catch

with open('data.txt') as f:
    for line in f:
        print line

I think @movieyoda code is probably what you should use however

Fastest way to check a string contain another substring in JavaScript?

I've found that using a simple for loop, iterating over all elements in the string and comparing using charAt performs faster than indexOf or Regex. The code and proof is available at JSPerf.

ETA: indexOf and charAt both perform similarly terrible on Chrome Mobile according to Browser Scope data listed on

How can I color a UIImage in Swift?

I ended up with this because other answers either lose resolution or work with UIImageView, not UIImage, or contain unnecessary actions:

Swift 3

extension UIImage {
    public func mask(with color: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        let context = UIGraphicsGetCurrentContext()!
        let rect = CGRect(origin:, size: size)
        self.draw(in: rect)
        let resultImage = UIGraphicsGetImageFromCurrentImageContext()!
        return resultImage

How to check if a value is not null and not empty string in JS

Both null and an empty string are falsy values in JS. Therefore,

if (data) { ... }

is completely sufficient.

A note on the side though: I would avoid having a variable in my code that could manifest in different types. If the data will eventually be a string, then I would initially define my variable with an empty string, so you can do this:

if (data !== '') { ... }

without the null (or any weird stuff like data = "0") getting in the way.

MYSQL Truncated incorrect DOUBLE value

If you're getting this problem with an insert that looks like the one below, the problem may simply be the lack of a space between -- and the comment text:

insert into myTable (a, b, c)
values (
   123 --something
  ,345 --something else
  ,567 --something something else

The problem with this is that the --something should actually be -- something with a space.

Javascript/Jquery Convert string to array

check this out :)

var traingIds = "[1,2]";  // ${triningIdArray} this value getting from server 
alert(traingIds);  // alerts [1,2]
var type = typeof(traingIds);
alert(type);   // // alerts String

//remove square brackets
traingIds = traingIds.replace('[','');
traingIds = traingIds.replace(']','');
alert(traingIds);  // alerts 1,2        
var trainindIdArray = traingIds.split(',');

?for(i = 0; i< trainindIdArray.length; i++){
    alert(trainindIdArray[i]); //outputs individual numbers in array

How to write hello world in assembler under Windows?

If you want to use NASM and Visual Studio's linker (link.exe) with anderstornvig's Hello World example you will have to manually link with the C Runtime Libary that contains the printf() function.

nasm -fwin32 helloworld.asm
link.exe helloworld.obj libcmt.lib

Hope this helps someone.

Click a button programmatically - JS

window.onload = function() {
    var userImage = document.getElementById('imageOtherUser');
    var hangoutButton = document.getElementById("hangoutButtonId");
    userImage.onclick = function() {; // this will trigger the click event

this will do the trick

What is the difference between "expose" and "publish" in Docker?

Most people use docker compose with networks. The documentation states:

The Docker network feature supports creating networks without the need to expose ports within the network, for detailed information see the overview of this feature).

Which means that if you use networks for communication between containers you don't need to worry about exposing ports.

JQuery to load Javascript file dynamically

Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.

You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:

$('#add_comment').click(function() {
    if(typeof TinyMCE == "undefined") {
        $.getScript('tinymce.js', function() {

Assuming you only have to call init on it once, that is. If not, you can figure it out from here :)

Send email using java

The short answer - No.

The long answer - no, since the code relies on the presence of a SMTP server running on the local machine, and listening on port 25. The SMTP server (technically the MTA or Mail Transfer Agent) is responsible for communicating with the Mail User Agent (MUA, which in this case is the Java process) to receive outgoing emails.

Now, MTAs are typically responsible for receiving mails from users for a particular domain. So, for the domain, it would be the Google mail servers that are responsible for authenticating mail user agents and hence transferring of mails to inboxes on the GMail servers. I'm not sure if GMail trusts open mail relay servers, but it is certainly not an easy task to perform authentication on behalf on Google, and then relay mail to the GMail servers.

If you read the JavaMail FAQ on using JavaMail to accessing GMail, you'll notice that the hostname and the port happen to be pointing to the GMail servers, and certainly not to localhost. If you intend to use your local machine, you'll need to perform either relaying or forwarding.

You'll probably need to understand the SMTP protocol in depth if you intend to get anywhere when it comes to SMTP. You can start with the Wikipedia article on SMTP, but any further progress will actually necessitate programming against a SMTP server.

Single line sftp from terminal

A minor modification like below worked for me when using it from within perl and system() call:

sftp {user}@{host} <<< $'put {local_file_path} {remote_file_path}'

check if "it's a number" function in Oracle

@JustinCave - The "when value_error" replacement for "when others" is a nice refinement to your approach above. This slight additional tweak, while conceptually the same, removes the requirement for the definition of and consequent memory allocation to your l_num variable:

function validNumber(vSomeValue IN varchar2)
  return case when abs(vSomeValue) >= 0 then 'T' end;
  when value_error then
    return 'F';

Just a note also to anyone preferring to emulate Oracle number format logic using the "riskier" REGEXP approach, please don't forget to consider NLS_NUMERIC_CHARACTERS and NLS_TERRITORY.

How to access site through IP address when website is on a shared host?

You can access you website using your IP address and your cPanel username with ~ symbols. For Example: http://serverip/~cpusername like as

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

In Python we can use the __str__() method.

We can override it in our class like this:

class User: 

    firstName = ''
    lastName = ''

    def __str__(self):
        return self.firstName + " " + self.lastName

and when running


it will call the function __str__(self) and print the firstName and lastName

django import error - No module named


First goto: virtualenv

by running the command: source bin/activate

and install django because you are getting the error related to 'import django':

pip install django

Then run:

python runserver

(Note: please change 'runserver' to the program name you want to run)

For the same issue, it worked in my case. ==================================Synopsis=========================================

(Development) Rakeshs-MacBook-Pro:src rakesh$ python runserver
Traceback (most recent call last):
  File "", line 8, in <module>
    from import execute_from_command_line
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "", line 14, in <module>
    import django
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
(Development) Rakeshs-MacBook-Pro:src rakesh$ 
(Development) Rakeshs-MacBook-Pro:src rakesh$ 
(Development) Rakeshs-MacBook-Pro:src rakesh$ python -Wall test
Traceback (most recent call last):
  File "", line 8, in <module>
    from import execute_from_command_line
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "", line 14, in <module>
    import django
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?


(Development) MacBook-Pro:src rakesh$ pip install django
Collecting django
  Downloading (7.3MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 7.3MB 1.1MB/s 
Collecting pytz (from django)
  Downloading (510kB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 512kB 4.7MB/s 
Installing collected packages: pytz, django


(Development) MacBook-Pro:src rakesh$ python runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python migrate' to apply them.

August 05, 2018 - 04:39:02
Django version 2.1, using settings 'trydjango.settings'
Starting development server at
Quit the server with CONTROL-C.
[05/Aug/2018 04:39:15] "GET / HTTP/1.1" 200 16348
[05/Aug/2018 04:39:15] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304
Not Found: /favicon.ico
[05/Aug/2018 04:39:16] "GET /favicon.ico HTTP/1.1" 404 1976

Good luck!! vs onClick

Well, one of the main ideas behind jQuery is to separate JavaScript from the nasty HTML code. The first method is the way to go.

Adding devices to team provisioning profile

right click on the device, then select 'add device to provisioning profile'

Display text from .txt file in batch file

@echo off
set log=%time% %date%
echo %log%

That is a batch for saving the date and time as a temporary variable, and displaying it. In a hurry, I don't have time to write a script to open a txt, maybe later.

Android - shadow on text?

You can do both in code and XML. Only 4 basic things to be set.

  1. shadow color
  2. Shadow Dx - it specifies the X-axis offset of shadow. You can give -/+ values, where -Dx draws a shadow on the left of text and +Dx on the right
  3. shadow Dy - it specifies the Y-axis offset of shadow. -Dy specifies a shadow above the text and +Dy specifies below the text.
  4. shadow radius - specifies how much the shadow should be blurred at the edges. Provide a small value if shadow needs to be prominent. Else otherwise.



This draws a prominent shadow on left-lower side of text. In code, you can add something like this;

    TextView item = new TextView(getApplicationContext());
    item.setShadowLayer(0.01f, -2, 2,   getResources().getColor(R.color.text_shadow_color));

Add error bars to show standard deviation on a plot in R

You can use arrows:

arrows(x,y-sd,x,y+sd, code=3, length=0.02, angle = 90)

Android 'Unable to add window -- token null is not for an application' exception

You can continue to use getApplicationContext(), but before use, you should add this flag: dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT), and the error will not show.

And don't forget to add permission:

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