Programs & Examples On #Acceptbutton


Press enter in textbox to and execute button command

Alternatively, you could set the .AcceptButton property of your form. Enter will automcatically create a click event.

this.AcceptButton = this.buttonSearch;

How can I include null values in a MIN or MAX?

It's a bit ugly but because the NULLs have a special meaning to you, this is the cleanest way I can think to do it:

SELECT recordid, MIN(startdate),
        THEN MAX(enddate)
FROM tmp GROUP BY recordid

That is, if any row has a NULL, we want to force that to be the answer. Only if no rows contain a NULL should we return the MIN (or MAX).

Why can't I use Docker CMD multiple times to run multiple services?

The official docker answer to Run multiple services in a container.

It explains how you can do it with an init system (systemd, sysvinit, upstart) , a script (CMD ./ or a supervisor like supervisord.

The && workaround can work only for services that starts in background (daemons) or that will execute quickly without interaction and release the prompt. Doing this with an interactive service (that keeps the prompt) and only the first service will start.

Max value of Xmx and Xms in Eclipse?

I am guessing you are using a 32 bit eclipse with 32 bit JVM. It wont allow heapsize above what you have specified.

Using a 64-bit Eclipse with a 64-bit JVM helps you to start up eclipse with much larger memory. (I am starting with -Xms1024m -Xmx4000m)

What are all codecs and formats supported by FFmpeg?

Codecs proper:

ffmpeg -codecs


ffmpeg -formats

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

Gantt chart is wrong... First process P3 has arrived so it will execute first. Since the burst time of P3 is 3sec after the completion of P3, processes P2,P4, and P5 has been arrived. Among P2,P4, and P5 the shortest burst time is 1sec for P2, so P2 will execute next. Then P4 and P5. At last P1 will be executed.

Gantt chart for this ques will be:

| P3 | P2 | P4 | P5 | P1 |

1    4    5    7   11   14

Average waiting time=(0+2+2+3+3)/5=2

Average Turnaround time=(3+3+4+7+6)/5=4.6

"No resource identifier found for attribute 'showAsAction' in package 'android'"

go to gradle and then to app.buildgradle then set compileSDKVersion to 21 and then if necessary the android studio will download some files

stop all instances of node.js server

You can try this:

taskkill /IM node.exe -F

jQuery: Handle fallback for failed AJAX Request

I believe that what you are looking for is error option for the jquery ajax object

getJSON is a wrapper to the $.ajax object, but it doesn't provide you with access to the error option.

EDIT: dcneiner has given a good example of the code you would need to use. (Even before I could post my reply)

Set default value of javascript object attributes

I'm surprised nobody has mentioned ternary operator yet.

var emptyObj = {a:'123', b:'234', c:0};
var defaultValue = 'defaultValue';
var attr = 'someNonExistAttribute';
emptyObj.hasOwnProperty(attr) ? emptyObj[attr] : defaultValue;//=> 'defaultValue'

attr = 'c'; // => 'c'
emptyObj.hasOwnProperty(attr) ? emptyObj[attr] : defaultValue; // => 0

In this way, even if the value of 'c' is 0, it will still get the correct value.

What is the shortest function for reading a cookie by name in JavaScript?

Both of these functions look equally valid in terms of reading cookie. You can shave a few bytes off though (and it really is getting into Code Golf territory here):

function readCookie(name) {
    var nameEQ = name + "=", ca = document.cookie.split(';'), i = 0, c;
    for(;i < ca.length;i++) {
        c = ca[i];
        while (c[0]==' ') c = c.substring(1);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length);
    return null;

All I did with this is collapse all the variable declarations into one var statement, removed the unnecessary second arguments in calls to substring, and replace the one charAt call into an array dereference.

This still isn't as short as the second function you provided, but even that can have a few bytes taken off:

function read_cookie(key)
    var result;
    return (result = new RegExp('(^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? result[2] : null;

I changed the first sub-expression in the regular expression to be a capturing sub-expression, and changed the result[1] part to result[2] to coincide with this change; also removed the unnecessary parens around result[2].

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

I always prefer to read input using nextLine() and then parse the string.

Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line.

A useful tool for parsing data from nextLine() would be str.split("\\s+").

String data = scanner.nextLine();
String[] pieces = data.split("\\s+");
// Parse the pieces

For more information regarding the Scanner class or String class refer to the following links.



Pass in an array of Deferreds to $.when()

I had a case very similar where I was posting in an each loop and then setting the html markup in some fields from numbers received from the ajax. I then needed to do a sum of the (now-updated) values of these fields and place in a total field.

Thus the problem was that I was trying to do a sum on all of the numbers but no data had arrived back yet from the async ajax calls. I needed to complete this functionality in a few functions to be able to reuse the code. My outer function awaits the data before I then go and do some stuff with the fully updated DOM.

    // 1st
    function Outer() {
        var deferreds = GetAllData();

        $.when.apply($, deferreds).done(function () {
            // now you can do whatever you want with the updated page

    // 2nd
    function GetAllData() {
        var deferreds = [];
        $('.calculatedField').each(function (data) {
        return deferreds;

    // 3rd
    function GetIndividualData(item) {
        var def = new $.Deferred();
        $.post('@Url.Action("GetData")', function (data) {
        return def;

How does Subquery in select statement work in oracle

It's simple-

SELECT empname,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

Explanation for the subquery:

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.


When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.

Explanation for the left join

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

For more information read Oracle Docs on subqueries and left join or left outer join.

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

Adapted from Timmmm to PYQT5

from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import QResizeEvent
from PyQt5.QtWidgets import QLabel

class Label(QLabel):

    def __init__(self):
        super(Label, self).__init__()
        self.pixmap_width: int = 1
        self.pixmapHeight: int = 1

    def setPixmap(self, pm: QPixmap) -> None:
        self.pixmap_width = pm.width()
        self.pixmapHeight = pm.height()

        super(Label, self).setPixmap(pm)

    def resizeEvent(self, a0: QResizeEvent) -> None:
        super(Label, self).resizeEvent(a0)

    def updateMargins(self):
        if self.pixmap() is None:
        pixmapWidth = self.pixmap().width()
        pixmapHeight = self.pixmap().height()
        if pixmapWidth <= 0 or pixmapHeight <= 0:
        w, h = self.width(), self.height()
        if w <= 0 or h <= 0:

        if w * pixmapHeight > h * pixmapWidth:
            m = int((w - (pixmapWidth * h / pixmapHeight)) / 2)
            self.setContentsMargins(m, 0, m, 0)
            m = int((h - (pixmapHeight * w / pixmapWidth)) / 2)
            self.setContentsMargins(0, m, 0, m)

Can I start the iPhone simulator without "Build and Run"?

The easiest way is start the simulator from the Xcode, and then on the dock, Ctrl + Click on the icon and select Keep in Dockenter image description here

How do I UPDATE from a SELECT in SQL Server?

In the accepted answer, after the:

Table_A.col1 = Table_B.col1,
Table_A.col2 = Table_B.col2

I would add:

OUTPUT deleted.*, inserted.*

What I usually do is putting everything in a roll backed transaction and using the "OUTPUT": in this way I see everything that is about to happen. When I am happy with what I see, I change the ROLLBACK into COMMIT.

I usually need to document what I did, so I use the "results to Text" option when I run the roll-backed query and I save both the script and the result of the OUTPUT. (Of course this is not practical if I changed too many rows)

Can pm2 run an 'npm start' script

I needed to run a specific npm script on my app in pm2 (for each env) In my case, it was when I created a staging/test service

The command that worked for me (the args must be forwarded that way):

pm2 start npm --name "my-app-name" -- run "npm:script"


pm2 start npm --name "myApp" -- run "start:test"

pm2 start npm --name "myApp" -- run "start:staging"

pm2 start npm --name "myApp" -- run "start:production"

Hope it helped

Maximum length of the textual representation of an IPv6 address?

45 characters.

You might expect an address to be


8 * 4 + 7 = 39

8 groups of 4 digits with 7 : between them.

But if you have an IPv4-mapped IPv6 address, the last two groups can be written in base 10 separated by ., eg. [::ffff:]. Written out fully:


(6 * 4 + 5) + 1 + (4 * 3 + 3) = 29 + 1 + 15 = 45

Note, this is an input/display convention - it's still a 128 bit address and for storage it would probably be best to standardise on the raw colon separated format, i.e. [0000:0000:0000:0000:0000:ffff:c0a8:64e4] for the address above.

Bootstrap fullscreen layout with 100% height

<section class="min-vh-100 d-flex align-items-center justify-content-center py-3">
  <div class="container">
    <div class="row justify-content-between align-items-center">

How to convert hex string to Java string?

First of all read in the data, then convert it to byte array:

 byte b = Byte.parseByte(str, 16); 

and then use String constructor:

new String(byte[] bytes) 

or if the charset is not system default then:

new String(byte[] bytes, String charsetName) 

Detecting the onload event of a window opened with

If the pop-up's document is from a different domain, this is simply not possible.

Update April 2015: I was wrong about this: if you own both domains, you can use window.postMessage and the message event in pretty much all browsers that are relevant today.

If not, there's still no way you'll be able to make this work cross-browser without some help from the document being loaded into the pop-up. You need to be able to detect a change in the pop-up that occurs once it has loaded, which could be a variable that JavaScript in the pop-up page sets when it handles its own load event, or if you have some control of it you could add a call to a function in the opener.

Entity Framework Refresh context?

Use the Refresh method:

context.Refresh(RefreshMode.StoreWins, yourEntity);

or in alternative dispose your current context and create a new one.

Converting a vector<int> to string

template<typename T>
string str(T begin, T end)
    stringstream ss;
    bool first = true;
    for (; begin != end; begin++)
        if (!first)
            ss << ", ";
        ss << *begin;
        first = false;
    return ss.str();

This is the str function that can make integers turn into a string and not into a char for what the integer represents. Also works for doubles.

Trying to get property of non-object in

<?php foreach ($sidemenus->mname as $sidemenu): ?>
<?php echo $sidemenu ."<br />";?>


$sidemenus = mysql_fetch_array($results);


<?php echo $sidemenu['mname']."<br />";?>

How to check if BigDecimal variable == 0 in java?

A simple and better way for your exemple is:

BigDecimal price;

if(BigDecimal.ZERO.compareTo(price) == 0){
   //Returns TRUE


How to load data from a text file in a PostgreSQL database?

COPY description_f (id, name) FROM 'absolutepath\test.txt' WITH (FORMAT csv, HEADER true, DELIMITER '   ');


COPY description_f (id, name) FROM 'D:\HIVEWORX\COMMON\TermServerAssets\Snomed2021\SnomedCT\Full\Terminology\sct2_Description_Full_INT_20210131.txt' WITH (FORMAT csv, HEADER true, DELIMITER ' ');

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

If pip fails to install "MySQLdb", a workaround is to download and install it on your machine first from this link

then copy all MySQL* and _mysql* files and directories from your system Python to your Virtualenv dir:

c:\Python27\Lib\site-packages (or similar path to your system Python) to c:\my_virtenv\Lib\site-packages (path to your virtualenv)

JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

Convert LocalDateTime to LocalDateTime in UTC

Here's a simple little utility class that you can use to convert local date times from zone to zone, including a utility method directly to convert a local date time from the current zone to UTC (with main method so you can run it and see the results of a simple test):

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public final class DateTimeUtil {
    private DateTimeUtil() {

    public static void main(final String... args) {
        final LocalDateTime now =;
        final LocalDateTime utc = DateTimeUtil.toUtc(now);

        System.out.println("Now: " + now);
        System.out.println("UTC: " + utc);

    public static LocalDateTime toZone(final LocalDateTime time, final ZoneId fromZone, final ZoneId toZone) {
        final ZonedDateTime zonedtime = time.atZone(fromZone);
        final ZonedDateTime converted = zonedtime.withZoneSameInstant(toZone);
        return converted.toLocalDateTime();

    public static LocalDateTime toZone(final LocalDateTime time, final ZoneId toZone) {
        return DateTimeUtil.toZone(time, ZoneId.systemDefault(), toZone);

    public static LocalDateTime toUtc(final LocalDateTime time, final ZoneId fromZone) {
        return DateTimeUtil.toZone(time, fromZone, ZoneOffset.UTC);

    public static LocalDateTime toUtc(final LocalDateTime time) {
        return DateTimeUtil.toUtc(time, ZoneId.systemDefault());

How to force reloading php.ini file?

TL;DR; If you're still having trouble after restarting apache or nginx, also try restarting the php-fpm service.

The answers here don't always satisfy the requirement to force a reload of the php.ini file. On numerous occasions I've taken these steps to be rewarded with no update, only to find the solution I need after also restarting the php-fpm service. So if restarting apache or nginx doesn't trigger a php.ini update although you know the files are updated, try restarting php-fpm as well.

To restart the service:

Note: prepend sudo if not root

Using SysV Init scripts directly:

/etc/init.d/php-fpm restart        # typical
/etc/init.d/php5-fpm restart       # debian-style
/etc/init.d/php7.0-fpm restart     # debian-style PHP 7

Using service wrapper script

service php-fpm restart        # typical
service php5-fpm restart       # debian-style
service php7.0-fpm restart.    # debian-style PHP 7

Using Upstart (e.g. ubuntu):

restart php7.0-fpm         # typical (ubuntu is debian-based) PHP 7
restart php5-fpm           # typical (ubuntu is debian-based)
restart php-fpm            # uncommon

Using systemd (newer servers):

systemctl restart php-fpm.service        # typical
systemctl restart php5-fpm.service       # uncommon
systemctl restart php7.0-fpm.service     # uncommon PHP 7

Or whatever the equivalent is on your system.

The above commands taken directly from this server fault answer

How to use onClick event on react Link component?

I don't believe this is a good pattern to use in general. Link will run your onClick event and then navigate to the route, so there will be a slight delay navigating to the new route. A better strategy is to navigate to the new route with the 'to' prop as you have done, and in the new component's componentDidMount() function you can fire your hello function or any other function. It will give you the same result, but with a much smoother transition between routes.

For context, I noticed this while updating my redux store with an onClick event on Link like you have here, and it caused a ~.3 second blank-white-screen delay before mounting the new route's component. There was no api call involved, so I was surprised the delay was so big. However, if you're just console logging 'hello' the delay might not be noticeable.

How to succinctly write a formula with many variables from a data frame?

A slightly different approach is to create your formula from a string. In the formula help page you will find the following example :

## Create a formula for a model with a large number of variables:
xnam <- paste("x", 1:25, sep="")
fmla <- as.formula(paste("y ~ ", paste(xnam, collapse= "+")))

Then if you look at the generated formula, you will get :

R> fmla
y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 + 
    x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 + 
    x22 + x23 + x24 + x25

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

First you need to install cors by using below command :

npm install cors --save

Now add the following code to your app starting file like ( app.js or server.js)

var express = require('express');
var app = express();

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

//enables cors
  'allowedHeaders': ['sessionId', 'Content-Type'],
  'exposedHeaders': ['sessionId'],
  'origin': '*',
  'preflightContinue': false


Create a txt file using batch file in a specific folder

You have it almost done. Just explicitly say where to create the file

@echo off

This creates a file containing a blank line (CR + LF = 2 bytes).

If you want the file empty (0 bytes)

@echo off

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

They are essentially equivalent to each other (in fact this is how some databases implement DISTINCT under the hood).

If one of them is faster, it's going to be DISTINCT. This is because, although the two are the same, a query optimizer would have to catch the fact that your GROUP BY is not taking advantage of any group members, just their keys. DISTINCT makes this explicit, so you can get away with a slightly dumber optimizer.

When in doubt, test!

super() in Java

Yes, super() (lowercase) calls a constructor of the parent class. You can include arguments: super(foo, bar)

There is also a super keyword, that you can use in methods to invoke a method of the superclass

A quick google for "Java super" results in this

console.log timestamps in Chrome?

If you are using Google Chrome browser, you can use chrome console api:

  • console.time: call it at the point in your code where you want to start the timer
  • console.timeEnd: call it to stop the timer

The elapsed time between these two calls is displayed in the console.

For detail info, please see the doc link:

Join String list elements with a delimiter in one step

You can use the StringUtils.join() method of Apache Commons Lang:

String join = StringUtils.join(joinList, "+");

Eclipse DDMS error "Can't bind to local 8600 for debugger"

Worked for me, based on this answer

In Eclipse go to


Then tick "Use ADBHOST" as "".

Then just restart eclipse

How to disable mouse scroll wheel scaling with Google Maps API

I created a more developed jQuery plugin that allows you to lock or unlock the map with a nice button.

This plugin disables the Google Maps iframe with a transparent overlay div and adds a button for unlockit. You must press for 650 milliseconds to unlock it.

You can change all the options for your convenience. Check it at

Here's some example.

(function() {_x000D_
  $(function() {_x000D_
    $("#btn-start").click(function() {_x000D_
        printLog: true_x000D_
      return $("#btn-stop").click(function() {_x000D_
        return $("iframe[src*='']").scrollprevent().stop();_x000D_
    return $("#btn-start").trigger("click");_x000D_
.embed-container {_x000D_
  position: relative !important;_x000D_
  padding-bottom: 56.25% !important;_x000D_
  height: 0 !important;_x000D_
  overflow: hidden !important;_x000D_
  max-width: 100% !important;_x000D_
.embed-container iframe {_x000D_
  position: absolute !important;_x000D_
  top: 0 !important;_x000D_
  left: 0 !important;_x000D_
  width: 100% !important;_x000D_
  height: 100% !important;_x000D_
.mapscroll-wrap {_x000D_
  position: static !important;_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<div class="embed-container">_x000D_
  <iframe src="!1m18!1m12!1m3!1d12087.746318586604!2d-71.64614110000001!3d-40.76341959999999!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x9610bf42e48faa93%3A0x205ebc786470b636!2sVilla+la+Angostura%2C+Neuqu%C3%A9n!5e0!3m2!1ses-419!2sar!4v1425058155802"_x000D_
  width="400" height="300" frameborder="0" style="border:0"></iframe>_x000D_
<p><a id="btn-start" href="#">"Start Scroll Prevent"</a>  <a id="btn-stop" href="#">"Stop Scroll Prevent"</a>_x000D_

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

plt.savefig(file_path, bbox_inches="tight", pad_inches = 0)

plt.savefig has those options in itself, just need to set axes off before

How can I get all sequences in an Oracle database?

You may not have permission to dba_sequences. So you can always just do:

select * from user_sequences;

Get gateway ip address in android

I'm using cyanogenmod 7.2 on android 2.3.4, then just open terminal emulator and type:

$ ip addr show
$ ip route show

Javascript how to split newline

(function($) {_x000D_
  $(document).ready(function() {_x000D_
    $('#data').click(function(e) {_x000D_
      $.each($("#keywords").val().split("\n"), function(e, element) {_x000D_
<script src=""></script>_x000D_
<textarea id="keywords">Hello_x000D_
<input id="data" type="button" value="submit">

Get div tag scroll position using JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <script type="text/javascript">
        function scollPos() {
            var div = document.getElementById("myDiv").scrollTop;
            document.getElementById("pos").innerHTML = div;
    <form id="form1">
    <div id="pos">
    <div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
        Place some large content here

SyntaxError: Unexpected token function - Async Await Nodejs

I too had the same problem.

I was running node v 6.2 alongside using purgecss within my gulpfile. Problem only occurred when I created a new Laravel project; up until that point, I never had an issue with purgecss.

Following @Quentin's statement - how node versions prior to 7.6 do not support async functions - I decided to update my node version to 9.11.2

This worked for me:


$ npm install -g n

$ n 9.11.2


delete 'node_modules' from the route directory


$ npm install

Still not sure how node/purgecss worked prior to updating.. but this did the trick.

Cannot open include file with Visual Studio

If your problem is still there it's certainly because you are trying to compile a different version from your current settings.

For example if you set your Additional Include Directories in Debug x64, be sure that you are compiling with the same configuration.

Check this: Build > Configuration Manager... > There is problably something like this in your active solution configuration: Debug x86 (Win32) platform.

Catching nullpointerexception in Java

The problem with your code is in your loop in Check_Circular. You are advancing through the list using n1 by going one node at a time. By reassigning n2 to you are advancing through it two at a time.

When you do that, may be null, so n2 will be null after the assignment. When the loop repeats and it checks if is not null, it throws the NPE because it can't get to next since n2 is already null.

You want to do something like what Alex posted instead.

Using Environment Variables with Vue.js

In addition to the previous answers, if you're looking to access VUE_APP_* env variables in your sass (either the sass section of a vue component or a scss file), then you can add the following to your vue.config.js (which you may need to create if you don't have one):

let sav = "";
for (let e in process.env) {
    if (/VUE_APP_/i.test(e)) {
        sav += `$${e}: "${process.env[e]}";`;

module.exports = {
    css: {
        loaderOptions: {
            sass: {
                data: sav,

The string sav seems to be prepended to every sass file that before processing, which is fine for variables. You could also import mixins at this stage to make them available for the sass section of each vue component.

You can then use these variables in your sass section of a vue file:

<style lang="scss">
.MyDiv {
    margin: 1em 0 0 0;
    background-image: url($VUE_APP_CDN+"/MyImg.png");

or in a .scss file:

.MyDiv {
    margin: 1em 0 0 0;
    background-image: url($VUE_APP_CDN+"/MyImg.png");


What are WSDL, SOAP and REST?

Wikipedia says "The Web Services Description Language is an XML-based language that provides a model for describing Web services". Put another way, WSDL is to a web service, as javadoc is to a java library.

The really sweet thing about WSDL, though, is that software can generate a client and server using WSDL.

Laravel 4: Redirect to a given url

This worked for me in Laravel 5.8

return \Redirect::to('');

Or instead of / you can use

use Redirect;

Nested rows with bootstrap grid system?

Adding to what @KyleMit said, consider using:

  • col-md-* classes for the larger outer columns
  • col-xs-* classes for the smaller inner columns

This will be useful when you view the page on different screen sizes.

On a small screen, the wrapping of larger outer columns will then happen while maintaining the smaller inner columns, if possible

How to run TestNG from command line

I had faced same problem because I downloaded TestNG plugin from Eclipse. Here what I did to get the Job done :

  1. After adding TestNG to your project library create one folder in your Project names as lib ( name can be anything ) :

  2. Go to "C:\Program Files\Eclipse\eclipse-java-mars-R-win32-x86_64\eclipse\plugins" location and copy com.beust.jcommander_1.72.0.jar and org.testng_6.14.2.r20180216145.jar file to created folder (lib).

Note : Files are testng.jar and jcommander.jar

  1. Now Launch CMD, and navigate to your project directory and then type :
    Java -cp C:\Users\User123\TestNG\lib*;C:\Users\User123\TestNG\bin org.testng.TestNG testng.xml

That's it !
Let me know if you have any more concerns.

Javascript: how to validate dates in format MM-DD-YYYY?

If your date needs to match DD.MM.YYYY and use AngularJS, use the following code:

$scope.validDate = function(value){
            var matches = /^(\d{1,2})[.](\d{1,2})[.](\d{4})$/.exec(value);
            if (matches == null) return false;
            var d = matches[1];
            var m = matches[2] - 1;
            var y = matches[3];
            var composedDate = new Date(y, m, d);
            return composedDate.getDate() == d &&
                composedDate.getMonth() == m &&
                composedDate.getFullYear() == y;

More about the scope object can be found here. Without AngularJS, simply change the first line to:

ValidDate = new function(value) {

And call it using:

var MyDate= ValidDate('29.09.2016');

How to clear the entire array?

[your Array name] = Empty

Then the array will be without content and can be filled again.

Can I get all methods of a class?

Straight from the source: Then I modified it to be self contained, not requiring anything from the command line. ;-)

import java.lang.reflect.*;

Compile with this:
C:\Documents and Settings\glow\My Documents\j>javac

Run like this, and results follow
C:\Documents and Settings\glow\My Documents\j>java DumpMethods
public void
public int
public java.lang.String DumpMethods.baz()
public static void DumpMethods.main(java.lang.String[])

public class DumpMethods {

    public void foo() { }

    public int bar() { return 12; }

    public String baz() { return ""; }

    public static void main(String args[]) {
        try {
            Class thisClass = DumpMethods.class;
            Method[] methods = thisClass.getDeclaredMethods();

            for (int i = 0; i < methods.length; i++) {
        } catch (Throwable e) {

PHP Convert String into Float/Double

Try using

$string = "2968789218";
$float = (double)$string;

Format specifier %02x

Your string is wider than your format width of 2. So there's no padding to be done.

WordPress - Check if user is logged in

get_current_user_id() will return the current user id (an integer), or will return 0 if the user is not logged in.

if (get_current_user_id()) {
   // display navbar here

More details here get_current_user_id().

Comparing strings in C# with OR in an if statement


if (testString.Equals(testString2)){

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

Removing whitespace between HTML elements when using line breaks

The whitespace between the elements is only put there by the HTML editor for visual formatting purposes. You can use jQuery to remove the whitespace:

$("div#MyImages").each(function () {

    var div = $(this);
    var children= div.children();


This detaches the child elements, clears any whitespace that remains before adding the child elements back again.

Unlike the other answers to this question, using this method ensures that the inherited css display and font-size values are maintained. There's also no need to use float and the cumbersome clear that is then required. Of course, you will need to be using jQuery.

Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells

Since you are copying tha same data to all rows, you don't actually need to loop at all. Try this:

    Dim Number_of_Sims As Long
    Dim rng As Range

    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Number_of_Sims = 100000

    Set rng = Range("C4:G4")
    rng.Offset(1, 0).Resize(Number_of_Sims) = rng.Value

    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub

How to copy marked text in notepad++

As of Notepad++ 5.9 they added a feature to 'Remove Unmarked Lines' which can be used to strip away everything that you don't want along with some search and replaces for the other text on each value line.

  1. Use the Search-->Find-->Mark functionality to mark each line you want to keep/copy and remember to tick 'Bookmark Line' before marking the text
  2. Select Search-->Bookmark-->Remove Unmarked Lines
  3. Use Search-->Find-->Replace to replace other text you do not want to keep/copy with nothing
  4. Save the remaining text or copy it.

You can also do a similar thing using Search-->Bookmark-->Copy Bookmarked Lines

So technically you still cannot copy marked text, but you can bookmark lines with marked text and then perform various operations on bookmarked or unmarked lines.

reading from app.config file

The reason is simple, your call to ConfigurationSettings.AppSettings is not returning the required config file. Please try any of the following ways:

  • Make sure your app config has the same name as your application's exe file - with the extension .config appended eg MyApp.exe.config
  • OR you can use ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).AppSettings["StartingMonthColumn"]

Hope this helps

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

I usually face this issue on Android 5.0+ version devices. Since it has multi-user profiles accounts on the same devices. Every app will install as a separate instance for all users. Make sure to uninstall for all the users as below screenshot.

enter image description here

How to make a PHP SOAP call using the SoapClient class

I had the same issue, but I just wrapped the arguments like this and it works now.

    $args = array();
    $args['Header'] = array(
        'CustomerCode' => 'dsadsad',
        'Language' => 'fdsfasdf'
    $args['RequestObject'] = $whatever;

    // this was the catch, double array with "Request"
    $response = $this->client->__soapCall($name, array(array( 'Request' => $args )));

Using this function:


You can see the Request XML whether it's changing or not depending on your arguments.

Use [ trace = 1, exceptions = 0 ] in SoapClient options.

Calendar Recurring/Repeating Events - Best Storage Method

Enhancement: replace timestamp with date

As a small enhancement to the accepted answer that was subsequently refined by ahoffner - it is possible to use a date format rather than timestamp. The advantages are:

  1. readable dates in the database
  2. no issue with the years > 2038 and timestamp
  3. removes need to be careful with timestamps that are based on seasonally adjusted dates i.e. in the UK 28th June starts one hour earlier than 28th December so deriving a timestamp from a date can break the recursion algorithm.

to do this, change the DB repeat_start to be stored as type 'date' and repeat_interval now hold days rather than seconds. i.e. 7 for a repeat of 7 days.

change the sql line:

WHERE (( 1370563200 - repeat_start) % repeat_interval = 0 )


WHERE ( DATEDIFF( '2013-6-7', repeat_start ) % repeat_interval = 0)

everything else remains the same. Simples!

Xampp Access Forbidden php

if used ubuntu operating system then check chmod of /Practice folder change read write permission

Open terminal press shortcut key Ctrl+Alt+T Goto

$ cd /opt/lampp/htdocs/

and change folder read write and execute permission by using chmod command

e.g folder name is practice and path of folder /opt/lampp/htdocs/practice

Type command

$ sudo chmod 777 -R Practice

what is chmod and 777 ? visit this link

How to push JSON object in to array using javascript


  • If there is a single object and you want to push whole object into an array then no need to iterate the object.

Try this :

var feed = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};_x000D_
var data = [];_x000D_

Instead of :

var my_json = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};_x000D_
var data = [];_x000D_
for(var i in my_json) {_x000D_

Table overflowing outside of div

You can prevent tables from expanding beyond their parent div by using table-layout:fixed.

The CSS below will make your tables expand to the width of the div surrounding it.


I found this trick here.

pandas groupby sort within groups

What you want to do is actually again a groupby (on the result of the first groupby): sort and take the first three elements per group.

Starting from the result of the first groupby:

In [60]: df_agg = df.groupby(['job','source']).agg({'count':sum})

We group by the first level of the index:

In [63]: g = df_agg['count'].groupby('job', group_keys=False)

Then we want to sort ('order') each group and take the first three elements:

In [64]: res = g.apply(lambda x: x.sort_values(ascending=False).head(3))

However, for this, there is a shortcut function to do this, nlargest:

In [65]: g.nlargest(3)
job     source
market  A         5
        D         4
        B         3
sales   E         7
        C         6
        B         4
dtype: int64

So in one go, this looks like:

df_agg['count'].groupby('job', group_keys=False).nlargest(3)

Count all occurrences of a string in lots of files with grep

If you want number of occurrences per file (example for string "tcp"):

grep -RIci "tcp" . | awk -v FS=":" -v OFS="\t" '$2>0 { print $2, $1 }' | sort -hr

Example output:

53  ./HTTPClient/src/HTTPClient.cpp
21  ./WiFi/src/WiFiSTA.cpp
19  ./WiFi/src/ETH.cpp
13  ./WiFi/src/WiFiAP.cpp
4   ./WiFi/src/WiFiClient.cpp
4   ./HTTPClient/src/HTTPClient.h
3   ./WiFi/src/WiFiGeneric.cpp
2   ./WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino
2   ./WiFiClientSecure/src/ssl_client.cpp
1   ./WiFi/src/WiFiServer.cpp


  • grep -RIci NEEDLE . - looks for string NEEDLE recursively from current directory (following symlinks), ignoring binaries, counting number of occurrences, ignoring case
  • awk ... - this command ignores files with zero occurrences and formats lines
  • sort -hr - sorts lines in reverse order by numbers in first column

Of course, it works with other grep commands with option -c (count) as well. For example:

grep -c "tcp" *.txt | awk -v FS=":" -v OFS="\t" '$2>0 { print $2, $1 }' | sort -hr

Load dimension value from res/values/dimension.xml from source code

If you just want to change the size font dynamically then you can:

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, resources.getDimension(R.dimen.tutorial_cross_marginTop))

As @achie's answer, you can get the dp from dimens.xml like this:

val dpValue = (resources.getDimension(R.dimen.tutorial_cross_marginTop)/ resources.displayMetrics.density).toInt()

or get sp like this

val spValue = (resources.getDimension(R.dimen.font_size)/ resources.displayMetrics.scaledDensity).toInt()

About #{getDimension}

     * Retrieve a dimensional for a particular resource ID.  Unit 
     * conversions are based on the current {@link DisplayMetrics} associated
     * with the resources.
     * @param id The desired resource identifier, as generated by the aapt
     *           tool. This integer encodes the package, type, and resource
     *           entry. The value 0 is an invalid identifier.
     * @return Resource dimension value multiplied by the appropriate 
     * metric.
     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
     * @see #getDimensionPixelOffset
     * @see #getDimensionPixelSize

Resource dimension value multiplied by the appropriate

How to create a user in Django?

Have you confirmed that you are passing actual values and not None?

from django.shortcuts import render

def createUser(request):
    userName = request.REQUEST.get('username', None)
    userPass = request.REQUEST.get('password', None)
    userMail = request.REQUEST.get('email', None)

    # TODO: check if already existed
    if userName and userPass and userMail:
       u,created = User.objects.get_or_create(userName, userMail)
       if created:
          # user was created
          # set the password here
          # user was retrieved
       # request was empty

    return render(request,'home.html')

Javascript/jQuery: Set Values (Selection) in a multiple Select

Just provide the jQuery val function with an array of values:

var values = "Test,Prof,Off";

And to get the selected values in the same format:

values = $('#strings').val();

How To fix white screen on app Start up?

you should disable Instant Run android studio Settings.

File>Settings>Build,Execution, Deployment>Instant Run unCheck all options shown there.

Note: White screen Issue due to Instant Run is only for Debug builds,this Issue will not appear on release builds.

Find the max of two or more columns with pandas

@DSM's answer is perfectly fine in almost any normal scenario. But if you're the type of programmer who wants to go a little deeper than the surface level, you might be interested to know that it is a little faster to call numpy functions on the underlying .to_numpy() (or .values for <0.24) array instead of directly calling the (cythonized) functions defined on the DataFrame/Series objects.

For example, you can use ndarray.max() along the first axis.

# Data borrowed from @DSM's post.
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
   A  B
0  1 -2
1  2  8
2  3  1

df['C'] = df[['A', 'B']].values.max(1)
# Or, assuming "A" and "B" are the only columns, 
# df['C'] = df.values.max(1) 

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3 

If your data has NaNs, you will need numpy.nanmax:

df['C'] = np.nanmax(df.values, axis=1)

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3 

You can also use numpy.maximum.reduce. numpy.maximum is a ufunc (Universal Function), and every ufunc has a reduce:

df['C'] = np.maximum.reduce(df['A', 'B']].values, axis=1)
# df['C'] = np.maximum.reduce(df[['A', 'B']], axis=1)
# df['C'] = np.maximum.reduce(df, axis=1)

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

enter image description here

np.maximum.reduce and np.max appear to be more or less the same (for most normal sized DataFrames)—and happen to be a shade faster than DataFrame.max. I imagine this difference roughly remains constant, and is due to internal overhead (indexing alignment, handling NaNs, etc).

The graph was generated using perfplot. Benchmarking code, for reference:

import pandas as pd
import perfplot

df_ = pd.DataFrame(np.random.randn(5, 1000))
    setup=lambda n: pd.concat([df_] * n, ignore_index=True),
        lambda df: df.assign(new=df.max(axis=1)),
        lambda df: df.assign(new=df.values.max(1)),
        lambda df: df.assign(new=np.nanmax(df.values, axis=1)),
        lambda df: df.assign(new=np.maximum.reduce(df.values, axis=1)),
    labels=['df.max', 'np.max', 'np.maximum.reduce', 'np.nanmax'],
    n_range=[2**k for k in range(0, 15)],
    xlabel='N (* len(df))',

How to pass values across the pages in without using Session

There are multiple ways to achieve this. I can explain you in brief about the 4 types which we use in our daily programming life cycle.

Please go through the below points.

1 Query String.


Response.Redirect("SecondForm.aspx?Parameter=" + TextBox1.Text);


TextBox1.Text = Request.QueryString["Parameter"].ToString();

This is the most reliable way when you are passing integer kind of value or other short parameters. More advance in this method if you are using any special characters in the value while passing it through query string, you must encode the value before passing it to next page. So our code snippet of will be something like this:


Response.Redirect("SecondForm.aspx?Parameter=" + Server.UrlEncode(TextBox1.Text));


TextBox1.Text = Server.UrlDecode(Request.QueryString["Parameter"].ToString());

URL Encoding

  1. Server.URLEncode
  2. HttpServerUtility.UrlDecode

2. Passing value through context object

Passing value through context object is another widely used method.


TextBox1.Text = this.Context.Items["Parameter"].ToString();


this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer("SecondForm.aspx", true);

Note that we are navigating to another page using Server.Transfer instead of Response.Redirect.Some of us also use Session object to pass values. In that method, value is store in Session object and then later pulled out from Session object in Second page.

3. Posting form to another page instead of PostBack

Third method of passing value by posting page to another form. Here is the example of that:


private void Page_Load(object sender, System.EventArgs e)
   buttonSubmit.Attributes.Add("onclick", "return PostPage();");

And we create a javascript function to post the form.


function PostPage()
   document.Form1.action = "SecondForm.aspx";
   document.Form1.method = "POST";
TextBox1.Text = Request.Form["TextBox1"].ToString();

Here we are posting the form to another page instead of itself. You might get viewstate invalid or error in second page using this method. To handle this error is to put EnableViewStateMac=false

4. Another method is by adding PostBackURL property of control for cross page post back

In ASP.NET 2.0, Microsoft has solved this problem by adding PostBackURL property of control for cross page post back. Implementation is a matter of setting one property of control and you are done.


<asp:Button id=buttonPassValue style=”Z-INDEX: 102" runat=”server” Text=”Button”         PostBackUrl=”~/SecondForm.aspx”></asp:Button>


TextBox1.Text = Request.Form["TextBox1"].ToString();

In above example, we are assigning PostBackUrl property of the button we can determine the page to which it will post instead of itself. In next page, we can access all controls of the previous page using Request object.

You can also use PreviousPage class to access controls of previous page instead of using classic Request object.


TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1");
TextBox1.Text = textBoxTemp.Text;

As you have noticed, this is also a simple and clean implementation of passing value between pages.



Pass form data to another page with php

The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol



<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">




 Hello <?php echo $_POST["name"]; ?>!<br>
 Your mail is <?php echo $_POST["mail"]; ?>.



Hello "name" !

Your email is "[email protected]" .

Android eclipse DDMS - Can't access data/data/ on phone to pull files

You must edit permission of data folder.

I use "Root Explorer" (see market) app on root mode.

On top select "Monunted as r/w"

then press over data folder (long click) and find Permission option

Have a somenthing like that

        read    write  execute




Make sure that "Others" have a check for read

Then go Eclpse and try again.

Sorry about my english,I hope can help you.

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

Advantages of this solution

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

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

Examples and Code

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

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

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

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

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

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

TypeScipt version

Failed Apache2 start, no error log

On Apache on Linux there might be a problem that the configuration cannot be checked because of a problem with environment variables not being set. This is a false positive which only occurs when running apache2 -S from commandline (See previous answer from @simhumileco). For instance Config variable ${APACHE_RUN_DIR} is not defined.

In order to fix this run source /etc/apache2/envvars from the commandline and then run `apache2 -S' to get to the real (possible) problems.

root@fileserver:~# apache2 -S
[Thu Apr 30 10:42:06.822719 2020] [core:warn] [pid 24624] AH00111: Config variable ${APACHE_RUN_DIR} is not defined
apache2: Syntax error on line 80 of /etc/apache2/apache2.conf: DefaultRuntimeDir must be a valid directory, absolute or relative to ServerRoot
root@fileserver:~# source /etc/apache2/envvars
root@fileserver:/root# apache2 -S
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using Set the 'ServerName' directive globally to suppress this message
VirtualHost configuration:
ServerRoot: "/etc/apache2"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/var/log/apache2/error.log"
Mutex ldap-cache: using_defaults
Mutex default: dir="/var/run/apache2/" mechanism=default
Mutex mpm-accept: using_defaults
Mutex watchdog-callback: using_defaults
PidFile: "/var/run/apache2/"
User: name="www-data" id=33
Group: name="www-data" id=33

How to make <input type="file"/> accept only these types?

As stated on w3schools:

audio/* - All sound files are accepted

video/* - All video files are accepted

image/* - All image files are accepted

MIME_type - A valid MIME type, with no parameters. Look at IANA MIME types for a complete list of standard MIME types

Accessing MP3 metadata with Python

A problem with eyed3 is that it will throw NotImplementedError("Unable to write ID3 v2.2") for common MP3 files.

In my experience, the mutagen class EasyID3 works more reliably. Example:

from mutagen.easyid3 import EasyID3

audio = EasyID3("example.mp3")
audio['title'] = u"Example Title"
audio['artist'] = u"Me"
audio['album'] = u"My album"
audio['composer'] = u"" # clear

All other tags can be accessed this way and saved, which will serve most purposes. More information can be found in the Mutagen Tutorial.

Replacing objects in array

Thanks to ES6 we can made it with easy way -> for example on util.js module ;))).

  1. Merge 2 array of entity

    export const mergeArrays = (arr1, arr2) => 
       arr1 && => arr2 && arr2.find(p => === || obj);

gets 2 array and merges it.. Arr1 is main array which is priority is high on merge process

  1. Merge array with same type of entity

    export const mergeArrayWithObject = (arr, obj) => arr && => === ? obj : t);

it merges the same kind of array of type with some kind of type for

example: array of person ->

[{id:1, name:"Bir"},{id:2, name: "Iki"},{id:3, name:"Uc"}]   
second param Person {id:3, name: "Name changed"}   

result is

[{id:1, name:"Bir"},{id:2, name: "Iki"},{id:3, name:"Name changed"}]

Permission is only granted to system app

To ignore this error for one instance only, add the tools:ignore="ProtectedPermissions" attribute to your permission declaration. Here is an example:

<uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE"
    tools:ignore="ProtectedPermissions" />

You have to add tools namespace in the manifest root element

<manifest xmlns:android=""

What is the difference between '@' and '=' in directive scope in AngularJS?

Simply we can use:-

  1. @ :- for String values for one way Data binding. in one way data binding you can only pass scope value to directive

  2. = :- for object value for two way data binding. in two way data binding you can change the scope value in directive as well as in html also.

  3. & :- for methods and functions.


In our Component definition for Angular version 1.5 And above
there are four different type of bindings:

  1. = Two-way data binding :- if we change the value,it automatically update
  2. < one way binding :- when we just want to read a parameter from a parent scope and not update it.

  3. @ this is for String Parameters

  4. & this is for Callbacks in case your component needs to output something to its parent scope

Compare dates with javascript

you can done this way also.

if (dateFormat(first, "yyyy-mm-dd") > dateFormat(second, "yyyy-mm-dd")) {


if (dateFormat(first, "mm-dd-yyyy") >  dateFormat(second, "mm-dd-yyyy")) {

i use following plugin for dateFormat()

        var dateFormat = function () {
        var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
            timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
            timezoneClip = /[^-+\dA-Z]/g,
            pad = function (val, len) {
                val = String(val);
                len = len || 2;
                while (val.length < len) val = "0" + val;
                return val;

        // Regexes and supporting functions are cached through closure
        return function (date, mask, utc) {
            var dF = dateFormat;

            // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
            if (arguments.length == 1 && == "[object String]" && !/\d/.test(date)) {
                mask = date;
                date = undefined;

            // Passing date through Date applies Date.parse, if necessary
            date = date ? new Date(date) : new Date;
            if (isNaN(date)) throw SyntaxError("invalid date");

            mask = String(dF.masks[mask] || mask || dF.masks["default"]);

            // Allow setting the utc argument via the mask
            if (mask.slice(0, 4) == "UTC:") {
                mask = mask.slice(4);
                utc = true;

            var _ = utc ? "getUTC" : "get",
                d = date[_ + "Date"](),
                D = date[_ + "Day"](),
                m = date[_ + "Month"](),
                y = date[_ + "FullYear"](),
                H = date[_ + "Hours"](),
                M = date[_ + "Minutes"](),
                s = date[_ + "Seconds"](),
                L = date[_ + "Milliseconds"](),
                o = utc ? 0 : date.getTimezoneOffset(),
                flags = {
                    d:    d,
                    dd:   pad(d),
                    ddd:  dF.i18n.dayNames[D],
                    dddd: dF.i18n.dayNames[D + 7],
                    m:    m + 1,
                    mm:   pad(m + 1),
                    mmm:  dF.i18n.monthNames[m],
                    mmmm: dF.i18n.monthNames[m + 12],
                    yy:   String(y).slice(2),
                    yyyy: y,
                    h:    H % 12 || 12,
                    hh:   pad(H % 12 || 12),
                    H:    H,
                    HH:   pad(H),
                    M:    M,
                    MM:   pad(M),
                    s:    s,
                    ss:   pad(s),
                    l:    pad(L, 3),
                    L:    pad(L > 99 ? Math.round(L / 10) : L),
                    t:    H < 12 ? "a"  : "p",
                    tt:   H < 12 ? "am" : "pm",
                    T:    H < 12 ? "A"  : "P",
                    TT:   H < 12 ? "AM" : "PM",
                    Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                    o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                    S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]

            return mask.replace(token, function ($0) {
                return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);

    // Some common format strings
    dateFormat.masks = {
        "default":      "ddd mmm dd yyyy HH:MM:ss",
        shortDate:      "m/d/yy",
        mediumDate:     "mmm d, yyyy",
        longDate:       "mmmm d, yyyy",
        fullDate:       "dddd, mmmm d, yyyy",
        shortTime:      "h:MM TT",
        mediumTime:     "h:MM:ss TT",
        longTime:       "h:MM:ss TT Z",
        isoDate:        "yyyy-mm-dd",
        isoTime:        "HH:MM:ss",
        isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
        isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"

    // Internationalization strings
    dateFormat.i18n = {
        dayNames: [
            "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
            "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
        monthNames: [
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
            "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"

    // For convenience...
    Date.prototype.format = function (mask, utc) {
        return dateFormat(this, mask, utc);

Spark DataFrame groupBy and sort in the descending order (pyspark)

By far the most convenient way is using this:


Doesn't require special imports.

Drawing rotated text on a HTML5 canvas

While this is sort of a follow up to the previous answer, it adds a little (hopefully).

Mainly what I want to clarify is that usually we think of drawing things like draw a rectangle at 10, 3.

So if we think about that like this: move origin to 10, 3, then draw rectangle at 0, 0. Then all we have to do is add a rotate in between.

Another big point is the alignment of the text. It's easiest to draw the text at 0, 0, so using the correct alignment can allow us to do that without measuring the text width.

We should still move the text by an amount to get it centered vertically, and unfortunately canvas does not have great line height support, so that's a guess and check thing ( correct me if there is something better ).

I've created 3 examples that provide a point and a text with 3 alignments, to show what the actual point on the screen is where the font will go.

enter image description here

var font, lineHeight, x, y;

x = 100;
y = 100;
font = 20;
lineHeight = 15; // this is guess and check as far as I know
this.context.font = font + 'px Arial';

// Right Aligned;
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);

this.context.textAlign = 'right';
this.context.fillText('right', 0, lineHeight / 2);


this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);

// Center
this.context.fillStyle = 'black';
x = 150;
y = 100;;
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);

this.context.textAlign = 'center';
this.context.fillText('center', 0, lineHeight / 2);


this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);

// Left
this.context.fillStyle = 'black';
x = 200;
y = 100;;
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);

this.context.textAlign = 'left';
this.context.fillText('left', 0, lineHeight / 2);


this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);

The line this.context.fillText('right', 0, lineHeight / 2); is basically 0, 0, except we move slightly for the text to be centered near the point

How do I calculate the date six months from the current date using the datetime Python module?

General function to get next date after/before x months.

from datetime import date

def after_month(given_date, month):
    yyyy = int(((given_date.year * 12 + given_date.month) + month)/12)
    mm = int(((given_date.year * 12 + given_date.month) + month)%12)

    if mm == 0:
        yyyy -= 1
        mm = 12
    return given_date.replace(year=yyyy, month=mm)

if __name__ == "__main__":
    today =

    for mm in [-12, -1, 0, 1, 2, 12, 20 ]:
        next_date = after_month(today, mm)

How can I submit form on button click when using preventDefault()?

Replace this :


with this:

$('#subscription_order_form').on('keydown', function(e){
    if (e.which===13) e.preventDefault();


That will prevent the form from submitting when Enter key is pressed as it prevents the default action of the key, but the form will submit normally on click.

Java - Search for files in a directory

This looks like a homework question, so I'll just give you a few pointers:

Try to give good distinctive variable names. Here you used "fileName" first for the directory, and then for the file. That is confusing, and won't help you solve the problem. Use different names for different things.

You're not using Scanner for anything, and it's not needed here, get rid of it.

Furthermore, the accept method should return a boolean value. Right now, you are trying to return a String. Boolean means that it should either return true or false. For example return a > 0; may return true or false, depending on the value of a. But return fileName; will just return the value of fileName, which is a String.

C# An established connection was aborted by the software in your host machine

An established connection was aborted by the software in your host machine

That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.

The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.

You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.

What does "where T : class, new()" mean?

new(): Specifying the new() constraint means type T must use a parameterless constructor, so an object can be instantiated from it - see Default constructors.

class: Means T must be a reference type so it can't be an int, float, double, DateTime or other struct (value type).

public void MakeCars()
    //This won't compile as researchEngine doesn't have a public constructor and so can't be instantiated.
    CarFactory<ResearchEngine> researchLine = new CarFactory<ResearchEngine>();
    var researchEngine = researchLine.MakeEngine();

    //Can instantiate new object of class with default public constructor
    CarFactory<ProductionEngine> productionLine = new CarFactory<ProductionEngine>();
    var productionEngine = productionLine.MakeEngine();

public class ProductionEngine { }
public class ResearchEngine
    private ResearchEngine() { }

public class CarFactory<TEngine> where TEngine : class, new()
    public TEngine MakeEngine()
        return new TEngine();

How to undo a successful "git cherry-pick"?

To undo your last commit, simply do git reset --hard HEAD~.

Edit: this answer applied to an earlier version of the question that did not mention preserving local changes; the accepted answer from Tim is indeed the correct one. Thanks to qwertzguy for the heads up.

how to hide keyboard after typing in EditText in android?

You might also want to define the imeOptions within the EditText. This way, the keyboard will go away once you press on Done:


How to set column header text for specific column in Datagridview C#

there is HeaderText property in Column object, you can find the column and set its HeaderText after initializing grid or do it in windows form designer via designer for DataGrid.

    public Form1()

        grid.Columns[0].HeaderText = "First Column"; 

More details are here at MSDN. More details about DataGrid are here.

Taking multiple inputs from user in python

You can read multiple inputs in Python 3.x by using below code which splits input string and converts into the integer and values are printed

user_input = input("Enter Numbers\n").split(',')
#strip is used to remove the white space. Not mandatory
all_numbers = [int(x.strip()) for x in user_input]
for i in all_numbers:

View the change history of a file using Git versioning

SourceTree users

If you use SourceTree to visualize your repository (it's free and quite good) you can right click a file and select Log Selected

enter image description here

The display (below) is much friendlier than gitk and most the other options listed. Unfortunately (at this time) there is no easy way to launch this view from the command line — SourceTree's CLI currently just opens repos.

enter image description here

How do I retrieve a textbox value using JQuery?

Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:

For radio button:

var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();

For textbox:

var txt=$('input:text[name=DrugDurationLength]').val();

Click in OK button inside an Alert (Selenium IDE)

Use the Alert Interface, First switchTo() to alert and then either use accept() to click on OK or use dismiss() to CANCEL it

Alert alert_box = driver.switchTo().alert();


Alert alert_box = driver.switchTo().alert();

Easiest way to convert a Blob into a byte array

the mySql blob class has the following function :


use it like this:

//(assuming you have a ResultSet named RS)
Blob blob = rs.getBlob("SomeDatabaseField");

int blobLength = (int) blob.length();  
byte[] blobAsBytes = blob.getBytes(1, blobLength);

//release the blob and free up memory. (since JDBC 4.0);

Extracting time from POSIXct

I can't find anything that deals with clock times exactly, so I'd just use some functions from package:lubridate and work with seconds-since-midnight:

clockS = function(t){hour(t)*3600+minute(t)*60+second(t)}

You might then want to look at some of the axis code to figure out how to label axes nicely.

Set a:hover based on class

Set a:hover based on class you can simply try:

a.main-nav-item:hover { }

read file from assets

getAssets() method will work when you are calling inside the Activity class.

If you calling this method in non-Activity class then you need to call this method from Context which is passed from Activity class. So below is the line by you can access the method.


ContextInstance may be passed as this of Activity class.

How do I convert a long to a string in C++?

In C++11, there are actually std::to_string and std::to_wstring functions in <string>.

string to_string(int val);
string to_string(long val);
string to_string(long long val);
string to_string(unsigned val);
string to_string(unsigned long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string (long double val);

Force IE8 Into IE7 Compatiblity Mode

my code has this tag

meta http-equiv="X-UA-Compatible" content="IE=7" />

is there a way where i can skip this tag and yet layouts get displayed well and fine using that tag the display will work upto IE 7 but i want to run it wel in further versions...

Adding a tooltip to an input box

<input type="name" placeholder="First Name" title="First Name" />

title="First Name" solves my proble. it worked with bootstrap.

Java: Difference between the setPreferredSize() and setSize() methods in components

Usage depends on whether the component's parent has a layout manager or not.

  • setSize() -- use when a parent layout manager does not exist;
  • setPreferredSize() (also its related setMinimumSize and setMaximumSize) -- use when a parent layout manager exists.

The setSize() method probably won't do anything if the component's parent is using a layout manager; the places this will typically have an effect would be on top-level components (JFrames and JWindows) and things that are inside of scrolled panes. You also must call setSize() if you've got components inside a parent without a layout manager.

Generally, setPreferredSize() will lay out the components as expected if a layout manager is present; most layout managers work by getting the preferred (as well as minimum and maximum) sizes of their components, then using setSize() and setLocation() to position those components according to the layout's rules.

For example, a BorderLayout tries to make the bounds of its "north" region equal to the preferred size of its north component---they may end up larger or smaller than that, depending on the size of the JFrame, the size of the other components in the layout, and so on.

What is a callback function?

Callback Function A function which passed to another function as an argument.

function test_function(){       
 alert("Hello world");  

setTimeout(test_function, 2000);

Note: In above example test_function used as an argument for setTimeout function.

Unable to copy a file from obj\Debug to bin\Debug

after day with search and build and rebuild i found that you just need to turn off turn on the visual studio its look like it catch the service in different thread

Reference — What does this symbol mean in PHP?

Bitwise Operator

What is a bit? A bit is a representation of 1 or 0. Basically OFF(0) and ON(1)

What is a byte? A byte is made up of 8 bits and the highest value of a byte is 255, which would mean every bit is set. We will look at why a byte's maximum value is 255.

|      1 Byte ( 8 bits )                  |
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|     

This representation of 1 Byte

1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255 (1 Byte)

A few examples for better understanding

The "AND" operator: &

$a =  9;
$b = 10;
echo $a & $b;

This would output the number 8. Why? Well let's see using our table example.

|      1 Byte ( 8 bits )                  |
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|     
|      $a    |   0|  0|  0|  0| 1| 0| 0| 1|    
|      $b    |   0|  0|  0|  0| 1| 0| 1| 0|
|      &     |   0|  0|  0|  0| 1| 0| 0| 0|

So you can see from the table the only bit they share together is the 8 bit.

Second example

$a =  36;
$b = 103;
echo $a & $b; // This would output the number 36.
$a = 00100100
$b = 01100111

The two shared bits are 32 and 4, which when added together return 36.

The "Or" operator: |

$a =  9;
$b = 10;
echo $a | $b;

This would output the number 11. Why?

|      1 Byte ( 8 bits )                  |
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|     
|      $a    |   0|  0|  0|  0| 1| 0| 0| 1|    
|      $b    |   0|  0|  0|  0| 1| 0| 1| 0|
|      |     |   0|  0|  0|  0| 1| 0| 1| 1|

You will notice that we have 3 bits set, in the 8, 2, and 1 columns. Add those up: 8+2+1=11.

postgresql port confusion 5433 or 5432?

The default port of Postgres is commonly configured in:

sudo vi /<path to your installation>/data/postgresql.conf

On Ubuntu this might be:

sudo vi /<path to your installation>/main/postgresql.conf

Search for port in this file.

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

execute function after complete page load

If you can use jQuery, look at load. You could then set your function to run after your element finishes loading.

For example, consider a page with a simple image:

<img src="book.png" alt="Book" id="book" />

The event handler can be bound to the image:

$('#book').load(function() {
  // Handler for .load() called.

If you need all elements on the current window to load, you can use

$(window).load(function () {
  // run code

If you cannot use jQuery, the plain Javascript code is essentially the same amount of (if not less) code:

window.onload = function() {
  // run code

How to validate date with format "mm/dd/yyyy" in JavaScript?

All credits go to elian-ebbing

Just for the lazy ones here I also provide a customized version of the function for the format yyyy-mm-dd.

function isValidDate(dateString)
    // First check for the pattern
    var regex_date = /^\d{4}\-\d{1,2}\-\d{1,2}$/;

        return false;

    // Parse the date parts to integers
    var parts   = dateString.split("-");
    var day     = parseInt(parts[2], 10);
    var month   = parseInt(parts[1], 10);
    var year    = parseInt(parts[0], 10);

    // Check the ranges of month and year
    if(year < 1000 || year > 3000 || month == 0 || month > 12)
        return false;

    var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

    // Adjust for leap years
    if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
        monthLength[1] = 29;

    // Check the range of the day
    return day > 0 && day <= monthLength[month - 1];

How do implement a breadth first traversal?

Use the following algorithm to traverse in breadth first search-

  1. First add the root node into the queue with the put method.
  2. Iterate while the queue is not empty.
  3. Get the first node in the queue, and then print its value.
  4. Add both left and right children into the queue (if the current nodehas children).
  5. Done. We will print the value of each node, level by level,by poping/removing the element

Code is written below-

    Queue<TreeNode> queue= new LinkedList<>();
    private void breadthWiseTraversal(TreeNode root) {
        TreeNode temp = root;
        ((LinkedList<TreeNode>) queue).add(temp);
            TreeNode ref= queue.remove();
            System.out.print(" ");
            if(ref.left!=null) {
                ((LinkedList<TreeNode>) queue).add(ref.left);
            if(ref.right!=null) {
                ((LinkedList<TreeNode>) queue).add(ref.right);

Validate a username and password against Active Directory?

Windows authentication can fail for various reasons: an incorrect user name or password, a locked account, an expired password, and more. To distinguish between these errors, call the LogonUser API function via P/Invoke and check the error code if the function returns false:

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

using Microsoft.Win32.SafeHandles;

public static class Win32Authentication
    private class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
        private SafeTokenHandle() // called by P/Invoke
            : base(true)

        protected override bool ReleaseHandle()
            return CloseHandle(this.handle);

    private enum LogonType : uint
        Network = 3, // LOGON32_LOGON_NETWORK

    private enum LogonProvider : uint
        WinNT50 = 3, // LOGON32_PROVIDER_WINNT50

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool CloseHandle(IntPtr handle);

    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool LogonUser(
        string userName, string domain, string password,
        LogonType logonType, LogonProvider logonProvider,
        out SafeTokenHandle token);

    public static void AuthenticateUser(string userName, string password)
        string domain = null;
        string[] parts = userName.Split('\\');
        if (parts.Length == 2)
            domain = parts[0];
            userName = parts[1];

        SafeTokenHandle token;
        if (LogonUser(userName, domain, password, LogonType.Network, LogonProvider.WinNT50, out token))
            throw new Win32Exception(); // calls Marshal.GetLastWin32Error()

Sample usage:

    Win32Authentication.AuthenticateUser("EXAMPLE\\user", "P@ssw0rd");
    // Or: Win32Authentication.AuthenticateUser("[email protected]", "P@ssw0rd");
catch (Win32Exception ex)
    switch (ex.NativeErrorCode)
        case 1326: // ERROR_LOGON_FAILURE (incorrect user name or password)
            // ...
        case 1327: // ERROR_ACCOUNT_RESTRICTION
            // ...
        case 1330: // ERROR_PASSWORD_EXPIRED
            // ...
        case 1331: // ERROR_ACCOUNT_DISABLED
            // ...
        case 1907: // ERROR_PASSWORD_MUST_CHANGE
            // ...
        case 1909: // ERROR_ACCOUNT_LOCKED_OUT
            // ...
        default: // Other

Note: LogonUser requires a trust relationship with the domain you're validating against.

jQuery Ajax error handling, show custom exception messages


     doPost(HttpServletRequest request, HttpServletResponse response){ 
            try{ //logic
            }catch(ApplicationException exception){ 
               //just added semicolon to end of line



 jQuery.ajax({// just showing error property
           error: function(jqXHR,error, errorThrown) {  
                   alert("Something went wrong");

Generic Ajax Error Handling

If I need to do some generic error handling for all the ajax requests. I will set the ajaxError handler and display the error on a div named errorcontainer on the top of html content.

        function(e, x, settings, exception) {
            var message;
            var statusErrorMap = {
                '400' : "Server understood the request, but request content was invalid.",
                '401' : "Unauthorized access.",
                '403' : "Forbidden resource can't be accessed.",
                '500' : "Internal server error.",
                '503' : "Service unavailable."
            if (x.status) {
                message =statusErrorMap[x.status];
                                      message="Unknown Error \n.";
            }else if(exception=='parsererror'){
                message="Error.\nParsing JSON Request failed.";
            }else if(exception=='timeout'){
                message="Request Time out.";
            }else if(exception=='abort'){
                message="Request was aborted by the server";
            }else {
                message="Unknown Error \n.";

Find unused code

Resharper is good for this like others have stated. Be careful though, these tools don't find you code that is used by reflection, e.g. cannot know if some code is NOT used by reflection.

Remove duplicated rows using dplyr

Most of the time, the best solution is using distinct() from dplyr, as has already been suggested.

However, here's another approach that uses the slice() function from dplyr.

# Generate fake data for the example
  df <- data.frame(
    x = sample(0:1, 10, replace = T),
    y = sample(0:1, 10, replace = T),
    z = 1:10

# In each group of rows formed by combinations of x and y
# retain only the first row

    df %>%
      group_by(x, y) %>%

Difference from using the distinct() function

The advantage of this solution is that it makes it explicit which rows are retained from the original dataframe, and it can pair nicely with the arrange() function.

Let's say you had customer sales data and you wanted to retain one record per customer, and you want that record to be the one from their latest purchase. Then you could write:

customer_purchase_data %>%
   arrange(desc(Purchase_Date)) %>%
   group_by(Customer_ID) %>%

Cannot connect to repo with TortoiseSVN

As stated by David W. "First of all, check your URL" - Our dns entry changed breaking all svn repo connections. Connecting on ip instead of url as Wes stated worked - (now we have to fix our dns)

Convert Map<String,Object> to Map<String,String>

Use the Java 8 way of converting a Map<String, Object> to Map<String, String>. This solution handles null values.

Map<String, String> keysValuesStrings = keysValues.entrySet().stream()
    .filter(entry -> entry.getValue() != null)
    .collect(Collectors.toMap(Entry::getKey, entry -> entry.getValue().toString()));

Coding Conventions - Naming Enums

As already stated, enum instances should be uppercase according to the docs on the Oracle website (

However, while looking through a JavaEE7 tutorial on the Oracle website (, I stumbled across the "Duke's bookstore" tutorial and in a class (tutorial\examples\case-studies\dukes-bookstore\src\main\java\javaeetutorial\dukesbookstore\components\, I found the following enum definition:

private enum PropertyKeys {
    alt, coords, shape, targetImage;

According to the conventions, it should have looked like:

public enum PropertyKeys {
    ALT("alt"), COORDS("coords"), SHAPE("shape"), TARGET_IMAGE("targetImage");

    private final String val;

    private PropertyKeys(String val) {
        this.val = val;

    public String toString() {
        return val;

So it seems even the guys at Oracle sometimes trade convention with convenience.

Minimum Hardware requirements for Android development

Have a look at the android SDK system requirements Here

I'm guessing some extra RAM would help your developing experience...Also the emulator does take some time to start on even the speediest systems.

Detect browser or tab closing

Since no one has mentioned it yet (8+ years later): A WebSocket can be another effective way to detect a closed tab. As long as the tab is open and pointed at the host, the client is able to maintain an active WebSocket connection to the host.

Caveat: Please note that this solution is really only viable for a project if a WebSocket doesn't require any additional significant overhead from what you are already doing.

Within a sensible timeout period (e.g. 2 minutes), the server side can determine that the client has gone away after the WebSocket has disconnected and perform whatever action is desired such as removing uploaded temp files. (In my extremely specialized use-case, my goal was to terminate a localhost app server three seconds after the WebSocket connection drops and all CGI/FastCGI activity terminates - any other keep-alive connections don't affect me.)

I had problems getting the onunload event handler to work properly with beacons (as recommended by this answer). Closing the tab did not appear to trigger the beacon and open tabs triggered it in ways that could potentially cause problems. A WebSocket solved the problem I was running into more cleanly because the connection closes roughly around the same time that the tab closes and switching pages within the application simply opens a new WebSocket connection well within the delay window.

How to display loading message when an iFrame is loading?

If it's only a placeholder you are trying to achieve: a crazy approach is to inject text as an svg-background. It allows for some flexbility, and from what I've read the browser support should be fairly decent (haven't tested it though):

  • Chrome >= 27
  • FireFox >= 30
  • Internet Explorer >= 9
  • Safari >= 5.1


<iframe class="iframe-placeholder" src=""></iframe>


   background: url('data:image/svg+xml;charset=utf-8,<svg xmlns="" width="100%" height="100%" viewBox="0 0 100% 100%"><text fill="%23FF0000" x="50%" y="50%" font-family="\'Lucida Grande\', sans-serif" font-size="24" text-anchor="middle">PLACEHOLDER</text></svg>') 0px 0px no-repeat;

What can you change?

Inside the background-value:

  • font size: look for font-size="" and change the value to anything you want

  • font color: look for fill="". Don't forget to replace the # with %23 if you're using hexadecimal color notation. %23 stands for a # in URL encoding which is necessary for the svg-string to be able to be parsed in FireFox.

  • font family: look for font-family="" remember to escape the single quotes if you have a font that consists of multiple words (like with \'Lucida Grande\')

  • text: look for the element value of the text-element where you see the PLACEHOLDER string. You can replace the PLACEHOLDER string with anything that is url-compliant (special characters need to be converted to percent notation)

Example on fiddle


  • No extra HTML-elements
  • No js
  • Text can easily (...) be adjusted without the need of an external program
  • It's SVG, so you can easily put any SVG you want in there.


  • Browser support
  • It's complex
  • It's hacky
  • If the iframe-src doesn't have a background set, the placeholder will shine through (which is not inherent to this method, but just standard behaviour when you use a bg on the iframe)

I would only recommend this only if it's absolutely necessary to show text as a placeholder in an iframe which requires a little bit of flexbility (multiple languages, ...). Just take a moment and reflect on it: is all this really necessary? If I had a choice, I'd go for @Christina's method

A Simple AJAX with JSP example

loadXMLDoc JS function should return false, otherwise it will result in postback.

How to list all users in a Linux group?

I have tried grep 'sample-group-name' /etc/group,that will list all the member of the group you specified based on the example here

Passing an array of parameters to a stored procedure

You could try this:


SELECT @List = '1,2,3,4,5,6,7,8'

WHERE ID NOT IN (' + @List + ')'

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

Prefixing with 'r' works very well, but it needs to be in the correct syntax. For example:

passwordFile = open(r'''C:\Users\Bob\SecretPasswordFile.txt''')

No need for \\ here - maintains readability and works well.

How to install mysql-connector via pip

pip install mysql-connector

Last but not least,You can also install mysql-connector via source code

Download source code from:

How can one develop iPhone apps in Java?

Specifically talks about Java based Android apps being ported to the iPhone using non-Apple hardware.

You might also want to check out MonoTouch (C# rather than Java...but the two are very similar).

Python regular expressions return true/false

You can use re.match() or Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while checks for a match anywhere in the string (this is what Perl does by default). refer this

In angular $http service, How can I catch the "status" of error?

Since $http.get returns a 'promise' with the extra convenience methods success and error (which just wrap the result of then) you should be able to use (regardless of your Angular version):

    .then(function success(response) {
        console.log('succeeded', response); // supposed to have: data, status, headers, config, statusText
    }, function error(response) {
        console.log('failed', response); // supposed to have: data, status, headers, config, statusText

Not strictly an answer to the question, but if you're getting bitten by the "my version of Angular is different than the docs" issue you can always dump all of the arguments, even if you don't know the appropriate method signature:

  .success(function(data, foo, bar) {
    console.log(arguments); // includes data, status, etc including unlisted ones if present
  .error(function(baz, foo, bar, idontknow) {
    console.log(arguments); // includes data, status, etc including unlisted ones if present

Then, based on whatever you find, you can 'fix' the function arguments to match.

"The public type <<classname>> must be defined in its own file" error in Eclipse

Save this class in the file Also you cant have more than one public classes in one file.

How to properly add cross-site request forgery (CSRF) token using PHP

CSRF protection





<input type="hidden" name="token" value="{{ form_token() }}" />


<meta name="csrf-token" content="{{ csrf_token() }}">


    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')


use Illuminate\Http\Request;

Route::get('/token', function (Request $request) {
    $token = $request->session()->token();

    $token = csrf_token();

    // ...




namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
     * The URIs that should be excluded from CSRF verification.
     * @var array
    protected $except = [

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

The add_subplot() method has several call signatures:

  1. add_subplot(nrows, ncols, index, **kwargs)
  2. add_subplot(pos, **kwargs)
  3. add_subplot(ax)
  4. add_subplot() <-- since 3.1.0

Calls 1 and 2:

Calls 1 and 2 achieve the same thing as one another (up to a limit, explained below). Think of them as first specifying the grid layout with their first 2 numbers (2x2, 1x8, 3x4, etc), e.g:

# is equivalent to:

Both produce a subplot arrangement of (3 x 4 = 12) subplots in 3 rows and 4 columns. The third number in each call indicates which axis object to return, starting from 1 at the top left, increasing to the right.

This code illustrates the limitations of using call 2:

#!/usr/bin/env python3
import matplotlib.pyplot as plt

def plot_and_text(axis, text):
  '''Simple function to add a straight line
  and text to an axis object'''
  axis.text(0.02, 0.9, text)

f = plt.figure()
f2 = plt.figure()

_max = 12
for i in range(_max):
  axis = f.add_subplot(3,4,i+1, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
  plot_and_text(axis,chr(i+97) + ') ' + '3,4,' +str(i+1))

  # If this check isn't in place, a 
  # ValueError: num must be 1 <= num <= 15, not 0 is raised
  if i < 9:
    axis = f2.add_subplot(341+i, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
    plot_and_text(axis,chr(i+97) + ') ' + str(341+i))



You can see with call 1 on the LHS you can return any axis object, however with call 2 on the RHS you can only return up to index = 9 rendering subplots j), k), and l) inaccessible using this call.

I.e it illustrates this point from the documentation:

pos is a three digit integer, where the first digit is the number of rows, the second the number of columns, and the third the index of the subplot. i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that all integers must be less than 10 for this form to work.

Call 3

In rare circumstances, add_subplot may be called with a single argument, a subplot axes instance already created in the present figure but not in the figure's list of axes.

Call 4 (since 3.1.0):

If no positional arguments are passed, defaults to (1, 1, 1).

i.e., reproducing the call fig.add_subplot(111) in the question.

Printing chars and their ASCII-code in C

Nothing can be more simple than this

#include <stdio.h>  

int main()  
    int i;  

    for( i=0 ; i<=255 ; i++ ) /*ASCII values ranges from 0-255*/  
        printf("ASCII value of character %c = %d\n", i, i);  

    return 0;  

Source: program to print ASCII value of all characters

How do I get an element to scroll into view, using jQuery?

Have a look at the jQuery.scrollTo plugin. Here's a demo.

This plugin has a lot of options that go beyond what native scrollIntoView offers you. For instance, you can set the scrolling to be smooth, and then set a callback for when the scrolling finishes.

You can also have a look at all the JQuery plugins tagged with "scroll".

How to get last month/year in java?

Use Joda Time Library. It is very easy to handle date, time, calender and locale with it and it will be integrated to java in version 8.

DateTime#minusMonths method would help you get previous month.

DateTime month = new DateTime().minusMonths (1); 

What is the difference between .*? and .* regular expressions?

Let's say you have:


<(.*)> would match a></a where as <(.*?)> would match a. The latter stops after the first match of >. It checks for one or 0 matches of .* followed by the next expression.

The first expression <(.*)> doesn't stop when matching the first >. It will continue until the last match of >.

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

Since you're only dealing with a 3x3 matrix of possible locations, it'd be pretty easy to just write a search through all possibilities without taxing you computing power. For each open space, compute through all the possible outcomes after that marking that space (recursively, I'd say), then use the move with the most possibilities of winning.

Optimizing this would be a waste of effort, really. Though some easy ones might be:

  • Check first for possible wins for the other team, block the first one you find (if there are 2 the games over anyway).
  • Always take the center if it's open (and the previous rule has no candidates).
  • Take corners ahead of sides (again, if the previous rules are empty)

Powershell Get-ChildItem most recent file in directory

You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster

CSS how to make an element fade in and then fade out?

Use css @keyframes

.elementToFadeInAndOut {
    opacity: 1;
    animation: fade 2s linear;

@keyframes fade {
  0%,100% { opacity: 0 }
  50% { opacity: 1 }

here is a DEMO

.elementToFadeInAndOut {_x000D_
    height: 200px;_x000D_
    background: red;_x000D_
    -webkit-animation: fadeinout 4s linear forwards;_x000D_
    animation: fadeinout 4s linear forwards;_x000D_
@-webkit-keyframes fadeinout {_x000D_
  0%,100% { opacity: 0; }_x000D_
  50% { opacity: 1; }_x000D_
@keyframes fadeinout {_x000D_
  0%,100% { opacity: 0; }_x000D_
  50% { opacity: 1; }_x000D_
<div class=elementToFadeInAndOut></div>

Reading: Using CSS animations

You can clean the code by doing this:

.elementToFadeInAndOut {_x000D_
    height: 200px;_x000D_
    background: red;_x000D_
    -webkit-animation: fadeinout 4s linear forwards;_x000D_
    animation: fadeinout 4s linear forwards;_x000D_
    opacity: 0;_x000D_
@-webkit-keyframes fadeinout {_x000D_
  50% { opacity: 1; }_x000D_
@keyframes fadeinout {_x000D_
  50% { opacity: 1; }_x000D_
<div class=elementToFadeInAndOut></div>

Selecting empty text input using jQuery


After trying a lots of version I found this the most logical.

Note that text is case-sensitive.

ImportError: No module named scipy

I recommend you to remove scipy via

apt-get purge scipy

and then to install it by

pip install scipy

If you do both then you might confuse you deb package manager due to possibly differing versions.

Xcode/Simulator: How to run older iOS version?

Open xcode and in the top menu go to xcode > Preferences > Downloads and you will be given the option to download old sdks to use with xcode. You can also download command line tools and Device Debugging Support.

enter image description here

Rename file with Git

I had a similar problem going through a tutorial.

# git mv README README.markdown

fatal: bad source, source=README, destination=README.markdown

I included the filetype in the source file:

# git mv README.rdoc README.markdown

and it worked perfectly. Don't forget to commit the changes with i.e.:

# git commit -a -m "Improved the README"

Sometimes it is simple little things like that, that piss us off. LOL

Why can't I change my input value in React even with the onChange listener

I think it is best way for you.

You should add this: this.onTodoChange = this.onTodoChange.bind(this).

And your function has event param(e), and get value:

            updatable : false,
            name :,
            status : this.props.status
    this.onTodoChange = this.onTodoChange.bind(this)
<input className="form-control" type="text" value={} id={'todoName' +} onChange={this.onTodoChange}/>

         const {name, value} =;
        this.setState({[name]: value});

How to get name of the computer in VBA?

A shell method to read the environmental variable for this courtesy of devhut

Debug.Print CreateObject("WScript.Shell").ExpandEnvironmentStrings("%COMPUTERNAME%")

Same source gives an API method:

Option Explicit

#If VBA7 And Win64 Then
    'x64 Declarations
    Declare PtrSafe Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
    'x32 Declaration
    Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#End If

Public Sub test()

    Debug.Print ComputerName
End Sub

Public Function ComputerName() As String
    Dim sBuff                 As String * 255
    Dim lBuffLen              As Long
    Dim lResult               As Long
    lBuffLen = 255
    lResult = GetComputerName(sBuff, lBuffLen)
    If lBuffLen > 0 Then
        ComputerName = Left(sBuff, lBuffLen)
    End If
End Function

How can I listen to the form submit event in javascript?

Why do people always use jQuery when it isn't necessary?
Why can't people just use simple JavaScript?

var ele = /*Your Form Element*/;
    ele.addEventListener("submit", callback, false);  //Modern browsers
}else if(ele.attachEvent){
    ele.attachEvent('onsubmit', callback);            //Old IE

callback is a function that you want to call when the form is being submitted.

About EventTarget.addEventListener, check out this documentation on MDN.

To cancel the native submit event (prevent the form from being submitted), use .preventDefault() in your callback function,

document.querySelector("#myForm").addEventListener("submit", function(e){
        e.preventDefault();    //stop form from submitting

Listening to the submit event with libraries

If for some reason that you've decided a library is necessary (you're already using one or you don't want to deal with cross-browser issues), here's a list of ways to listen to the submit event in common libraries:

  1. jQuery


    Where ele is the form element reference, and callback being the callback function reference. Reference

    <iframe width="100%" height="100%" src="" frameborder="0"></iframe>

  1. AngularJS (1.x)

    <form ng-submit="callback()">
    $scope.callback = function(){ /*...*/ };

    Very straightforward, where $scope is the scope provided by the framework inside your controller. Reference

  2. React

    <form onSubmit={this.handleSubmit}>
    class YourComponent extends Component {
        // stuff
        handleSubmit(event) {
            // do whatever you need here
            // if you need to stop the submit event and 
            // perform/dispatch your own actions
        // more stuff

    Simply pass in a handler to the onSubmit prop. Reference

  3. Other frameworks/libraries

    Refer to the documentation of your framework.


You can always do your validation in JavaScript, but with HTML5 we also have native validation.

<!-- Must be a 5 digit number -->
<input type="number" required pattern="\d{5}">

You don't even need any JavaScript! Whenever native validation is not supported, you can fallback to a JavaScript validator.


How to link home brew python version and set it as default

brew switch to python3 by default, so if you want to still set python2 as default bin python, running:

brew unlink python && brew link python2 --force

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

This is a common issue while setting up Maven. All you need to do is the below :-

  1. M2_HOME :- D:\apache-maven-2.0.11
  2. M2 :- D:\apache-maven-2.0.11\bin
  3. Path :- Append it with ;%M2%

M2_HOME & M2 :- need to be declared as System variables and not as USER / ADMIN Variables.

Path :- This can be the System Variable OR the USER / ADMIN variable [PATH]. Preferably System Variable.

Once you carefully do the setting of these 3 variable, you can verify Maven's installation as below.

On CMD Prompt :-

C:\Documents and Settings\ADMIN>mvn --version

Output :-

Apache Maven 2.0.11 (r909250; 2010-02-12 11:25:50+0530) Java version: 1.6.0_22 Java home: C:\Program Files\Java\jdk1.6.0_22\jre Default locale: en_US, platform encoding: Cp1252 OS name: "windows xp" version: "5.1" arch: "x86" Family: "windows"


Laravel Checking If a Record Exists

In laravel eloquent, has default exists() method, refer followed example.

if(User::where('id', $user_id )->exists()){ // your code... }

Memory errors and list limits?

If you want to circumvent this problem you could also use the shelve. Then you would create files that would be the size of your machines capacity to handle, and only put them on the RAM when necessary, basically writing to the HD and pulling the information back in pieces so you can process it.

Create binary file and check if information is already in it if yes make a local variable to hold it else write some data you deem necessary.

Data ='File01')
   for i in range(0,100):
     Matrix_Shelve = 'Matrix' + str(i)
     if Matrix_Shelve in Data:
        Matrix_local = Data[Matrix_Shelve]
        Data[Matrix_Selve] = 'somenthingforlater'

Hope it doesn't sound too arcaic.

A SQL Query to select a string between two known strings

I had a similar need to parse out a set of parameters stored within an IIS logs' csUriQuery field, which looked like this: id=3598308&user=AD\user&parameter=1&listing=No needed in this format.

I ended up creating a User-defined function to accomplish a string between, with the following assumptions:

  1. If the starting occurrence is not found, a NULL is returned, and
  2. If the ending occurrence is not found, the rest of the string is returned

Here's the code:

CREATE FUNCTION dbo.str_between(@col varchar(max), @start varchar(50), @end varchar(50))  
  RETURNS varchar(max)  
  RETURN substring(@col, charindex(@start, @col) + len(@start), 
         isnull(nullif(charindex(@end, stuff(@col, 1, charindex(@start, @col)-1, '')),0),
         len(stuff(@col, 1, charindex(@start, @col)-1, ''))+1) - len(@start)-1);

For the above question, the usage is as follows:

DECLARE @a VARCHAR(MAX) = 'All I knew was that the dog had been very bad and required harsh punishment immediately regardless of what anyone else thought.'
SELECT dbo.str_between(@a, 'the dog', 'immediately')
-- Yields' had been very bad and required harsh punishment '

How to compare two floating point numbers in Bash?

beware when comparing numbers that are package versions, like checking if grep 2.20 is greater than version 2.6:

$ awk 'BEGIN { print (2.20 >= 2.6) ? "YES" : "NO" }'

$ awk 'BEGIN { print (2.2 >= 2.6) ? "YES" : "NO" }'

$ awk 'BEGIN { print (2.60 == 2.6) ? "YES" : "NO" }'

I solved such problem with such shell/awk function:

# get version of GNU tool
toolversion() {
    local prog="$1" operator="$2" value="$3" version

    version=$($prog --version | awk '{print $NF; exit}')

    awk -vv1="$version" -vv2="$value" 'BEGIN {
        split(v1, a, /\./); split(v2, b, /\./);
        if (a[1] == b[1]) {
            exit (a[2] '$operator' b[2]) ? 0 : 1
        else {
            exit (a[1] '$operator' b[1]) ? 0 : 1

if toolversion grep '>=' 2.6; then
   # do something awesome

Formatting a float to 2 decimal places

string outString= number.ToString("####0.00");

Android Studio and Gradle build error

The only solution I've found is to first create the project in Android Studio, then close the project, then import the project. I searched all over and could not find the root cause and all other solutions people posted didn't work.

Undo a particular commit in Git that's been pushed to remote repos

If the commit you want to revert is a merged commit (has been merged already), then you should either -m 1 or -m 2 option as shown below. This will let git know which parent commit of the merged commit to use. More details can be found HERE.

  • git revert <commit> -m 1
  • git revert <commit> -m 2

Undefined symbols for architecture i386

A bit late to the party but might be valuable to someone with this error..

I just straight copied a bunch of files into an Xcode project, if you forget to add them to your projects Build Phases you will get the error "Undefined symbols for architecture i386". So add your implementation files to Compile Sources, and Xib files to Copy Bundle Resources.

The error was telling me that there was no link to my classes simply because they weren't included in the Compile Sources, quite obvious really but may save someone a headache.

How do I get the name of the rows from the index of a data frame?


  • outputs the row names as pandas Index object.


  • casts to a list.

df.index['Row 2':'Row 5']

  • supports label slicing similar to columns.

Change icon on click (toggle)

$("#togglebutton").click(function () {

I have a button with the id "togglebutton" and an icon from FontAwesome . This can be a way to toggle it . from left arrow to right arrow icon

Replace HTML Table with Divs

Please be aware that although tables are discouraged as a primary means of page layout, they still have their place. Tables can and should be used when and where appropriate and until some of the more popular browsers (ahem, IE, ahem) become more standards compliant, tables are sometimes the best route to a solution.

How to convert hashmap to JSON object in Java

Here my single-line solution with GSON:

myObject = new Gson().fromJson(new Gson().toJson(myHashMap), MyClass.class);

Redirect HTTP to HTTPS on default virtual host without ServerName

This is the complete way to omit unneeded redirects, too ;)

These rules are intended to be used in .htaccess files, as a RewriteRule in a *:80 VirtualHost entry needs no Conditions.

RewriteEngine on
RewriteCond %{HTTPS} off [OR] 
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]


RewriteEngine on

==> enable the engine at all

RewriteCond %{HTTPS} off [OR]

==> match on non-https connections, or (not setting [OR] would cause an implicit AND !)

RewriteCond %{HTTP:X-Forwarded-Proto} !https

==> match on forwarded connections (proxy, loadbalancer, etc.) without https

RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]

==> if one of both Conditions match, do the rewrite of the whole URL, sending a 301 to have this 'learned' by the client (some do, some don't) and the L for the last rule.

intl extension: installing php_intl.dll

Had the same issue ... I found the files needed by searching my drive for icu**.dll and found the ones listed above but with 46 instead of 36 in the php folder. I copy pasted them to the apache/bin file and tried starting apache and it finally started. On the Server Checks page it has now changed from Yellow Check to Green OK. Hope this helps.

What is a semaphore?

Semaphore can also be used as a ... semaphore. For example if you have multiple process enqueuing data to a queue, and only one task consuming data from the queue. If you don't want your consuming task to constantly poll the queue for available data, you can use semaphore.

Here the semaphore is not used as an exclusion mechanism, but as a signaling mechanism. The consuming task is waiting on the semaphore The producing task are posting on the semaphore.

This way the consuming task is running when and only when there is data to be dequeued

Android: remove notification from notification bar

Please try this,

public void removeNotification(Context context, int notificationId) {      
    NotificationManager nMgr = (NotificationManager) context.getApplicationContext()

How do you do exponentiation in C?

To add to what Evan said: C does not have a built-in operator for exponentiation, because it is not a primitive operation for most CPUs. Thus, it's implemented as a library function.

Also, for computing the function e^x, you can use the exp(double), expf(float), and expl(long double) functions.

Note that you do not want to use the ^ operator, which is the bitwise exclusive OR operator.

Handling back button in Android Navigation Component

just create an extension function to the fragment

fun Fragment.onBackPressedAction(action: () -> Boolean) {
    requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object :
        OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            this.isEnabled = action()
            if (!this.isEnabled) {

and after in the fragment put the code into onCreateView (the action must return false to call the activity onBackPressed)

onBackPressedAction { //do something }

How to skip to next iteration in jQuery.each() util?

By 'return non-false', they mean to return any value which would not work out to boolean false. So you could return true, 1, 'non-false', or whatever else you can think up.

Use jquery click to handle anchor onClick()

The HTML should look like:

<div class="solTitle"> <a href="#"  id="solution0">Solution0 </a></div>
<div class="solTitle"> <a href="#"  id="solution1">Solution1 </a></div>

<div id="summary_solution0" style="display:none" class="summary">Summary solution0</div>
<div id="summary_solution1" style="display:none" class="summary">Summary solution1</div>

And the javascript:

    $(".solTitle a").live('click',function(e){
        var contentId = "summary_" + $(this).attr('id');
        $("#" + contentId).show();

See the Example:

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

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

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

Double border with different color

Alternatively, you can use pseudo-elements to do so :) the advantage of the pseudo-element solution is that you can use it to space the inner border at an arbitrary distance away from the actual border, and the background will show through that space. The markup:

body {_x000D_
  background-image: linear-gradient(180deg, #ccc 50%, #fff 50%);_x000D_
  background-repeat: no-repeat;_x000D_
  height: 100vh;_x000D_
.double-border {_x000D_
  background-color: #ccc;_x000D_
  border: 4px solid #fff;_x000D_
  padding: 2em;_x000D_
  width: 16em;_x000D_
  height: 16em;_x000D_
  position: relative;_x000D_
  margin: 0 auto;_x000D_
.double-border:before {_x000D_
  background: none;_x000D_
  border: 4px solid #fff;_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  top: 4px;_x000D_
  left: 4px;_x000D_
  right: 4px;_x000D_
  bottom: 4px;_x000D_
  pointer-events: none;_x000D_
<div class="double-border">_x000D_
  <!-- Content -->_x000D_

If you want borders that are consecutive to each other (no space between them), you can use multiple box-shadow declarations (separated by commas) to do so:

body {_x000D_
  background-image: linear-gradient(180deg, #ccc 50%, #fff 50%);_x000D_
  background-repeat: no-repeat;_x000D_
  height: 100vh;_x000D_
.double-border {_x000D_
  background-color: #ccc;_x000D_
  border: 4px solid #fff;_x000D_
    inset 0 0 0 4px #eee,_x000D_
    inset 0 0 0 8px #ddd,_x000D_
    inset 0 0 0 12px #ccc,_x000D_
    inset 0 0 0 16px #bbb,_x000D_
    inset 0 0 0 20px #aaa,_x000D_
    inset 0 0 0 20px #999,_x000D_
    inset 0 0 0 20px #888;_x000D_
  /* And so on and so forth, if you want border-ception */_x000D_
  margin: 0 auto;_x000D_
  padding: 3em;_x000D_
  width: 16em;_x000D_
  height: 16em;_x000D_
  position: relative;_x000D_
<div class="double-border">_x000D_
  <!-- Content -->_x000D_

Negate if condition in bash script

You can use unequal comparison -ne instead of -eq:

wget -q --tries=10 --timeout=20 --spider
if [[ $? -ne 0 ]]; then
    echo "Sorry you are Offline"
    exit 1

What are the differences between the BLOB and TEXT datatypes in MySQL?

A BLOB is a binary string to hold a variable amount of data. For the most part BLOB's are used to hold the actual image binary instead of the path and file info. Text is for large amounts of string characters. Normally a blog or news article would constitute to a TEXT field

L in this case is used stating the storage requirement. (Length|Size + 3) as long as it is less than 224.


find difference between two text files with one item per line



>awk 'NR == FNR {file1[$0]++; next} !($0 in file1)' file1 file2

>awk 'NR == FNR {file1[$0]++; next} ($0 in file1)' file1 file2

> What's awk command to get 'm1 and m3' ??  as in file1 and not in file2? 

SQL Server: Multiple table joins with a WHERE clause

You need to do a LEFT JOIN.

SELECT Computer.ComputerName, Application.Name, Software.Version
FROM Computer
JOIN dbo.Software_Computer
    ON Computer.ID = Software_Computer.ComputerID
LEFT JOIN dbo.Software
    ON Software_Computer.SoftwareID = Software.ID
RIGHT JOIN dbo.Application
    ON Application.ID = Software.ApplicationID
WHERE Computer.ID = 1 

Here is the explanation:

The result of a left outer join (or simply left join) for table A and B always contains all records of the "left" table (A), even if the join-condition does not find any matching record in the "right" table (B). This means that if the ON clause matches 0 (zero) records in B, the join will still return a row in the result—but with NULL in each column from B. This means that a left outer join returns all the values from the left table, plus matched values from the right table (or NULL in case of no matching join predicate). If the right table returns one row and the left table returns more than one matching row for it, the values in the right table will be repeated for each distinct row on the left table. From Oracle 9i onwards the LEFT OUTER JOIN statement can be used as well as (+).

How to get a .csv file into R?

You need read.csv("C:/somedirectory/some/file.csv") and in general it doesn't hurt to actually look at the help page including its example section at the bottom.

SQLite: How do I save the result of a query as a CSV file?

All the existing answers only work from the sqlite command line, which isn't ideal if you'd like to build a reusable script. Python makes it easy to build a script that can be executed programatically.

import pandas as pd
import sqlite3

conn = sqlite3.connect('your_cool_database.sqlite')

df = pd.read_sql('SELECT * from orders', conn)
df.to_csv('orders.csv', index = False)

You can customize the query to only export part of the sqlite table to the CSV file.

You can also run a single command to export all sqlite tables to CSV files:

for table in c.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall():
    t = table[0]
    df = pd.read_sql('SELECT * from ' + t, conn)
    df.to_csv(t + '_one_command.csv', index = False)

See here for more info.

Socket.IO handling disconnect event

You can also, if you like use socket id to manage your player list like this.

io.on('connection', function(socket){
  socket.on('disconnect', function() {
    for(var i = 0; i < onlineplayers.length; i++ ){
      if(onlineplayers[i].socket ==={
        console.log(onlineplayers[i].code + " just disconnected")
        onlineplayers.splice(i, 1)
    io.emit('players', onlineplayers)

  socket.on('lobby_join', function(player) {
    if(player.available === false) return
    var exists = false
    for(var i = 0; i < onlineplayers.length; i++ ){
      if(onlineplayers[i].code === player.code){
        exists = true
    if(exists === false){
        code: player.code,
    io.emit('players', onlineplayers)

  socket.on('lobby_leave', function(player) {
    var exists = false
    for(var i = 0; i < onlineplayers.length; i++ ){
      if(onlineplayers[i].code === player.code){
        onlineplayers.splice(i, 1)
    io.emit('players', onlineplayers)

How to get the path of running java program

Try this code:

final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

replace 'MyClass' with your class containing the main method.

Alternatively you can also use


Above mentioned System property provides

Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

Visual c++ can't open include file 'iostream'

Some things that you should check:

  • Check the include folder in your version of VS (in "C:\Program Files\Microsoft Visual Studio xx.x\VC\include" check for the file which you are including, iostream, make sure it's there).

  • Check your projects Include Directories in <Project Name> > Properties > Configuration Properties > VC++ Directories > Include Directories - (it should look like this: $(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include;)

  • Make sure that you selected the correct project for this code (File > New > Project > Visual C++ > Win32 Console Application)

  • Make sure that you don't have <iostream.h> anywhere in your code files, VS doesn't support that (in the same project, check your other code files, .cpp and .h files for <iostream.h> and remove it).

  • Make sure that you don't have more than one main() function in your project code files (in the same project, check your other code files, .cpp and .h files for the main() function and remove it or replace it with another name).

Some things you could try building with:

  • Exclude using namespace std; from your main() function and put it after the include directive.
  • Use std::cout without using namespace std;.

Keep overflow div scrolled to bottom unless user scrolls up

//Make sure message list is scrolled to the bottom
var container = $('#MessageWindowContent')[0];
var containerHeight = container.clientHeight;
var contentHeight = container.scrollHeight;

container.scrollTop = contentHeight - containerHeight;

Here is my version based on dotnetCarpenter's answer. My approach is a pure jQuery and I named the variables to make things a bit clearer.. What is happening is if the content height is greater then the container we scroll the extra distance down to achieve the desired result.

Works in IE and chrome..

What does the 'u' symbol mean in front of string values?

This is a feature, not a bug.

See, specifically the 'unicode type' section.

Multiline TextBox multiple newline

textBox1.Text = "Line1" + Environment.NewLine + "Line2";

Also the markup needs to include TextMode="MultiLine" (otherwise it shows text as one line)

<asp:TextBox ID="multitxt" runat="server" TextMode="MultiLine" ></asp:TextBox>

How to draw border around a UILabel?

Swift 3/4 with @IBDesignable

While almost all the above solutions work fine but I would suggest an @IBDesignable custom class for this.

class CustomLabel: UILabel {

    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code

    @IBInspectable var borderColor: UIColor = UIColor.white {
        didSet {
            layer.borderColor = borderColor.cgColor

    @IBInspectable var borderWidth: CGFloat = 2.0 {
        didSet {
            layer.borderWidth = borderWidth

    @IBInspectable var cornerRadius: CGFloat = 0.0 {
        didSet {
            layer.cornerRadius = cornerRadius

How do I print the type or class of a variable in Swift?

Another important aspect that influences the class name returned from String(describing: type(of: self)) is Access Control.

Consider the following example, based on Swift 3.1.1, Xcode 8.3.3 (July 2017)

func printClassNames() {

    let className1 = SystemCall<String>().getClassName()
    print(className1) // prints: "SystemCall<String>"

    let className2 = DemoSystemCall().getClassName()
    print(className2) // prints: "DemoSystemCall"

    // private class example
    let className3 = PrivateDemoSystemCall().getClassName()
    print(className3) // prints: "(PrivateDemoSystemCall in _0FC31E1D2F85930208C245DE32035247)" 

    // fileprivate class example
    let className4 = FileprivateDemoSystemCall().getClassName()
    print(className4) // prints: "(FileprivateDemoSystemCall in _0FC31E1D2F85930208C245DE32035247)" 

class SystemCall<T> {
    func getClassName() -> String {
        return String(describing: type(of: self))

class DemoSystemCall: SystemCall<String> { }

private class PrivateDemoSystemCall: SystemCall<String> { }

fileprivate class FileprivateDemoSystemCall: SystemCall<String> { }

As you can see, all classes in this example have different levels of access control which influence their String representation. In case the classes have private or fileprivate access control levels, Swift seems to append some kind of identifier related to the "nesting" class of the class in question.

The result for both PrivateDemoSystemCall and FileprivateDemoSystemCall is that the same identifier is appended because they both are nested in the same parent class.

I have not yet found a way to get rid of that, other than some hacky replace or regex function.

Just my 2 cents.

How can I expand and collapse a <div> using javascript?

Many problems here

I've set up a fiddle that works for you: