Programs & Examples On #Apache commons cli

The Apache Commons CLI library provides an API for parsing command line options passed to programs. It's also able to print help messages detailing the options available for a command line tool.

How to call a RESTful web service from Android?

I used OkHttpClient to call restful web service. It's very simple.

OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
                .url(url)
                .build();

Response response = httpClient.newCall(request).execute();
String body = response.body().string()

PermissionError: [WinError 5] Access is denied python using moviepy to write gif

I was facing the same error while running command

pip install --upgrade pip

in a virtual venvironment (created with python -m venv venv).

using the --user flag fixed the problem for me

pip install --upgrade pip --user

If the problem not resolved use --user flag in a command prompt with admin rights.

Listing contents of a bucket with boto3

ObjectSummary:

There are two identifiers that are attached to the ObjectSummary:

  • bucket_name
  • key

boto3 S3: ObjectSummary

More on Object Keys from AWS S3 Documentation:

Object Keys:

When you create an object, you specify the key name, which uniquely identifies the object in the bucket. For example, in the Amazon S3 console (see AWS Management Console), when you highlight a bucket, a list of objects in your bucket appears. These names are the object keys. The name for a key is a sequence of Unicode characters whose UTF-8 encoding is at most 1024 bytes long.

The Amazon S3 data model is a flat structure: you create a bucket, and the bucket stores objects. There is no hierarchy of subbuckets or subfolders; however, you can infer logical hierarchy using key name prefixes and delimiters as the Amazon S3 console does. The Amazon S3 console supports a concept of folders. Suppose that your bucket (admin-created) has four objects with the following object keys:

Development/Projects1.xls

Finance/statement1.pdf

Private/taxdocument.pdf

s3-dg.pdf

Reference:

AWS S3: Object Keys

Here is some example code that demonstrates how to get the bucket name and the object key.

Example:

import boto3
from pprint import pprint

def main():

    def enumerate_s3():
        s3 = boto3.resource('s3')
        for bucket in s3.buckets.all():
             print("Name: {}".format(bucket.name))
             print("Creation Date: {}".format(bucket.creation_date))
             for object in bucket.objects.all():
                 print("Object: {}".format(object))
                 print("Object bucket_name: {}".format(object.bucket_name))
                 print("Object key: {}".format(object.key))

    enumerate_s3()


if __name__ == '__main__':
    main()

Initialization of an ArrayList in one line

Try with this code line:

Collections.singletonList(provider)

Node.js getaddrinfo ENOTFOUND

I tried it using the request module, and was able to print the body of that page out pretty easily. Unfortunately with the skills I have, I can't help other than that.

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

<VirtualHost *:80>
    ServerName www.YOURDOMAIN.COM
    ServerAlias YOURDOMAIN.COM
    DocumentRoot /var/www/YOURDOMAIN.COM/public_html
    ErrorLog /var/www/YOURDOMAIN.COM/error.log
    CustomLog /var/www/YOURDOMAIN.COM/requests.log combined

    DocumentRoot /var/www/YOURDOMAIN.COM/public_html
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /var/www/YOURDOMAIN.COM/public_html>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

</VirtualHost>

Getting The ASCII Value of a character in a C# string

This example might help you. by using simple casting you can get code behind urdu character.

string str = "?????";
        char ch = ' ';
        int number = 0;
        for (int i = 0; i < str.Length; i++)
        {
            ch = str[i];
            number = (int)ch;
            Console.WriteLine(number);
        }

How to generate and validate a software license key?

The C# / .NET engine we use for licence key generation is now maintained as open source:

https://github.com/appsoftware/.NET-Licence-Key-Generator.

It's based on a "Partial Key Verification" system which means only a subset of the key that you use to generate the key has to be compiled into your distributable. You create the keys your self, so the licence implementation is unique to your software.

As stated above, if your code can be decompiled, it's relatively easy to circumvent most licencing systems.

Difference between $(window).load() and $(document).ready() functions

$(document).ready happens when all the elements are present in the DOM, but not necessarily all content.

$(document).ready(function() {
    alert("document is ready");
});

window.onload or $(window).load() happens after all the content resources (images, etc) have been loaded.

$(window).load(function() {
    alert("window is loaded");
});

How to Git stash pop specific stash in 1.8.3?

As Robert pointed out, quotation marks might do the trick for you:

git stash pop stash@"{1}"

Google Chrome display JSON AJAX response as tree and not as a plain text

Google Chrome now supports this (Developer Tools > Network > [XHR item in list] Preview).

In addition, you can use a third party tool to format the json content. Here's one that presents a tree view, and here's another that merely formats the text (and does validation).

How do I create the small icon next to the website tab for my site?

This is for the icon in the browser (most of the sites omit the type):

<link rel="icon" type="image/vnd.microsoft.icon"
     href="http://example.com/favicon.ico" />

or

<link rel="icon" type="image/png"
     href="http://example.com/image.png" />

or

<link rel="apple-touch-icon"
     href="http://example.com//apple-touch-icon.png">

for the shortcut icon:

<link rel="shortcut icon"
     href="http://example.com/favicon.ico" />

Place them in the <head></head> section.

Edit may 2019 some additional examples from MDN

Reliable method to get machine's MAC address in C#

public static PhysicalAddress GetMacAddress()
{
    var myInterfaceAddress = NetworkInterface.GetAllNetworkInterfaces()
        .Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback)
        .OrderByDescending(n => n.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
        .Select(n => n.GetPhysicalAddress())
        .FirstOrDefault();

    return myInterfaceAddress;
}

What causes java.lang.IncompatibleClassChangeError?

Another situation where this error can appear is with Emma Code Coverage.

This happens when assigning an Object to an interface. I guess this has something to do with the Object being instrumented and not binary compatible anymore.

http://sourceforge.net/tracker/?func=detail&aid=3178921&group_id=177969&atid=883351

Fortunately this problem doesn't happen with Cobertura, so I've added cobertura-maven-plugin in my reporting plugins of my pom.xml

How to show the text on a ImageButton?

you can use a regular Button and the android:drawableTop attribute (or left, right, bottom) instead.

How can I count the number of children?

What if you are using this to determine the current selector to find its children so this holds: <ol> then there is <li>s under how to write a selector var count = $(this+"> li").length; wont work..

Add new field to every document in a MongoDB collection

Since MongoDB version 3.2 you can use updateMany():

> db.yourCollection.updateMany({}, {$set:{"someField": "someValue"}})

How to install popper.js with Bootstrap 4?

npm install bootstrap jquery --save

You don't have to install popper.js with npm as it comes with npm Bootstrap in bootstrap.bundle.js.

Bundled JS files (bootstrap.bundle.js and minified bootstrap.bundle.min.js) include Popper, but not jQuery.

Source to Verify: Link

Now you only have to do this in your HTML file:

<script src="node_modules/jquery/dist/jquery.slim.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>

Loop structure inside gnuplot?

Take a look also to the do { ... } command since gnuplot 4.6 as it is very powerful:

do for [t=0:50] {
  outfile = sprintf('animation/bessel%03.0f.png',t)
  set output outfile
  splot u*sin(v),u*cos(v),bessel(u,t/50.0) w pm3d ls 1
}

http://www.gnuplotting.org/gnuplot-4-6-do/

Private vs Protected - Visibility Good-Practice Concern

I read an article a while ago that talked about locking down every class as much as possible. Make everything final and private unless you have an immediate need to expose some data or functionality to the outside world. It's always easy to expand the scope to be more permissible later on, but not the other way around. First consider making as many things as possible final which will make choosing between private and protected much easier.

  1. Make all classes final unless you need to subclass them right away.
  2. Make all methods final unless you need to subclass and override them right away.
  3. Make all method parameters final unless you need to change them within the body of the method, which is kinda awkward most of the times anyways.

Now if you're left with a final class, then make everything private unless something is absolutely needed by the world - make that public.

If you're left with a class that does have subclass(es), then carefully examine every property and method. First consider if you even want to expose that property/method to subclasses. If you do, then consider whether a subclass can wreak havoc on your object if it messed up the property value or method implementation in the process of overriding. If it's possible, and you want to protect your class' property/method even from subclasses (sounds ironic, I know), then make it private. Otherwise make it protected.

Disclaimer: I don't program much in Java :)

Use sed to replace all backslashes with forward slashes

I had to use [\\] or [/] to be able to make this work, FYI.

awk '!/[\\]/' file > temp && mv temp file

and

awk '!/[/]/' file > temp && mv temp file

I was using awk to remove backlashes and forward slashes from a list.

Jenkins, specifying JAVA_HOME

Using Jenkins 2 (2.3.2 in my case), the right way seems to insert the following into your pipeline file:

env.JAVA_HOME="${tool 'jdk1.8.0_111'}"
env.PATH="${env.JAVA_HOME}/bin:${env.PATH}"

"jdk1.8.0_111" beeing the name of the java configuration initially registered into Jenkins

jQuery UI: Datepicker set year range dropdown to 100 years

You can set the year range using this option per documentation here http://api.jqueryui.com/datepicker/#option-yearRange

yearRange: '1950:2013', // specifying a hard coded year range

or this way

yearRange: "-100:+0", // last hundred years

From the Docs

Default: "c-10:c+10"

The range of years displayed in the year drop-down: either relative to today's year ("-nn:+nn"), relative to the currently selected year ("c-nn:c+nn"), absolute ("nnnn:nnnn"), or combinations of these formats ("nnnn:-nn"). Note that this option only affects what appears in the drop-down, to restrict which dates may be selected use the minDate and/or maxDate options.

Error 5 : Access Denied when starting windows service

I accidentally set my service to run as Local service solution was to switch to Local System

How to run Visual Studio post-build events for debug build only

FYI, you do not need to use goto. The shell IF command can be used with round brackets:

if $(ConfigurationName) == Debug (
  copy "$(TargetDir)myapp.dll" "c:\delivery\bin" /y
  copy "$(TargetDir)myapp.dll.config" "c:\delivery\bin" /y
) ELSE (
  echo "why, Microsoft, why".
)

Including a css file in a blade template?

in your main layout put this in the head at the bottom of everything

@stack('styles')

and in your view put this

@push('styles')

    <link rel="stylesheet" href="{{ asset('css/app.css') }}">

@endpush

basically a placeholder so the links will appear on your main layout, and you can see custom css files on different pages

How do I use select with date condition?

Another feature is between:

Select * from table where date between '2009/01/30' and '2009/03/30'

How to validate an e-mail address in swift?

For anyone who is still looking for an answer to this, please have a look at the following framework;

ATGValidator

It is a rule based validation framework, which handles most of the validations out of box. And top it all, it has form validator which supports validation of multiple textfields at the same time.

For validating an email string, use the following;

"[email protected]".satisfyAll(rules: [StringRegexRule.email]).status

If you want to validate an email from textfield, try below code;

textfield.validationRules = [StringRegexRule.email]
textfield.validationHandler = { result in
    // This block will be executed with relevant result whenever validation is done.
    print(result.status, result.errors)
}
// Below line is to manually trigger validation.
textfield.validateTextField()

If you want to validate it while typing in textfield or when focus is changed to another field, add one of the following lines;

textfield.validateOnInputChange(true)
// or
textfield.validateOnFocusLoss(true)

Please check the readme file at the link for more use cases.

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

Ensure you set SmtpClient.Credentials after calling SmtpClient.UseDefaultCredentials = false.

The order is important as setting SmtpClient.UseDefaultCredentials = false will reset SmtpClient.Credentials to null.

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

You are not currently on a branch. To push the history leading to the current (detached HEAD) state now, use

git push origin HEAD:<name-of-remote-branch>

append option to select menu?

$(document).ready(function(){

    $('#mySelect').append("<option>BMW</option>")

})

Regular Expression for alphanumeric and underscores

There's a lot of verbosity in here, and I'm deeply against it, so, my conclusive answer would be:

/^\w+$/

\w is equivalent to [A-Za-z0-9_], which is pretty much what you want. (unless we introduce unicode to the mix)

Using the + quantifier you'll match one or more characters. If you want to accept an empty string too, use * instead.

How to convert a list of numbers to jsonarray in Python

Use the json module to produce JSON output:

import json

with open(outputfilename, 'wb') as outfile:
    json.dump(row, outfile)

This writes the JSON result directly to the file (replacing any previous content if the file already existed).

If you need the JSON result string in Python itself, use json.dumps() (added s, for 'string'):

json_string = json.dumps(row)

The L is just Python syntax for a long integer value; the json library knows how to handle those values, no L will be written.

Demo string output:

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

Get the current script file name

This might help:

basename($_SERVER['PHP_SELF'])

it will work even if you are using include.

Insertion Sort vs. Selection Sort

Although Time Complexity of selection sort and insertion sort is the same, that is n(n - 1)/2. The average performance insertion sort is better. Tested on my i5 cpu with random 30000 integers, selection sort took 1.5s in average, while insertion sort take 0.6s in average.

Adding a line break in MySQL INSERT INTO text

If you're OK with a SQL command that spreads across multiple lines, then oedo's suggestion is the easiest:

INSERT INTO mytable (myfield) VALUES ('hi this is some text
and this is a linefeed.
and another');

I just had a situation where it was preferable to have the SQL statement all on one line, so I found that a combination of CONCAT_WS() and CHAR() worked for me.

INSERT INTO mytable (myfield) VALUES (CONCAT_WS(CHAR(10 using utf8), 'hi this is some text', 'and this is a linefeed.', 'and another'));

How can I get a Unicode character's code?

For me, only "Integer.toHexString(registered)" worked the way I wanted:

char registered = '®';
System.out.println("Answer:"+Integer.toHexString(registered));

This answer will give you only string representations what are usually presented in the tables. Jon Skeet's answer explains more.

How do I clear the dropdownlist values on button click event using jQuery?

If you want to reset bootstrap page with button click using jQuery :

function resetForm(){
        var validator = $( "#form_ID" ).validate();
        validator.resetForm();
}

Using above code you also have change the field colour as red to normal.

If you want to reset only fielded value then :

$("#form_ID")[0].reset();

How to sort a dataframe by multiple column(s)

Your choices

  • order from base
  • arrange from dplyr
  • setorder and setorderv from data.table
  • arrange from plyr
  • sort from taRifx
  • orderBy from doBy
  • sortData from Deducer

Most of the time you should use the dplyr or data.table solutions, unless having no-dependencies is important, in which case use base::order.


I recently added sort.data.frame to a CRAN package, making it class compatible as discussed here: Best way to create generic/method consistency for sort.data.frame?

Therefore, given the data.frame dd, you can sort as follows:

dd <- data.frame(b = factor(c("Hi", "Med", "Hi", "Low"), 
      levels = c("Low", "Med", "Hi"), ordered = TRUE),
      x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
      z = c(1, 1, 1, 2))
library(taRifx)
sort(dd, f= ~ -z + b )

If you are one of the original authors of this function, please contact me. Discussion as to public domaininess is here: https://chat.stackoverflow.com/transcript/message/1094290#1094290


You can also use the arrange() function from plyr as Hadley pointed out in the above thread:

library(plyr)
arrange(dd,desc(z),b)

Benchmarks: Note that I loaded each package in a new R session since there were a lot of conflicts. In particular loading the doBy package causes sort to return "The following object(s) are masked from 'x (position 17)': b, x, y, z", and loading the Deducer package overwrites sort.data.frame from Kevin Wright or the taRifx package.

#Load each time
dd <- data.frame(b = factor(c("Hi", "Med", "Hi", "Low"), 
      levels = c("Low", "Med", "Hi"), ordered = TRUE),
      x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
      z = c(1, 1, 1, 2))
library(microbenchmark)

# Reload R between benchmarks
microbenchmark(dd[with(dd, order(-z, b)), ] ,
    dd[order(-dd$z, dd$b),],
    times=1000
)

Median times:

dd[with(dd, order(-z, b)), ] 778

dd[order(-dd$z, dd$b),] 788

library(taRifx)
microbenchmark(sort(dd, f= ~-z+b ),times=1000)

Median time: 1,567

library(plyr)
microbenchmark(arrange(dd,desc(z),b),times=1000)

Median time: 862

library(doBy)
microbenchmark(orderBy(~-z+b, data=dd),times=1000)

Median time: 1,694

Note that doBy takes a good bit of time to load the package.

library(Deducer)
microbenchmark(sortData(dd,c("z","b"),increasing= c(FALSE,TRUE)),times=1000)

Couldn't make Deducer load. Needs JGR console.

esort <- function(x, sortvar, ...) {
attach(x)
x <- x[with(x,order(sortvar,...)),]
return(x)
detach(x)
}

microbenchmark(esort(dd, -z, b),times=1000)

Doesn't appear to be compatible with microbenchmark due to the attach/detach.


m <- microbenchmark(
  arrange(dd,desc(z),b),
  sort(dd, f= ~-z+b ),
  dd[with(dd, order(-z, b)), ] ,
  dd[order(-dd$z, dd$b),],
  times=1000
  )

uq <- function(x) { fivenum(x)[4]}  
lq <- function(x) { fivenum(x)[2]}

y_min <- 0 # min(by(m$time,m$expr,lq))
y_max <- max(by(m$time,m$expr,uq)) * 1.05
  
p <- ggplot(m,aes(x=expr,y=time)) + coord_cartesian(ylim = c( y_min , y_max )) 
p + stat_summary(fun.y=median,fun.ymin = lq, fun.ymax = uq, aes(fill=expr))

microbenchmark plot

(lines extend from lower quartile to upper quartile, dot is the median)


Given these results and weighing simplicity vs. speed, I'd have to give the nod to arrange in the plyr package. It has a simple syntax and yet is almost as speedy as the base R commands with their convoluted machinations. Typically brilliant Hadley Wickham work. My only gripe with it is that it breaks the standard R nomenclature where sorting objects get called by sort(object), but I understand why Hadley did it that way due to issues discussed in the question linked above.

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

Replace your query with the following:

$query = mysql_query("INSERT INTO users VALUES('$username','$pass','$email')", `$Connect`);

Can't install nuget package because of "Failed to initialize the PowerShell host"

Remember to restart Visual Studio after you've done the Set-ExecutionPolicy Unrestricted in PowerShell (x86).

If that doesn't work, try Set-ExecutionPolicy RemoteSigned in PowerShell (x86) then restart Visual Studio.

Array.push() and unique items

You have to use === -1, if it equals to -1 i.e. item is not available in your array:

  this.items = [];

  add(item) {
    if(this.items.indexOf(item) === -1) {
      this.items.push(item);
      console.log(this.items);
    }
  }

How do I convert an integer to binary in JavaScript?

function dec2bin(dec){
    return (dec >>> 0).toString(2);
}

dec2bin(1);    // 1
dec2bin(-1);   // 11111111111111111111111111111111
dec2bin(256);  // 100000000
dec2bin(-256); // 11111111111111111111111100000000

You can use Number.toString(2) function, but it has some problems when representing negative numbers. For example, (-1).toString(2) output is "-1".

To fix this issue, you can use the unsigned right shift bitwise operator (>>>) to coerce your number to an unsigned integer.

If you run (-1 >>> 0).toString(2) you will shift your number 0 bits to the right, which doesn't change the number itself but it will be represented as an unsigned integer. The code above will output "11111111111111111111111111111111" correctly.

This question has further explanation.

-3 >>> 0 (right logical shift) coerces its arguments to unsigned integers, which is why you get the 32-bit two's complement representation of -3.

How do I delete rows in a data frame?

Here's a quick and dirty function to remove a row by index.

removeRowByIndex <- function(x, row_index) {
  nr <- nrow(x)
  if (nr < row_index) {
    print('row_index exceeds number of rows')
  } else if (row_index == 1)
  {
    return(x[2:nr, ])
  } else if (row_index == nr) {
    return(x[1:(nr - 1), ])
  } else {
    return (x[c(1:(row_index - 1), (row_index + 1):nr), ])
  }
}

It's main flaw is it the row_index argument doesn't follow the R pattern of being a vector of values. There may be other problems as I only spent a couple of minutes writing and testing it, and have only started using R in the last few weeks. Any comments and improvements on this would be very welcome!

gradient descent using python and numpy

I know this question already have been answer but I have made some update to the GD function :

  ### COST FUNCTION

def cost(theta,X,y):
     ### Evaluate half MSE (Mean square error)
     m = len(y)
     error = np.dot(X,theta) - y
     J = np.sum(error ** 2)/(2*m)
     return J

 cost(theta,X,y)



def GD(X,y,theta,alpha):

    cost_histo = [0]
    theta_histo = [0]

    # an arbitrary gradient, to pass the initial while() check
    delta = [np.repeat(1,len(X))]
    # Initial theta
    old_cost = cost(theta,X,y)

    while (np.max(np.abs(delta)) > 1e-6):
        error = np.dot(X,theta) - y
        delta = np.dot(np.transpose(X),error)/len(y)
        trial_theta = theta - alpha * delta
        trial_cost = cost(trial_theta,X,y)
        while (trial_cost >= old_cost):
            trial_theta = (theta +trial_theta)/2
            trial_cost = cost(trial_theta,X,y)
            cost_histo = cost_histo + trial_cost
            theta_histo = theta_histo +  trial_theta
        old_cost = trial_cost
        theta = trial_theta
    Intercept = theta[0] 
    Slope = theta[1]  
    return [Intercept,Slope]

res = GD(X,y,theta,alpha)

This function reduce the alpha over the iteration making the function too converge faster see Estimating linear regression with Gradient Descent (Steepest Descent) for an example in R. I apply the same logic but in Python.

Find a file in python

If you are working with Python 2 you have a problem with infinite recursion on windows caused by self-referring symlinks.

This script will avoid following those. Note that this is windows-specific!

import os
from scandir import scandir
import ctypes

def is_sym_link(path):
    # http://stackoverflow.com/a/35915819
    FILE_ATTRIBUTE_REPARSE_POINT = 0x0400
    return os.path.isdir(path) and (ctypes.windll.kernel32.GetFileAttributesW(unicode(path)) & FILE_ATTRIBUTE_REPARSE_POINT)

def find(base, filenames):
    hits = []

    def find_in_dir_subdir(direc):
        content = scandir(direc)
        for entry in content:
            if entry.name in filenames:
                hits.append(os.path.join(direc, entry.name))

            elif entry.is_dir() and not is_sym_link(os.path.join(direc, entry.name)):
                try:
                    find_in_dir_subdir(os.path.join(direc, entry.name))
                except UnicodeDecodeError:
                    print "Could not resolve " + os.path.join(direc, entry.name)
                    continue

    if not os.path.exists(base):
        return
    else:
        find_in_dir_subdir(base)

    return hits

It returns a list with all paths that point to files in the filenames list. Usage:

find("C:\\", ["file1.abc", "file2.abc", "file3.abc", "file4.abc", "file5.abc"])

How to pass data between fragments

1- The first way is define an interface

public interface OnMessage{
    void sendMessage(int fragmentId, String message);
}

public interface OnReceive{
    void onReceive(String message);
}

2- In you activity implement OnMessage interface

public class MyActivity implements OnMessage {
   ...
   @Override
   public void sendMessage(int fragmentId, String message){
       Fragment fragment = getSupportFragmentManager().findFragmentById(fragmentId);
       ((OnReceive) fragment).sendMessage();
   }
}

3- In your fragment implement OnReceive interface

public class MyFragment implements OnReceive{
    ...
    @Override
    public void onReceive(String message){
        myTextView.setText("Received message:" + message);
    }
}

This is the boilerplate version of handling message passing between fragments.

Another way of handing data passage between fragments are by using an event bus.

1- Register/unregister to an event bus

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    EventBus.getDefault().unregister(this);
    super.onStop();
}

2- Define an event class

public class Message{
    public final String message;

    public Message(String message){
        this.message = message;
    }
}

3- Post this event in anywhere in your application

EventBus.getDefault().post(new Message("hello world"));

4- Subscribe to that event to receive it in your Fragment

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessage(Message event){
    mytextview.setText(event.message);
}

For more details, use cases, and an example project about the event bus pattern.

How do I get the entity that represents the current user in Symfony2?

$this->container->get('security.token_storage')->getToken()->getUser();

How to access local files of the filesystem in the Android emulator?

In Android Studio 3.5.3, the Device File Explorer can be found in View -> Tool Windows.

It can also be opened using the vertical tabs on the right-hand side of the main window.

How to position one element relative to another with jQuery?

Here is a jQuery function I wrote that helps me position elements.

Here is an example usage:

$(document).ready(function() {
  $('#el1').position('#el2', {
    anchor: ['br', 'tr'],
    offset: [-5, 5]
  });
});

The code above aligns the bottom-right of #el1 with the top-right of #el2. ['cc', 'cc'] would center #el1 in #el2. Make sure that #el1 has the css of position: absolute and z-index: 10000 (or some really large number) to keep it on top.

The offset option allows you to nudge the coordinates by a specified number of pixels.

The source code is below:

jQuery.fn.getBox = function() {
  return {
    left: $(this).offset().left,
    top: $(this).offset().top,
    width: $(this).outerWidth(),
    height: $(this).outerHeight()
  };
}

jQuery.fn.position = function(target, options) {
  var anchorOffsets = {t: 0, l: 0, c: 0.5, b: 1, r: 1};
  var defaults = {
    anchor: ['tl', 'tl'],
    animate: false,
    offset: [0, 0]
  };
  options = $.extend(defaults, options);

  var targetBox = $(target).getBox();
  var sourceBox = $(this).getBox();

  //origin is at the top-left of the target element
  var left = targetBox.left;
  var top = targetBox.top;

  //alignment with respect to source
  top -= anchorOffsets[options.anchor[0].charAt(0)] * sourceBox.height;
  left -= anchorOffsets[options.anchor[0].charAt(1)] * sourceBox.width;

  //alignment with respect to target
  top += anchorOffsets[options.anchor[1].charAt(0)] * targetBox.height;
  left += anchorOffsets[options.anchor[1].charAt(1)] * targetBox.width;

  //add offset to final coordinates
  left += options.offset[0];
  top += options.offset[1];

  $(this).css({
    left: left + 'px',
    top: top + 'px'
  });

}

How can I determine whether a 2D Point is within a Polygon?

This seems to work in R (apologies for ugliness, would like to see better version!).

pnpoly <- function(nvert,vertx,verty,testx,testy){
          c <- FALSE
          j <- nvert 
          for (i in 1:nvert){
              if( ((verty[i]>testy) != (verty[j]>testy)) && 
   (testx < (vertx[j]-vertx[i])*(testy-verty[i])/(verty[j]-verty[i])+vertx[i]))
            {c <- !c}
             j <- i}
   return(c)}

Passing multiple values to a single PowerShell script parameter

One way to do it would be like this:

 param(
       [Parameter(Position=0)][String]$Vlan,
       [Parameter(ValueFromRemainingArguments=$true)][String[]]$Hosts
    ) ...

This would allow multiple hosts to be entered with spaces.

CSS background-image not working

I have tried your code and found that if we put background-image: url(image.png); in btn-pToolName and change color:#000000. it displays the image at background.

my test css:

           .btn-pTool {
                margin: 0;
                padding: 0;
            }

            .btn-pToolName {
                text-align: center;
                width: 26px;
                height: 190px;
                display: block;
                color: #000000;
                text-decoration: none;
                font-family: Arial, Helvetica, sans-serif;
                font-weight: bold;
                font-size: 1em;
                line-height: 32px;
                background-image: url(defalut.png);
                background-repeat: no-repeat;
            }

and test html:

        <div class="pToolContainer">
            <span class="btn-pTool"><a class="btn-pToolName" href="#">adad</a></span>
            <div class="pToolSlidePanel"></div>
        </div>

Hope this helps.

What is the difference between JavaScript and jQuery?

Javascript is base of jQuery.

jQuery is a wrapper of JavaScript, with much pre-written functionality and DOM traversing.

Sorting Python list based on the length of the string

Write a function lensort to sort a list of strings based on length.

def lensort(a):
    n = len(a)
    for i in range(n):
        for j in range(i+1,n):
            if len(a[i]) > len(a[j]):
                temp = a[i]
                a[i] = a[j]
                a[j] = temp
    return a
print lensort(["hello","bye","good"])

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

you must be using old version of wget i had same issue. i was using wget 1.12.so to solve this issue there are 2 way: Update wget or use curl

curl -LO 'https://example.com/filename.tar.gz'

Preventing an image from being draggable or selectable without using JS

Depending on the situation, it is often helpful to make the image a background image of a div with CSS.

<div id='my-image'></div>

Then in CSS:

#my-image {
    background-image: url('/img/foo.png');
    width: ???px;
    height: ???px;
}

See this JSFiddle for a live example with a button and a different sizing option.

How to Kill A Session or Session ID (ASP.NET/C#)

Session.Abandon(); did not work for me either.

The way I had to write it to get it to work was like this. Might work for you too.

HttpContext.Current.Session.Abandon();

How can I pass variable to ansible playbook in the command line?

Reading the docs I find the section Passing Variables On The Command Line, that gives this example:

ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo"

Others examples demonstrate how to load from JSON string (=1.2) or file (=1.3)

ImportError: No module named request

You can do that using Python 2.

  1. Remove request
  2. Make that line: from urllib2 import urlopen

You cannot have request in Python 2, you need to have Python 3 or above.

array.select() in javascript

There's also Array.find() in ES6 which returns the first matching element it finds.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

const myArray = [1, 2, 3]

const myElement = myArray.find((element) => element === 2)

console.log(myElement)
// => 2

Convert timestamp to date in Oracle SQL

CAST(timestamp_expression AS DATE)

For example, The query is : SELECT CAST(SYSTIMESTAMP AS DATE) FROM dual;

C++ pass an array by reference

Arrays can only be passed by reference, actually:

void foo(double (&bar)[10])
{
}

This prevents you from doing things like:

double arr[20];
foo(arr); // won't compile

To be able to pass an arbitrary size array to foo, make it a template and capture the size of the array at compile time:

template<typename T, size_t N>
void foo(T (&bar)[N])
{
    // use N here
}

You should seriously consider using std::vector, or if you have a compiler that supports c++11, std::array.

Ruby optional parameters

1) You cannot overload the method (Why doesn't ruby support method overloading?) so why not write a new method altogether?

2) I solved a similar problem using the splat operator * for an array of zero or more length. Then, if I want to pass a parameter(s) I can, it is interpreted as an array, but if I want to call the method without any parameter then I don't have to pass anything. See Ruby Programming Language pages 186/187

How to clear Route Caching on server: Laravel 5.2.37

you can define a route in web.php

Route::get('/clear/route', 'ConfigController@clearRoute');

and make ConfigController.php like this

   class ConfigController extends Controller
{
    public function clearRoute()
    {
        \Artisan::call('route:clear');
    }
}

and go to that route on server example http://your-domain/clear/route

Convert Text to Date?

I had a very similar issue earlier. Unfortunately I looked at this thread and didn't find an answer which I was happy with. Hopefully this will help others.

Using VBA.DateSerial(year,month,day) you can overcome Excel's intrinsic bias to US date format. It also means you have full control over the data, which is something I personally prefer:

function convDate(str as string) as Date
  Dim day, month, year as integer
  year  = int(mid(str,1,4))
  month = int(mid(str,6,2))
  day   = int(mid(str,9,2))
  convDate = VBA.DateSerial(year,month,day)
end function

Setting query string using Fetch GET request

Solution without external packages

to perform a GET request using the fetch api I worked on this solution that doesn't require the installation of packages.

this is an example of a call to the google's map api

// encode to scape spaces
const esc = encodeURIComponent;
const url = 'https://maps.googleapis.com/maps/api/geocode/json?';
const params = { 
    key: "asdkfñlaskdGE",
    address: "evergreen avenue",
    city: "New York"
};
// this line takes the params object and builds the query string
const query = Object.keys(params).map(k => `${esc(k)}=${esc(params[k])}`).join('&')
const res = await fetch(url+query);
const googleResponse = await res.json()

feel free to copy this code and paste it on the console to see how it works!!

the generated url is something like:

https://maps.googleapis.com/maps/api/geocode/json?key=asdkf%C3%B1laskdGE&address=evergreen%20avenue&city=New%20York

this is what I was looking before I decided to write this, enjoy :D

How to write log base(2) in c/c++

uint16_t log2(uint32_t n) {//but truncated
     if (n==0) throw ...
     uint16_t logValue = -1;
     while (n) {//
         logValue++;
         n >>= 1;
     }
     return logValue;
 }

Basically the same as tomlogic's.

Can you animate a height change on a UITableViewCell when selected?

Swift version of Simon Lee's answer:

tableView.beginUpdates()
tableView.endUpdates()

Keep in mind that you should modify the height properties BEFORE endUpdates().

How to use adb command to push a file on device without sd card

My solution (example with a random mp4 video file):

  1. Set a file to device:

    adb push /home/myuser/myVideoFile.mp4 /storage/emulated/legacy/
    
  2. Get a file from device:

    adb pull /storage/emulated/legacy/myVideoFile.mp4 
    

For retrieve the path in the code:

String myFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myVideoFile.mp4";

This is all. This solution doesn't give permission problems and it works fine.

Last point: I wanted to change the video metadata information. If you want to write into your device you should change the permission in the AndroidManifest.xml. Add this line:

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

how to insert value into DataGridView Cell?

For Some Reason I could Not add Numbers(in string Format) to the DataGridView But This Worked For Me Hope it help someone!

//dataGridView1.Rows[RowCount].Cells[0].Value = FEString3;//This was not adding Stringed Numbers like "1","2","3"....
DataGridViewCell NewCell = new DataGridViewTextBoxCell();//Create New Cell
NewCell.Value = FEString3;//Set Cell Value
DataGridViewRow NewRow = new DataGridViewRow();//Create New Row
NewRow.Cells.Add(NewCell);//Add Cell to Row
dataGridView1.Rows.Add(NewRow);//Add Row To Datagrid

Switch case in C# - a constant value is expected

switch is very picky in the sense that the values in the switch must be a compile time constant. and also the value that's being compared must be a primitive (or string now). For this you should use an if statement.

The reason may go back to the way that C handles them in that it creates a jump table (because the values are compile time constants) and it tries to copy the same semantics by not allowing evaluated values in your cases.

Extract time from moment js object

You can do something like this

var now = moment();
var time = now.hour() + ':' + now.minutes() + ':' + now.seconds();
time = time + ((now.hour()) >= 12 ? ' PM' : ' AM');

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

This is reviving an old question, but in Python 3, you can just use bytes directly:

>>> bytes([17, 24, 121, 1, 12, 222, 34, 76])
b'\x11\x18y\x01\x0c\xde"L'

Mvn install or Mvn package

mvn install is the option that is most often used.
mvn package is seldom used, only if you're debugging some issue with the maven build process.

See: http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html

Note that mvn package will only create a jar file.
mvn install will do that and install the jar (and class etc.) files in the proper places if other code depends on those jars.

I usually do a mvn clean install; this deletes the target directory and recreates all jars in that location.
The clean helps with unneeded or removed stuff that can sometimes get in the way.
Rather then debug (some of the time) just start fresh all of the time.

How do I connect to this localhost from another computer on the same network?

If you are on Windows, use ipconfig to get the local IPv4 address, and then specify that under your Apache configuration file: httpd.conf, like:

Listen: 10.20.30.40:80

Restart your Apache server and test it from other computer on the network.

Removing all line breaks and adding them after certain text

I have achieved this with following
Edit > Blank Operations > Remove Unnecessary Blank and EOL

How can I do a BEFORE UPDATED trigger with sql server?

All "normal" triggers in SQL Server are "AFTER ..." triggers. There are no "BEFORE ..." triggers.

To do something before an update, check out INSTEAD OF UPDATE Triggers.

git - Server host key not cached

Had the same issue, and forget to connect to SSH on port where is actuall repository, not just general SSH port, then the host key is different!

How do I convert from a money datatype in SQL server?

I found this approach direct and useful.

CONVERT(VARCHAR(10), CONVERT(MONEY, fieldname)) AS PRICE

SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel

You have configured the auth.php and used members table for authentication but there is no user_email field in the members table so, Laravel says

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_email' in 'where clause' (SQL: select * from members where user_email = ? limit 1) (Bindings: array ( 0 => '[email protected]', ))

Because, it tries to match the user_email in the members table and it's not there. According to your auth configuration, laravel is using members table for authentication not users table.

Using IQueryable with Linq

Marc Gravell's answer is very complete, but I thought I'd add something about this from the user's point of view, as well...


The main difference, from a user's perspective, is that, when you use IQueryable<T> (with a provider that supports things correctly), you can save a lot of resources.

For example, if you're working against a remote database, with many ORM systems, you have the option of fetching data from a table in two ways, one which returns IEnumerable<T>, and one which returns an IQueryable<T>. Say, for example, you have a Products table, and you want to get all of the products whose cost is >$25.

If you do:

 IEnumerable<Product> products = myORM.GetProducts();
 var productsOver25 = products.Where(p => p.Cost >= 25.00);

What happens here, is the database loads all of the products, and passes them across the wire to your program. Your program then filters the data. In essence, the database does a SELECT * FROM Products, and returns EVERY product to you.

With the right IQueryable<T> provider, on the other hand, you can do:

 IQueryable<Product> products = myORM.GetQueryableProducts();
 var productsOver25 = products.Where(p => p.Cost >= 25.00);

The code looks the same, but the difference here is that the SQL executed will be SELECT * FROM Products WHERE Cost >= 25.

From your POV as a developer, this looks the same. However, from a performance standpoint, you may only return 2 records across the network instead of 20,000....

Measuring elapsed time with the Time module

time.time() will do the job.

import time

start = time.time()
# run your code
end = time.time()

elapsed = end - start

You may want to look at this question, but I don't think it will be necessary.

How to check if IEnumerable is null or empty?

Take a look at this opensource library: Nzr.ToolBox

public static bool IsEmpty(this System.Collections.IEnumerable enumerable)

Verilog: How to instantiate a module

Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.

An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto and can afterwards be manually edited.

subcomponent subcomponent_instance_name(/*AUTOINST*/);

Expanded

subcomponent subcomponent_instance_name (/*AUTOINST*/
  //Inputs
  .clk,         (clk)           
  .rst_n,       (rst_n)
  .data_rx      (data_rx_1[9:0]),
  //Outputs
  .data_tx      (data_tx[9:0])
);

Implicit wires can be automated with /*AUTOWIRE*/. Check the link for further information.

Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded

As "there are tens of thousands of cells in the page" binding the click-event to every single cell will cause a terrible performance problem. There's a better way to do this, that is binding a click event to the body & then finding out if the cell element was the target of the click. Like this:

$('body').click(function(e){
       var Elem = e.target;
       if (Elem.nodeName=='td'){
           //.... your business goes here....
           // remember to replace $(this) with $(Elem)
       }
})

This method will not only do your task with native "td" tag but also with later appended "td". I think you'll be interested in this article about event binding & delegate


Or you can simply use the ".on()" method of jQuery with the same effect:

$('body').on('click', 'td', function(){
        ...
});

HTML 5 video recording and storing a stream

MediaRecorder API is the solution you are looking for,

Firefox has been supporting it for some time now, and the buzz is is Chrome is gonna implement it in its next release (Chrome 48), but guess you still might need to enable the experimental flag, apparently the flag won't be need from Chrome version 49, for more info check out this Chrome issue.

Meanwhile, a sample of how to do it in Firefox:

_x000D_
_x000D_
var video, reqBtn, startBtn, stopBtn, ul, stream, recorder;
video = document.getElementById('video');
reqBtn = document.getElementById('request');
startBtn = document.getElementById('start');
stopBtn = document.getElementById('stop');
ul = document.getElementById('ul');
reqBtn.onclick = requestVideo;
startBtn.onclick = startRecording;
stopBtn.onclick = stopRecording;
startBtn.disabled = true;
ul.style.display = 'none';
stopBtn.disabled = true;

function requestVideo() {
  navigator.mediaDevices.getUserMedia({
      video: true,
      audio: true
    })
    .then(stm => {
      stream = stm;
      reqBtn.style.display = 'none';
      startBtn.removeAttribute('disabled');
      video.src = URL.createObjectURL(stream);
    }).catch(e => console.error(e));
}

function startRecording() {
  recorder = new MediaRecorder(stream, {
    mimeType: 'video/mp4'
  });
  recorder.start();
  stopBtn.removeAttribute('disabled');
  startBtn.disabled = true;
}


function stopRecording() {
  recorder.ondataavailable = e => {
    ul.style.display = 'block';
    var a = document.createElement('a'),
      li = document.createElement('li');
    a.download = ['video_', (new Date() + '').slice(4, 28), '.webm'].join('');
    a.href = URL.createObjectURL(e.data);
    a.textContent = a.download;
    li.appendChild(a);
    ul.appendChild(li);
  };
  recorder.stop();
  startBtn.removeAttribute('disabled');
  stopBtn.disabled = true;
}
_x000D_
<div>

  <button id='request'>
    Request Camera
  </button>
  <button id='start'>
    Start Recording
  </button>
  <button id='stop'>
    Stop Recording
  </button>
  <ul id='ul'>
    Downloads List:
  </ul>

</div>
<video id='video' autoplay></video>
_x000D_
_x000D_
_x000D_

Swap two variables without using a temporary variable

C# 7 introduced tuples which enables swapping two variables without a temporary one:

int a = 10;
int b = 2;
(a, b) = (b, a);

This assigns b to a and a to b.

Javascript: How to remove the last character from a div or a string?

$('#mainn').text(function (_,txt) {
    return txt.slice(0, -1);
});

demo --> http://jsfiddle.net/d72ML/8/

Call to undefined function curl_init().?

You have to enable curl with php.

Here is the instructions for same

How do I use namespaces with TypeScript external modules?

Nothing wrong with Ryan's answer, but for people who came here looking for how to maintain a one-class-per-file structure while still using ES6 namespaces correctly please refer to this helpful resource from Microsoft.

One thing that's unclear to me after reading the doc is: how to import the entire (merged) module with a single import.

Edit Circling back to update this answer. A few approaches to namespacing emerge in TS.

All module classes in one file.

export namespace Shapes {
    export class Triangle {}
    export class Square {}      
}

Import files into namespace, and reassign

import { Triangle as _Triangle } from './triangle';
import { Square as _Square } from './square';

export namespace Shapes {
  export const Triangle = _Triangle;
  export const Square = _Square;
}

Barrels

// ./shapes/index.ts
export { Triangle } from './triangle';
export { Square } from './square';

// in importing file:
import * as Shapes from './shapes/index.ts';
// by node module convention, you can ignore '/index.ts':
import * as Shapes from './shapes';
let myTriangle = new Shapes.Triangle();

A final consideration. You could namespace each file

// triangle.ts
export namespace Shapes {
    export class Triangle {}
}

// square.ts
export namespace Shapes {
    export class Square {}
}

But as one imports two classes from the same namespace, TS will complain there's a duplicate identifier. The only solution as this time is to then alias the namespace.

import { Shapes } from './square';
import { Shapes as _Shapes } from './triangle';

// ugh
let myTriangle = new _Shapes.Shapes.Triangle();

This aliasing is absolutely abhorrent, so don't do it. You're better off with an approach above. Personally, I prefer the 'barrel'.

How to enumerate an object's properties in Python?

If you're looking for reflection of all properties, the answers above are great.

If you're simply looking to get the keys of a dictionary (which is different from an 'object' in Python), use

my_dict.keys()

my_dict = {'abc': {}, 'def': 12, 'ghi': 'string' }
my_dict.keys() 
> ['abc', 'def', 'ghi']

Python: SyntaxError: non-keyword after keyword arg

To really get this clear, here's my for-beginners answer: You inputed the arguments in the wrong order.
A keyword argument has this style:

nullable=True, unique=False

A fixed parameter should be defined: True, False, etc. A non-keyword argument is different:

name="Ricardo", fruit="chontaduro" 

This syntax error asks you to first put name="Ricardo" and all of its kind (non-keyword) before those like nullable=True.

How Stuff and 'For Xml Path' work in SQL Server?

SELECT ID, 
    abc = STUFF(
                 (SELECT ',' + name FROM temp1 FOR XML PATH ('')), 1, 1, ''
               ) 
FROM temp1 GROUP BY id

Here in the above query STUFF function is used to just remove the first comma (,) from the generated xml string (,aaa,bbb,ccc,ddd,eee) then it will become (aaa,bbb,ccc,ddd,eee).

And FOR XML PATH('') simply converts column data into (,aaa,bbb,ccc,ddd,eee) string but in PATH we are passing '' so it will not create a XML tag.

And at the end we have grouped records using ID column.

MYSQL Sum Query with IF Condition

Try with a CASE in this way :

SUM(CASE 
    WHEN PaymentType = "credit card" 
    THEN TotalAmount 
    ELSE 0 
END) AS CreditCardTotal,

Should give what you are looking for ...

Make Adobe fonts work with CSS3 @font-face in IE9

I can only explain you how to fix the "CSS3114" error.
You have to change the embedding level of your TTF file.

Using the appropriate tool you can set it to installable embedding allowed.
For a 64-bit version, check @user22600's answer.

Remove Last Comma from a string

long shot here

var sentence="I got,. commas, here,";
var pattern=/,/g;
var currentIndex;
while (pattern.test(sentence)==true)  {    
  currentIndex=pattern.lastIndex;
 }
if(currentIndex==sentence.trim().length)
alert(sentence.substring(0,currentIndex-1));
else
 alert(sentence);

How to save a list as numpy array in python?

I suppose, you mean converting a list into a numpy array? Then,

import numpy as np

# b is some list, then ...    
a = np.array(b).reshape(lengthDim0, lengthDim1);

gives you a as an array of list b in the shape given in reshape.

Android: Go back to previous activity

Just try this in, first activity

Intent mainIntent = new Intent(Activity1.this, Activity2.class);
this.startActivity(mainIntent);

In your second activity

@Override
public void onBackPressed() {
    this.finish();
}

How to programmatically send SMS on the iPhone?

Here is a tutorial which does exactly what you are looking for: the MFMessageComposeViewController.

http://blog.mugunthkumar.com/coding/iphone-tutorial-how-to-send-in-app-sms/

Essentially:

MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
    controller.body = @"SMS message here";
    controller.recipients = [NSArray arrayWithObjects:@"1(234)567-8910", nil];
    controller.messageComposeDelegate = self;
    [self presentModalViewController:controller animated:YES];
}

And a link to the docs.

https://developer.apple.com/documentation/messageui/mfmessagecomposeviewcontroller

Interesting 'takes exactly 1 argument (2 given)' Python error

If a non-static method is member of a class, you have to define it like that:

def Method(self, atributes..)

So, I suppose your 'e' is instance of some class with implemented method that tries to execute and has too much arguments.

Pass array to where in Codeigniter Active Record

Use where_in()

$ids = array('20', '15', '22', '46', '86');
$this->db->where_in('id', $ids );

How to get the list of all printers in computer

If you are working with MVC C#, this is the way to deal with printers and serial ports for dropdowns.

using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;
using System.Drawing.Printing;

    public class Miclass
    {
        private void AllViews()
        {
            List<PortClass> ports = new List<PortClass>();
            List<Printersclass> Printersfor = new List<Printersclass>();
            string[] portnames = SerialPort.GetPortNames();
            /*PORTS*/
            for (int i = 0; i < portnames.Count(); i++)
            {
                ports.Add(new PortClass() { Name = portnames[i].Trim(), Desc = portnames[i].Trim() });
            }
            /*PRINTER*/
            for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
            {
                Printersfor.Add(new Printersclass() { Name = PrinterSettings.InstalledPrinters[i].Trim(), Desc = PrinterSettings.InstalledPrinters[i].Trim() });
            }
        }
    }
    public class PortClass
    {
        public string Name { get; set; }
        public string Desc { get; set; }

        public override string ToString()
        {
            return string.Format("{0} ({1})", Name, Desc);
        }
    }
    public class Printersclass
    {
        public string Name { get; set; }
        public string Desc { get; set; }

        public override string ToString()
        {
            return string.Format("{0} ({1})", Name, Desc);
        }
    }

MVC Redirect to View from jQuery with parameters

redirect with query string

 $('#results').on('click', '.item', function () {
                    var NestId = $(this).data('id');
                   // var url = '@Url.Action("Details", "Artists",new { NestId = '+NestId+'  })'; 
                    var url = '@ Url.Content("~/Artists/Details?NestId =' + NestId + '")'
                    window.location.href = url; 
                })

Counting number of characters in a file through shell script

I would have thought that it would be better to use stat to find the size of a file, since the filesystem knows it already, rather than causing the whole file to have to be read with awk or wc - especially if it is a multi-GB file or one that may be non-resident in the file-system on an HSM.

stat -c%s file

Yes, I concede it doesn't account for multi-byte characters, but would add that the OP has never clarified whether that is/was an issue.

Why extend the Android Application class?

Offhand, I can't think of a real scenario in which extending Application is either preferable to another approach or necessary to accomplish something. If you have an expensive, frequently used object you can initialize it in an IntentService when you detect that the object isn't currently present. Application itself runs on the UI thread, while IntentService runs on its own thread.

I prefer to pass data from Activity to Activity with explicit Intents, or use SharedPreferences. There are also ways to pass data from a Fragment to its parent Activity using interfaces.

How do I set response headers in Flask?

This work for me

from flask import Flask
from flask import Response

app = Flask(__name__)

@app.route("/")
def home():
    return Response(headers={'Access-Control-Allow-Origin':'*'})

if __name__ == "__main__":
    app.run()

Error Handler - Exit Sub vs. End Sub

Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.

If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.

How to strip HTML tags with jQuery?

You can use the existing split function

One easy and choppy exemple:

var str = '<p> example ive got a string</P>';
var substr = str.split('<p> ');
// substr[0] contains ""
// substr[1] contains "example ive got a string</P>"
var substr2 = substr [1].split('</p>');
// substr2[0] contains "example ive got a string"
// substr2[1] contains ""

The example is just to show you how the split works.

Rails: How do I create a default value for attributes in Rails activerecord's model?

I found a better way to do it now:

def status=(value) 
  self[:status] = 'P' 
end 

In Ruby a method call is allowed to have no parentheses, therefore I should name the local variable into something else, otherwise Ruby will recognize it as a method call.

Karma: Running a single test file from command line

Even though --files is no longer supported, you can use an env variable to provide a list of files:

// karma.conf.js
function getSpecs(specList) {
  if (specList) {
    return specList.split(',')
  } else {
    return ['**/*_spec.js'] // whatever your default glob is
  }
}

module.exports = function(config) {
  config.set({
    //...
    files: ['app.js'].concat(getSpecs(process.env.KARMA_SPECS))
  });
});

Then in CLI:

$ env KARMA_SPECS="spec1.js,spec2.js" karma start karma.conf.js --single-run

R solve:system is exactly singular

Lapack is a Linear Algebra package which is used by R (actually it's used everywhere) underneath solve(), dgesv spits this kind of error when the matrix you passed as a parameter is singular.

As an addendum: dgesv performs LU decomposition, which, when using your matrix, forces a division by 0, since this is ill-defined, it throws this error. This only happens when matrix is singular or when it's singular on your machine (due to approximation you can have a really small number be considered 0)

I'd suggest you check its determinant if the matrix you're using contains mostly integers and is not big. If it's big, then take a look at this link.

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

In SQL, is UPDATE always faster than DELETE+INSERT?

Just tried updating 43 fields on a table with 44 fields, the remaining field was the primary clustered key.

The update took 8 seconds.

A Delete + Insert is faster than the minimum time interval that the "Client Statistics" reports via SQL Management Studio.

Peter

MS SQL 2008

Android Studio and android.support.v4.app.Fragment: cannot resolve symbol

I encountered this issue and tried everything including File > Invalidate Caches but nothing worked. The reason this issue was happening for me was because I had external projects that were using a different AppCompat version to my main gradle file.

After I updated all gradle files to be the same version the compile error went away.

Git push won't do anything (everything up-to-date)

git push doesn't push all of your local branches: how would it know which remote branches to push them to? It only pushes local branches which have been configured to push to a particular remote branch.

On my version of Git (1.6.5.3), when I run git remote show origin it actually prints out which branches are configured for push:

Local refs configured for 'git push':
  master pushes to master (up to date)
  quux   pushes to quux   (fast forwardable)

Q. But I could push to master without worrying about all this!

When you git clone, by default it sets up your local master branch to push to the remote's master branch (locally referred to as origin/master), so if you only commit on master, then a simple git push will always push your changes back.

However, from the output snippet you posted, you're on a branch called develop, which I'm guessing hasn't been set up to push to anything. So git push without arguments won't push commits on that branch.

When it says "Everything up-to-date", it means "all the branches you've told me how to push are up to date".

Q. So how can I push my commits?

If what you want to do is put your changes from develop into origin/master, then you should probably merge them into your local master then push that:

git checkout master
git merge develop
git push             # will push 'master'

If what you want is to create a develop branch on the remote, separate from master, then supply arguments to git push:

git push origin develop

That will: create a new branch on the remote called develop; and bring that branch up to date with your local develop branch; and set develop to push to origin/develop so that in future, git push without arguments will push develop automatically.

If you want to push your local develop to a remote branch called something other than develop, then you can say:

git push origin develop:something-else

However, that form won't set up develop to always push to origin/something-else in future; it's a one-shot operation.

Why is SQL Server 2008 Management Studio Intellisense not working?

Same problem, but just re-installing SQL Management Studio 2008 R2 Service Pack 1 worked for me. I left my DB engine alone. The DB engine is not the problem, just SQL Management Studio getting hosed by Visual Studio SP1.

Installers here...

http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=26727

I installed SQLManagementStudio_x86_ENU.exe (32 bit for my machine).

bootstrap datepicker today as default

According to this link Set default date of jquery datepicker, the other solution is

var d = new Date();

var currDate = d.getDate();
var currMonth = d.getMonth();
var currYear = d.getFullYear();

var dateStr = currDate + "-" + currMonth + "-" + currYear;

$("#datepicker").datepicker(({dateFormat: "dd-mm-yy" autoclose: true, defaultDate: dateStr });

How to change the color of a CheckBox?

Add this line in your styles.xml file:

<style>
    <item name="android:colorAccent">@android:color/holo_green_dark</item>
</style>

Day Name from Date in JS

use the Date.toLocaleString() method :

new Date(dateString).toLocaleString('en-us', {weekday:'long'})

Converting from byte to int in java

Bytes are transparently converted to ints.

Just say

int i= rno[0];

Setting width and height

You can override the canvas style width !important ...

canvas{

  width:1000px !important;
  height:600px !important;

}

also

specify responsive:true, property under options..

options: {
    responsive: true,
    maintainAspectRatio: false,
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero:true
            }
        }]
    }
}

update under options added : maintainAspectRatio: false,

link : http://codepen.io/theConstructor/pen/KMpqvo

Auto start node.js server on boot

I would recommend installing your node.js app as a Windows service, and then set the service to run at startup. That should make it a bit easier to control the startup action by using the Windows Services snapin rather than having to add or remove batch files in the Startup folder.

Another service-related question in Stackoverflow provided a couple of (apprently) really good options. Check out How to install node.js as a Windows Service. node-windows looks really promising to me. As an aside, I used similar tools for Java apps that needed to run as services. It made my life a whole lot easier. Hope this helps.

How to apply bold text style for an entire row using Apache POI?

This should work fine.

    Workbook wb = new XSSFWorkbook("myWorkbook.xlsx");
    Row row=sheet.getRow(0);
    CellStyle style=null;

    XSSFFont defaultFont= wb.createFont();
    defaultFont.setFontHeightInPoints((short)10);
    defaultFont.setFontName("Arial");
    defaultFont.setColor(IndexedColors.BLACK.getIndex());
    defaultFont.setBold(false);
    defaultFont.setItalic(false);

    XSSFFont font= wb.createFont();
    font.setFontHeightInPoints((short)10);
    font.setFontName("Arial");
    font.setColor(IndexedColors.WHITE.getIndex());
    font.setBold(true);
    font.setItalic(false);

    style=row.getRowStyle();
    style.setFillBackgroundColor(IndexedColors.DARK_BLUE.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFont(font);

If you do not create defaultFont all your workbook will be using the other one as default.

React onClick function fires on render

Because you are calling that function instead of passing the function to onClick, change that line to this:

<button type="submit" onClick={() => { this.props.removeTaskFunction(todo) }}>Submit</button>

=> called Arrow Function, which was introduced in ES6, and will be supported on React 0.13.3 or upper.

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I had the same problem, but with small difference. I had added NetworkConnectionCallback to check situation when internet connection had changed at runtime, and checking like this before sending all requests:

private fun isConnected(): Boolean {
    val activeNetwork = cManager.activeNetworkInfo
    return activeNetwork != null && activeNetwork.isConnected
}

There can be state like CONNECTING (you can see i? when you turn on wifi, icon starts blinking, after connecting to network, image is static). So, we have two different states: one CONNECT another CONNECTING, and when Retrofit tried to send request internet connection is disabled and it throws UnknownHostException. I forgot to add another type of exception in function which was responsible for sending requests.

try{
//for example, retrofit call
}
catch (e: Exception) {
        is UnknownHostException -> "Unknown host!"
        is ConnectException -> "No internet!"
        else -> "Unknown exception!"
    }

It's just a tricky moment that can by related with this problem.

Hope, I will help somebody)

navbar color in Twitter Bootstrap

You can download a custom version of bootstrap and set @navbarBackground to the color you want.

http://twitter.github.com/bootstrap/customize.html

Getting vertical gridlines to appear in line plot in matplotlib

According to matplotlib documentation, The signature of the Axes class grid() method is as follows:

Axes.grid(b=None, which='major', axis='both', **kwargs)
Turn the axes grids on or off.

which can be ‘major’ (default), ‘minor’, or ‘both’ to control whether major tick grids, minor tick grids, or both are affected.

axis can be ‘both’ (default), ‘x’, or ‘y’ to control which set of gridlines are drawn.

So in order to show grid lines for both the x axis and y axis, we can use the the following code:

ax = plt.gca()
ax.grid(which='major', axis='both', linestyle='--')

This method gives us finer control over what to show for grid lines.

What does (function($) {})(jQuery); mean?

Type 3, in order to work would have to look like this:

(function($){
    //Attach this new method to jQuery
    $.fn.extend({     
        //This is where you write your plugin's name
        'pluginname': function(_options) {
            // Put defaults inline, no need for another variable...
            var options =  $.extend({
                'defaults': "go here..."
            }, _options);

            //Iterate over the current set of matched elements
            return this.each(function() {

                //code to be inserted here

            });
        }
    }); 
})(jQuery);

I am unsure why someone would use extend over just directly setting the property in the jQuery prototype, it is doing the same exact thing only in more operations and more clutter.

How to change the href for a hyperlink using jQuery

href in an attribute, so you can change it using pure JavaScript, but if you already have jQuery injected in your page, don't worry, I will show it both ways:

Imagine you have this href below:

<a id="ali" alt="Ali" href="http://dezfoolian.com.au">Alireza Dezfoolian</a>

And you like to change it the link...

Using pure JavaScript without any library you can do:

document.getElementById("ali").setAttribute("href", "https://stackoverflow.com");

But also in jQuery you can do:

$("#ali").attr("href", "https://stackoverflow.com");

or

$("#ali").prop("href", "https://stackoverflow.com");

In this case, if you already have jQuery injected, probably jQuery one look shorter and more cross-browser...but other than that I go with the JS one...

CSS3 Transition not working

If you have a <script> tag anywhere on your page (even in the HTML, even if it is an empty tag with a src), then a transition must be activated by some event (it won't fire automatically when the page loads).

AngularJS check if form is valid in controller

The BusinessCtrl is initialised before the createBusinessForm's FormController. Even if you have the ngController on the form won't work the way you wanted. You can't help this (you can create your ngControllerDirective, and try to trick the priority.) this is how angularjs works.

See this plnkr for example: http://plnkr.co/edit/WYyu3raWQHkJ7XQzpDtY?p=preview

What is the difference between JavaScript and ECMAScript?

Various JavaScript versions are implementations of the ECMAScript standard.

CodeIgniter: Create new helper?

Well for me only works adding the text "_helper" after in the php file like:

Codeiginiter Helpers

And to load automatically the helper in the folder aplication -> file autoload.php add in the array helper's the name without "_helper" like:

$autoload['helper'] = array('comunes');

And with that I can use all the helper's functions

What Regex would capture everything from ' mark to the end of a line?

'.*$

Starting with a single quote ('), match any character (.) zero or more times (*) until the end of the line ($).

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

Is there a macro to conditionally copy rows to another worksheet?

If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?

How do I get my Maven Integration tests to run

You can split them very easily using JUnit categories and Maven.
This is shown very, very briefly below by splitting unit and integration tests.

Define A Marker Interface

The first step in grouping a test using categories is to create a marker interface.
This interface will be used to mark all of the tests that you want to be run as integration tests.

public interface IntegrationTest {}

Mark your test classes

Add the category annotation to the top of your test class. It takes the name of your new interface.

import org.junit.experimental.categories.Category;

@Category(IntegrationTest.class)
public class ExampleIntegrationTest{

    @Test
    public void longRunningServiceTest() throws Exception {
    }

}

Configure Maven Unit Tests

The beauty of this solution is that nothing really changes for the unit test side of things.
We simply add some configuration to the maven surefire plugin to make it to ignore any integration tests.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.11</version>
    <configuration>
        <includes>
            <include>**/*.class</include>
        </includes>
        <excludedGroups>
            com.test.annotation.type.IntegrationTest
        </excludedGroups>
    </configuration>
</plugin>

When you do a mvn clean test, only your unmarked unit tests will run.

Configure Maven Integration Tests

Again the configuration for this is very simple.
We use the standard failsafe plugin and configure it to only run the integration tests.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
        <includes>
            <include>**/*.class</include>
        </includes>
        <groups>
            com.test.annotation.type.IntegrationTest
        </groups>
    </configuration>
</plugin>

The configuration uses a standard execution goal to run the failsafe plugin during the integration-test phase of the build.

You can now do a mvn clean install.
This time as well as the unit tests running, the integration tests are run during the integration-test phase.

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

I wanted to copy commit history of "master" branch & overwrite the commit history of "main" branch .
The steps are:-

  1. git checkout master
  2. git branch main master -f
  3. git checkout main
  4. git push

To delete master branch:-

a. Locally:-

  1. git checkout main
  2. git branch -d master

b. Globally:-

  1. git push origin --delete master

Do Upvote it!

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

I had the same problem and I could solve it by adding the entity into persistence.xml. The problem was caused due to the fact that the entity was not added to the persistence config. Edit your persistence file:

<persistence-unit name="MY_PU" transaction-type="RESOURCE_LOCAL">
<provider>`enter code here`
     org.hibernate.jpa.HibernatePersistenceProvider
  </provider>
<class>mypackage.MyEntity</class>

...

Update Tkinter Label from variable

This is the easiest one , Just define a Function and then a Tkinter Label & Button . Pressing the Button changes the text in the label. The difference that you would when defining the Label is that use the text variable instead of text. Code is tested and working.

    from tkinter import *
    master = Tk()
    
    def change_text():
        my_var.set("Second click")
    
    my_var = StringVar()
    my_var.set("First click")
    label = Label(mas,textvariable=my_var,fg="red")
    button = Button(mas,text="Submit",command = change_text)
    button.pack()
    label.pack()
    
    master.mainloop()

How do you fadeIn and animate at the same time?

For people still looking a couple of years later, things have changed a bit. You can now use the queue for .fadeIn() as well so that it will work like this:

$('.tooltip').fadeIn({queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');

This has the benefit of working on display: none elements so you don't need the extra two lines of code.

Search of table names

I am assuming you want to pass the database name as a parameter and not just run:

SELECT  *
FROM    DBName.sys.tables
WHERE   Name LIKE '%XXX%'

If so, you could use dynamic SQL to add the dbname to the query:

DECLARE @DBName NVARCHAR(200) = 'YourDBName',
        @TableName NVARCHAR(200) = 'SomeString';

IF NOT EXISTS (SELECT 1 FROM master.sys.databases WHERE Name = @DBName)
    BEGIN
        PRINT 'DATABASE NOT FOUND';
        RETURN;
    END;

DECLARE @SQL NVARCHAR(MAX) = '  SELECT  Name
                                FROM    ' + QUOTENAME(@DBName) + '.sys.tables
                                WHERE   Name LIKE ''%'' + @Table + ''%''';

EXECUTE SP_EXECUTESQL @SQL, N'@Table NVARCHAR(200)', @TableName;

How to access POST form fields

Note for Express 4 users:

If you try and put app.use(express.bodyParser()); into your app, you'll get the following error when you try to start your Express server:

Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.

You'll have to install the package body-parser separately from npm, then use something like the following (example taken from the GitHub page):

var express    = require('express');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser());

app.use(function (req, res, next) {
  console.log(req.body) // populated!
  next();
})

How can I rebuild indexes and update stats in MySQL innoDB?

To date (mysql 8.0.18) there is no suitable function inside mysql to re-create indexes.
Since mysql 8.0 myisam is slowly phasing into deprecated status, innodb is the current main storage engine.
In most practical cases innodb is the best choice and it's supposed to keep indexes working well.
In most practical cases innodb also does a good job, you do not need to recreate indexes. Almost always.

When it comes to large tables with hundreds of GB data amd rows and a lot of writing the situation changes, indexes can degrade in performance.
In my personal case I've seen performance drop from ~15 minutes for a count(*) using a secondary index to 4300 minutes after 2 months of writing to the table with linear time increase.
After recreating the index the performance goes back to 15 minutes.

To date we have two options to do that:
1) OPTIMIZE TABLE (or ALTER TABLE)
Innodb doesn't support optimization so in both cases the entire table will be read and re-created.
This means you need the storage for the temporary file and depending on the table a lot of time (I've cases where an optimize takes a week to complete). This will compact the data and rebuild all indexes.
Despite not being officially recommended, I highly recommend the OPTIMIZE process on write-heavy tables up to 100GB in size.

2) ALTER TABLE DROP KEY -> ALTER TABLE ADD KEY
You manually drop the key by name, you manually create it again. In a production environment you'll want to create it first, then drop the old version.
The upside: this can be a lot faster than optimize. The downside: you need to manually create the syntax.
"SHOW CREATE TABLE" can be used to quickly see which indexes are available and how they are called.

Appendix:
1) To just update statistics you can use the already mentioned "ANALYZE TABLE".
2) If you experience performance degradation on write-heavy servers you might need to restart mysql. There are a couple of bugs in current mysql (8.0) that can cause significant slowdown without showing up in error log. Eventually those slowdowns lead to a server crash but it can take weeks or even months to build up to the crash, in this process the server gets slower and slower in responses.
3) If you wish to re-create a large table that takes weeks to complete or fails after hours due to internal data integrity problems you should do a CREATE TABLE LIKE, INSERT INTO SELECT *. then 'atomic RENAME' the tables.
4) If INSERT INTO SELECT * takes hours to days to complete on huge tables you can speed up the process by about 20-30 times using a multi-threaded approach. You "partition" the table into chunks and INSERT INTO SELECT * in parallel.

How to delay the .keyup() handler until the user stops typing?

Delay Multi Function Calls using Labels

This is the solution i work with. It will delay the execution on ANY function you want. It can be the keydown search query, maybe the quick click on previous or next buttons ( that would otherwise send multiple request if quickly clicked continuously , and be not used after all). This uses a global object that stores each execution time, and compares it with the most current request.

So the result is that only that last click / action will actually be called, because those requests are stored in a queue, that after the X milliseconds is called if no other request with the same label exists in the queue!

function delay_method(label,callback,time){
    if(typeof window.delayed_methods=="undefined"){window.delayed_methods={};}  
    delayed_methods[label]=Date.now();
    var t=delayed_methods[label];
    setTimeout(function(){ if(delayed_methods[label]!=t){return;}else{  delayed_methods[label]=""; callback();}}, time||500);
  }

You can set your own delay time ( its optional, defaults to 500ms). And send your function arguments in a "closure fashion".

For example if you want to call the bellow function:

function send_ajax(id){console.log(id);}

To prevent multiple send_ajax requests, you delay them using:

delay_method( "check date", function(){ send_ajax(2); } ,600);

Every request that uses the label "check date" will only be triggered if no other request is made in the 600 miliseconds timeframe. This argument is optional

Label independency (calling the same target function) but run both:

delay_method("check date parallel", function(){send_ajax(2);});
delay_method("check date", function(){send_ajax(2);});

Results in calling the same function but delay them independently because of their labels being different

Checking if a key exists in a JavaScript object?

New awesome solution with JavaScript Destructuring:

let obj = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
};

let {key1, key2, key3, key4} = obj;

// key1 = "value1"
// key2 = "value2"
// key3 = "value3"
// key4 = undefined

// Can easily use `if` here on key4
if(!key4) { console.log("key not present"); } // Key not present

Do check other use of JavaScript Destructuring

How to use @Nullable and @Nonnull annotations more effectively?

What I do in my projects is to activate the following option in the "Constant conditions & exceptions" code inspection:
Suggest @Nullable annotation for methods that may possibly return null and report nullable values passed to non-annotated parameters Inspections

When activated, all non-annotated parameters will be treated as non-null and thus you will also see a warning on your indirect call:

clazz.indirectPathToA(null); 

For even stronger checks the Checker Framework may be a good choice (see this nice tutorial.
Note: I have not used that yet and there may be problems with the Jack compiler: see this bugreport

Difference between File.separator and slash in paths

As the gentlemen described the difference with variant details.

I would like to recommend the use of the Apache Commons io api, class FilenameUtils when dealing with files in a program with the possibility of deploying on multiple OSs.

Test if number is odd or even

Try this one with #Input field

<?php
    //checking even and odd
    echo '<form action="" method="post">';
    echo "<input type='text' name='num'>\n";
    echo "<button type='submit' name='submit'>Check</button>\n";
    echo "</form>";

    $num = 0;
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (empty($_POST["num"])) {
        $numErr = "<span style ='color: red;'>Number is required.</span>";
        echo $numErr;
        die();
      } else {
          $num = $_POST["num"];
      }


    $even = ($num % 2 == 0);
    $odd = ($num % 2 != 0);
    if ($num > 0){
        if($even){
            echo "Number is even.";
        } else {
            echo "Number is odd.";
        }
    } else {
        echo "Not a number.";
    }
    }
?>

Display number with leading zeros

This is how I do it:

str(1).zfill(len(str(total)))

Basically zfill takes the number of leading zeros you want to add, so it's easy to take the biggest number, turn it into a string and get the length, like this:

Python 3.6.5 (default, May 11 2018, 04:00:52) 
[GCC 8.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> total = 100
>>> print(str(1).zfill(len(str(total))))
001
>>> total = 1000
>>> print(str(1).zfill(len(str(total))))
0001
>>> total = 10000
>>> print(str(1).zfill(len(str(total))))
00001
>>> 

is the + operator less performant than StringBuffer.append()

In the words of Knuth, "premature optimization is the root of all evil!" The small defference either way will most likely not have much of an effect in the end; I'd choose the more readable one.

Using Ansible set_fact to create a dictionary from register results

Thank you Phil for your solution; in case someone ever gets in the same situation as me, here is a (more complex) variant:

---
# this is just to avoid a call to |default on each iteration
- set_fact:
    postconf_d: {}

- name: 'get postfix default configuration'
  command: 'postconf -d'
  register: command

# the answer of the command give a list of lines such as:
# "key = value" or "key =" when the value is null
- name: 'set postfix default configuration as fact'
  set_fact:
    postconf_d: >
      {{
        postconf_d |
        combine(
          dict([ item.partition('=')[::2]|map('trim') ])
        )
  with_items: command.stdout_lines

This will give the following output (stripped for the example):

"postconf_d": {
    "alias_database": "hash:/etc/aliases", 
    "alias_maps": "hash:/etc/aliases, nis:mail.aliases",
    "allow_min_user": "no", 
    "allow_percent_hack": "yes"
}

Going even further, parse the lists in the 'value':

- name: 'set postfix default configuration as fact'
  set_fact:
    postconf_d: >-
      {% set key, val = item.partition('=')[::2]|map('trim') -%}
      {% if ',' in val -%}
        {% set val = val.split(',')|map('trim')|list -%}
      {% endif -%}
      {{ postfix_default_main_cf | combine({key: val}) }}
  with_items: command.stdout_lines
...
"postconf_d": {
    "alias_database": "hash:/etc/aliases", 
    "alias_maps": [
        "hash:/etc/aliases", 
        "nis:mail.aliases"
    ], 
    "allow_min_user": "no", 
    "allow_percent_hack": "yes"
}

A few things to notice:

  • in this case it's needed to "trim" everything (using the >- in YAML and -%} in Jinja), otherwise you'll get an error like:

    FAILED! => {"failed": true, "msg": "|combine expects dictionaries, got u\"  {u'...
    
  • obviously the {% if .. is far from bullet-proof

  • in the postfix case, val.split(',')|map('trim')|list could have been simplified to val.split(', '), but I wanted to point out the fact you will need to |list otherwise you'll get an error like:

    "|combine expects dictionaries, got u\"{u'...': <generator object do_map at ...
    

Hope this can help.

How can jQuery deferred be used?

The answer by ehynds will not work, because it caches the responses data. It should cache the jqXHR which is also a Promise. Here is the correct code:

var cache = {};

function getData( val ){

    // return either the cached value or an
    // jqXHR object (which contains a promise)
    return cache[ val ] || $.ajax('/foo/', {
        data: { value: val },
        dataType: 'json',
        success: function(data, textStatus, jqXHR){
            cache[ val ] = jqXHR;
        }
    });
}

getData('foo').then(function(resp){
    // do something with the response, which may
    // or may not have been retreived using an
    // XHR request.
});

The answer by Julian D. will work correct and is a better solution.

RabbitMQ / AMQP: single queue, multiple consumers for same message?

Fan out was clearly what you wanted. fanout

read rabbitMQ tutorial: https://www.rabbitmq.com/tutorials/tutorial-three-javascript.html

here's my example:

Publisher.js:

amqp.connect('amqp://<user>:<pass>@<host>:<port>', async (error0, connection) => {
    if (error0) {
      throw error0;
    }
    console.log('RabbitMQ connected')
    try {
      // Create exchange for queues
      channel = await connection.createChannel()
      await channel.assertExchange(process.env.EXCHANGE_NAME, 'fanout', { durable: false });
      await channel.publish(process.env.EXCHANGE_NAME, '', Buffer.from('msg'))
    } catch(error) {
      console.error(error)
    }
})

Subscriber.js:

amqp.connect('amqp://<user>:<pass>@<host>:<port>', async (error0, connection) => {
    if (error0) {
      throw error0;
    }
    console.log('RabbitMQ connected')
    try {
      // Create/Bind a consumer queue for an exchange broker
      channel = await connection.createChannel()
      await channel.assertExchange(process.env.EXCHANGE_NAME, 'fanout', { durable: false });
      const queue = await channel.assertQueue('', {exclusive: true})
      channel.bindQueue(queue.queue, process.env.EXCHANGE_NAME, '')

      console.log(" [*] Waiting for messages in %s. To exit press CTRL+C");
      channel.consume('', consumeMessage, {noAck: true});
    } catch(error) {
      console.error(error)
    }
});

here is an example i found in the internet. maybe can also help. https://www.codota.com/code/javascript/functions/amqplib/Channel/assertExchange

How to get the scroll bar with CSS overflow on iOS

Edit following the comment left, kindly, by kritzikratzi:

[Starting] with ios 5beta a new property -webkit-overflow-scrolling: touch can be added which should result in the expected behaviour.

Some, but very little, further reading:


Original answer, left for posterity.

Unfortunately neither overflow: auto, or scroll, produces scrollbars on the iOS devices, apparently due to the screen-width that would be taken up such useful mechanisms.

Instead, as you've found, users are required to perform the two-finger swipe in order to scroll the overflow-ed content. The only reference, since I'm unable to find the manual for the phone itself, I could find is here: tuaw.com: iPhone 101: Two-fingered scrolling.

The only work-around I can think of for this, is if you could possibly use some JavaScript, and maybe jQTouch, to create your own scroll-bars for overflow elements. Alternatively you could use @media queries to remove the overflow and show the content in full, as an iPhone user this gets my vote, if only for the sheer simplicity. For example:

<link rel="stylesheet" href="handheld.css" media="only screen and (max-device width:480px)" />

The preceding code comes from A List Apart, from the same article linked-to above (I'm not sure why they left of the type="text/css", but I assume there are reasons.

Encrypt and decrypt a password in Java

EDIT : this answer is old. Usage of MD5 is now discouraged as it can easily be broken.


MD5 must be good enough for you I imagine? You can achieve it with MessageDigest.

MessageDigest.getInstance("MD5");

There are also other algorithms listed here.

And here's an third party version of it, if you really want: Fast MD5

C#: easiest way to populate a ListBox from a List

Is this what you are looking for:

myListBox.DataSource = MyList;

What does the variable $this mean in PHP?

The best way to learn about the $this variable in PHP is to try it against the interpreter in various contexts:

print isset($this);              //true,   $this exists
print gettype($this);            //Object, $this is an object 
print is_array($this);           //false,  $this isn't an array
print get_object_vars($this);    //true,   $this's variables are an array
print is_object($this);          //true,   $this is still an object
print get_class($this);          //YourProject\YourFile\YourClass
print get_parent_class($this);   //YourBundle\YourStuff\YourParentClass
print gettype($this->container); //object
print_r($this);                  //delicious data dump of $this
print $this->yourvariable        //access $this variable with ->

So the $this pseudo-variable has the Current Object's method's and properties. Such a thing is useful because it lets you access all member variables and member methods inside the class. For example:

Class Dog{
    public $my_member_variable;                             //member variable

    function normal_method_inside_Dog() {                   //member method

        //Assign data to member variable from inside the member method
        $this->my_member_variable = "whatever";

        //Get data from member variable from inside the member method.
        print $this->my_member_variable;
    }
}

$this is reference to a PHP Object that was created by the interpreter for you, that contains an array of variables.

If you call $this inside a normal method in a normal class, $this returns the Object (the class) to which that method belongs.

It's possible for $this to be undefined if the context has no parent Object.

php.net has a big page talking about PHP object oriented programming and how $this behaves depending on context. https://www.php.net/manual/en/language.oop5.basic.php

javascript : sending custom parameters with window.open() but its not working

To concatenate strings, use the + operator.

To insert data into a URI, encode it for URIs.

Bad:

var url = "http://localhost:8080/login?cid='username'&pwd='password'"

Good:

var url_safe_username = encodeURIComponent(username);
var url_safe_password = encodeURIComponent(password);
var url = "http://localhost:8080/login?cid=" + url_safe_username + "&pwd=" + url_safe_password;

The server will have to process the query string to make use of the data. You can't assign to arbitrary form fields.

… but don't trigger new windows or pass credentials in the URI (where they are exposed to over the shoulder attacks and may be logged).

Using BigDecimal to work with currencies

NumberFormat.getNumberInstance(java.util.Locale.US).format(num);

How do I find the caller of a method using stacktrace or reflection?

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

class DBConnection {
    String createdBy = null;

    DBConnection(Throwable whoCreatedMe) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PrintWriter pw = new PrintWriter(os);
        whoCreatedMe.printStackTrace(pw);
        try {
            createdBy = os.toString();
            pw.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public class ThrowableTest {

    public static void main(String[] args) {

        Throwable createdBy = new Throwable(
                "Connection created from DBConnectionManager");
        DBConnection conn = new DBConnection(createdBy);
        System.out.println(conn.createdBy);
    }
}

OR

public static interface ICallback<T> { T doOperation(); }


public class TestCallerOfMethod {

    public static <T> T callTwo(final ICallback<T> c){
        // Pass the object created at callee to the caller
        // From the passed object we can get; what is the callee name like below.
        System.out.println(c.getClass().getEnclosingMethod().getName());
        return c.doOperation();
    }

    public static boolean callOne(){
        ICallback callBackInstance = new ICallback(Boolean){
            @Override
            public Boolean doOperation() 
            {
                return true;
            }
        };
        return callTwo(callBackInstance);
    }

    public static void main(String[] args) {
         callOne();
    }
}

When should you use a class vs a struct in C++?

For C++, there really isn't much of a difference between structs and classes. The main functional difference is that members of a struct are public by default, while they are private by default in classes. Otherwise, as far as the language is concerned, they are equivalent.

That said, I tend to use structs in C++ like I do in C#, similar to what Brian has said. Structs are simple data containers, while classes are used for objects that need to act on the data in addition to just holding on to it.

Test if a variable is a list or tuple

Has to be more complex test if you really want to handle just about anything as function argument.

type(a) != type('') and hasattr(a, "__iter__")

Although, usually it's enough to just spell out that a function expects iterable and then check only type(a) != type('').

Also it may happen that for a string you have a simple processing path or you are going to be nice and do a split etc., so you don't want to yell at strings and if someone sends you something weird, just let him have an exception.

Python Pandas: Get index of rows which column matches certain value

If you want to use your dataframe object only once, use:

df['BoolCol'].loc[lambda x: x==True].index

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

I just tried to show you the solution in a simple code

@IBAction func Button(sender : AnyObject) {
 if textField1.text != "" {
   // either textfield 1 is not empty then do this task
 }else{
   //show error here that textfield1 is empty
 }
}

String replace a Backslash

This will replace backslashes with forward slashes in the string:

source = source.replace('\\','/');

Cannot implicitly convert type 'int?' to 'int'.

simple

(i == null) ? i.Value : 0;

Insert text into textarea with jQuery

It works good for me in Chrome 20.0.11

var startPos = this[0].selectionStart;
var endPos = this[0].selectionEnd;
var scrollTop = this.scrollTop;
this[0].value = this[0].value.substring(0, startPos) + myVal + this[0].value.substring(endPos, this[0].value.length);
this.focus();
this.selectionStart = startPos + myVal.length;
this.selectionEnd = startPos + myVal.length;
this.scrollTop = scrollTop;

Optimum way to compare strings in JavaScript?

Well in JavaScript you can check two strings for values same as integers so yo can do this:

  • "A" < "B"
  • "A" == "B"
  • "A" > "B"

And therefore you can make your own function that checks strings the same way as the strcmp().

So this would be the function that does the same:

function strcmp(a, b)
{   
    return (a<b?-1:(a>b?1:0));  
}

What HTTP traffic monitor would you recommend for Windows?

I use Wireshark in most cases, but I have found Fiddler to be less of a hassle when dealing with encrypted data.

How to write a link like <a href="#id"> which link to the same page in PHP?

Edit:

Are you trying to do sth like this? See: http://twitter.github.com/bootstrap/javascript.html#tabs


See the working example: http://jsfiddle.net/U6aKT/

<a href="#id">go to id</a>
<div style="margin-top:2000px;"></div>
<a id="id">id</a>

Disable all Database related auto configuration in Spring Boot

I had the same problem here, solved like this:

Just add another application-{yourprofile}.yml where "yourprofile" could be "client".

In my case I just wanted to remove Redis in a Dev profile, so I added a application-dev.yml next to the main application.yml and it did the job.

In this file I put:

spring.autoconfigure.exclude: org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration

this should work with properties files as well.

I like the fact that there is no need to change the application code to do that.

Django - "no module named django.core.management"

It sounds like you do not have django installed. You should check the directory produced by this command:

python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"

To see if you have the django packages in there.

If there's no django folder inside of site-packages, then you do not have django installed (at least for that version of python).

It is possible you have more than one version of python installed and django is inside of another version. You can find out all the versions of python if you type python and then press TAB. Here are all the different python's I have.

$python
python            python2-config    python2.6         python2.7-config  pythonw2.5
python-config     python2.5         python2.6-config  pythonw           pythonw2.6
python2           python2.5-config  python2.7         pythonw2          pythonw2.7

You can do the above command for each version of python and look inside the site-packages directory of each to see if any of them have django installed. For example:

python2.5 -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"
python2.6 -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"

If you happen to find django inside of say python2.6, try your original command with

python2.6 manage.py ...

How to declare a structure in a header that is to be used by multiple files in c?

a.h:

#ifndef A_H
#define A_H

struct a { 
    int i;
    struct b {
        int j;
    }
};

#endif

there you go, now you just need to include a.h to the files where you want to use this structure.

Convert string (without any separator) to list

A python string is a list of characters. You can iterate over it right now!

justdigits = ""
for char in string:
    if char.isdigit():
        justdigits += str(char)

How do I pass multiple attributes into an Angular.js attribute directive?

This worked for me and I think is more HTML5 compliant. You should change your html to use 'data-' prefix

<div data-example-directive data-number="99"></div>

And within the directive read the variable's value:

scope: {
        number : "=",
        ....
    },

How can I convert a series of images to a PDF from the command line on linux?

Use convert from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)

How does the 'binding' attribute work in JSF? When and how should it be used?

How does it work?

When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding attributes are evaluated (along with id attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding attribute returns a precreated component (i.e. non-null) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding attribute with the autocreated component instance as argument.

In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.

Component instances are request scoped!

Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:

3.1.5 Component Bindings

...

Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly recommend that application developers place managed beans that are pointed at by component binding expressions in “request” scope. This is because placing it in session or application scope would require thread-safety, since UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on memory management when placing a component binding in “session” scope.

Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.

And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Java Threads at 100% CPU utilization using richfaces UIDataAdaptorBase and its internal HashMap, or even some "strange" IndexOutOfBoundsException or ConcurrentModificationException coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState() or restoreState() methods and like).

Using binding on a bean property is bad practice

Regardless, using binding this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value, and perhaps others like styleClass, disabled, rendered, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.

In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent(), new SomeComponent(), getChildren().add() and what not. See also How to refactor snippet of old JSP to some JSF equivalent?

Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>, <h:dataTable>, etc). See also How to dynamically add JSF components.

Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation> to the backing component (i.e. the component identified by <cc:interface componentType>. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?

Only use binding in local scope

However, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding attribute like so binding="#{foo}" and the component is during render response elsewhere in the same view directly as UIComponent reference available by #{foo}. Here are several related questions where such a solution is been used in the answer:

See also:

Could not open input file: artisan

You cannot use php artisan if you are not inside a laravel project folder.

That is why it says 'Could not open input file - artisan'.

Android and setting width and height programmatically in dp units

You'll have to convert it from dps to pixels using the display scale factor.

final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);

What is the &#xA; character?

It's a linefeed character. How you use it would be up to you.

Java - No enclosing instance of type Foo is accessible

Declare the INNER class Thing as a static and it will work with no issues.

I remember I have the same issue with the inner class Dog when I declared it as class Dog { only. I got the same issue as you did. There were two solutions:

1- To declare the inner class Dog as static. Or

2- To move the inner class Dog to a new class by itself.

Here is the Example:

public class ReturnDemo {

public static void main(String[] args) {
    
    int z = ReturnDemo.calculate(10, 12);
    System.out.println("z = " + z);
    
    ReturnDemo.Dog dog = new Dog("Bosh", " Doggy");
    System.out.println( dog.getDog());
}


public static int calculate (int x, int y) {
    return x + y;
}

public void print( ) {
    System.out.println("void method");
    return;
}

public String getString() {
    return "Retrun String type value";
}


static class Dog {
    
private String breed;
private String name;

public Dog(String breed, String name) {
    super();
    this.breed = breed;
    this.name = name;
}

public Dog getDog() {
    // return Dog type;
    return this;
    
}

public String toString() {
    return "breed" + breed.concat("name: " + name);
}
}

}

What is Teredo Tunneling Pseudo-Interface?

Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.

If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)

How to send a simple string between two programs using pipes?

dup2( STDIN_FILENO, newfd )

And read:

char reading[ 1025 ];
int fdin = 0, r_control;
if( dup2( STDIN_FILENO, fdin ) < 0 ){
    perror( "dup2(  )" );
    exit( errno );
}
memset( reading, '\0', 1025 );
while( ( r_control = read( fdin, reading, 1024 ) ) > 0 ){
    printf( "<%s>", reading );
    memset( reading, '\0', 1025 );
}
if( r_control < 0 )
    perror( "read(  )" );    
close( fdin );    

But, I think that fcntl can be a better solution

echo "salut" | code

What's the difference between next() and nextLine() methods from Scanner class?

next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

import java.util.Scanner;

public class temp
{
    public static void main(String arg[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("enter string for c");
        String c=sc.next();
        System.out.println("c is "+c);
        System.out.println("enter string for d");
        String d=sc.next();
        System.out.println("d is "+d);
    }
}

Output:

enter string for c abc def
c is abc

enter string for d

d is def

If you use nextLine() instead of next() then

Output:

enter string for c

ABC DEF
c is ABC DEF
enter string for d

GHI
d is GHI

Create Map in Java

I use such kind of a Map population thanks to Java 9. In my honest opinion, this approach provides more readability to the code.

  public static void main(String[] args) {
    Map<Integer, Point2D.Double> map = Map.of(
        1, new Point2D.Double(1, 1),
        2, new Point2D.Double(2, 2),
        3, new Point2D.Double(3, 3),
        4, new Point2D.Double(4, 4));
    map.entrySet().forEach(System.out::println);
  }

Dynamically create checkbox with JQuery from text input

Put a global variable to generate the ids.

<script>
    $(function(){
        // Variable to get ids for the checkboxes
        var idCounter=1;
        $("#btn1").click(function(){
            var val = $("#txtAdd").val();
            $("#divContainer").append ( "<label for='chk_" + idCounter + "'>" + val + "</label><input id='chk_" + idCounter + "' type='checkbox' value='" + val + "' />" );
            idCounter ++;
        });
    });
</script>
<div id='divContainer'></div>
<input type="text" id="txtAdd" /> 
<button id="btn1">Click</button>

pandas convert some columns into rows

I guess I found a simpler solution

temp1 = pd.melt(df1, id_vars=["location"], var_name='Date', value_name='Value')
temp2 = pd.melt(df1, id_vars=["name"], var_name='Date', value_name='Value')

Concat whole temp1 with temp2's column name

temp1['new_column'] = temp2['name']

You now have what you asked for.

How to auto-scroll to end of div when data is added?

If you don't know when data will be added to #data, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.

window.setInterval(function() {
  var elem = document.getElementById('data');
  elem.scrollTop = elem.scrollHeight;
}, 5000);

How to comment out a block of Python code in Vim

NERDcommenter is an excellent plugin for commenting which automatically detects a number of filetypes and their associated comment characters. Ridiculously easy to install using Pathogen.

Comment with <leader>cc. Uncomment with <leader>cu. And toggle comments with <leader>c<space>.

(The default <leader> key in vim is \)

For vs. while in C programming?

If you want a loop to execute while a condition is true, and not for a certain number of iterations, it is much easier for someone else to understand:

while (cond_true)

than something like this:

for (; cond_true ; )

Pointers in JavaScript?

In JavaScript, you cannot pass variables by reference to a function. However you can pass an object by reference.

How to add a margin to a table row <tr>

line-height can be the possible solution

tr
{
    line-height:30px;
}

Delete data with foreign key in SQL Server table

You can disable and re-enable the foreign key constraints before and after deleting:

alter table MyOtherTable nocheck constraint all
delete from MyTable
alter table MyOtherTable check constraint all