Programs & Examples On #Custom cursor

0

Change the mouse pointer using JavaScript

Look at this page: http://www.webcodingtech.com/javascript/change-cursor.php. Looks like you can access cursor off of style. This page shows it being done with the entire page, but I'm sure a child element would work just as well.

document.body.style.cursor = 'wait';

JAX-WS - Adding SOAP Headers

In jaxws-rt-2.2.10-ources.jar!\com\sun\xml\ws\transport\http\client\HttpTransportPipe.java:

public Packet process(Packet request) {
        Map<String, List<String>> userHeaders = (Map<String, List<String>>) request.invocationProperties.get(MessageContext.HTTP_REQUEST_HEADERS);
        if (userHeaders != null) {
            reqHeaders.putAll(userHeaders);

So, Map<String, List<String>> from requestContext with key MessageContext.HTTP_REQUEST_HEADERS will be copied to SOAP headers. Sample of Application Authentication with JAX-WS via headers

BindingProvider.USERNAME_PROPERTY and BindingProvider.PASSWORD_PROPERTY keys are processed special way in HttpTransportPipe.addBasicAuth(), adding standard basic authorization Authorization header.

See also Message Context in JAX-WS

Why use @PostConstruct?

Consider the following scenario:

public class Car {
  @Inject
  private Engine engine;  

  public Car() {
    engine.initialize();  
  }
  ...
}

Since Car has to be instantiated prior to field injection, the injection point engine is still null during the execution of the constructor, resulting in a NullPointerException.

This problem can be solved either by JSR-330 Dependency Injection for Java constructor injection or JSR 250 Common Annotations for the Java @PostConstruct method annotation.

@PostConstruct

JSR-250 defines a common set of annotations which has been included in Java SE 6.

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection.

JSR-250 Chap. 2.5 javax.annotation.PostConstruct

The @PostConstruct annotation allows for the definition of methods to be executed after the instance has been instantiated and all injects have been performed.

public class Car {
  @Inject
  private Engine engine;  

  @PostConstruct
  public void postConstruct() {
    engine.initialize();  
  }
  ...
} 

Instead of performing the initialization in the constructor, the code is moved to a method annotated with @PostConstruct.

The processing of post-construct methods is a simple matter of finding all methods annotated with @PostConstruct and invoking them in turn.

private  void processPostConstruct(Class type, T targetInstance) {
  Method[] declaredMethods = type.getDeclaredMethods();

  Arrays.stream(declaredMethods)
      .filter(method -> method.getAnnotation(PostConstruct.class) != null) 
      .forEach(postConstructMethod -> {
         try {
           postConstructMethod.setAccessible(true);
           postConstructMethod.invoke(targetInstance, new Object[]{});
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {      
          throw new RuntimeException(ex);
        }
      });
}

The processing of post-construct methods has to be performed after instantiation and injection have been completed.

Yii2 data provider default sorting

$dataProvider = new ActiveDataProvider([ 
    'query' => $query, 
    'sort'=> ['defaultOrder' => ['iUserId'=>SORT_ASC]] 
]);

Apache Prefork vs Worker MPM

Prefork and worker are two type of MPM apache provides. Both have their merits and demerits.

By default mpm is prefork which is thread safe.

Prefork MPM uses multiple child processes with one thread each and each process handles one connection at a time.

Worker MPM uses multiple child processes with many threads each. Each thread handles one connection at a time.

For more details you can visit https://httpd.apache.org/docs/2.4/mpm.html and https://httpd.apache.org/docs/2.4/mod/prefork.html

How to send parameters with jquery $.get()

I got this working : -

$.get('api.php', 'client=mikescafe', function(data) {
...
});

It sends via get the string ?client=mikescafe then collect this variable in api.php, and use it in your mysql statement.

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

Short and Crisp single line command, that will take care of it.

kill -9 $(lsof -i tcp:3000 -t)

javascript node.js next()

It is naming convention used when passing callbacks in situations that require serial execution of actions, e.g. scan directory -> read file data -> do something with data. This is in preference to deeply nesting the callbacks. The first three sections of the following article on Tim Caswell's HowToNode blog give a good overview of this:

http://howtonode.org/control-flow

Also see the Sequential Actions section of the second part of that posting:

http://howtonode.org/control-flow-part-ii

Set min-width in HTML table's <td>

<table style="min-width:50px; max-width:150px;">
    <tr>
        <td style="min-width:50px">one</td>
        <td style="min-width:100px">two</td>
    </tr>
</table>

This works for me using an email script.

How to store file name in database, with other info while uploading image to server using PHP?

Here is the answer for those of you looking like I did all over the web trying to find out how to do this task. Uploading a photo to a server with the file name stored in a mysql database and other form data you want in your Database. Please let me know if it helped.

Firstly the form you need:

    <form method="post" action="addMember.php" enctype="multipart/form-data">
    <p>
              Please Enter the Band Members Name.
            </p>
            <p>
              Band Member or Affiliates Name:
            </p>
            <input type="text" name="nameMember"/>
            <p>
              Please Enter the Band Members Position. Example:Drums.
            </p>
            <p>
              Band Position:
            </p>
            <input type="text" name="bandMember"/>
            <p>
              Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
            </p>
            <p>
              Photo:
            </p>
            <input type="hidden" name="size" value="350000">
            <input type="file" name="photo"> 
            <p>
              Please Enter any other information about the band member here.
            </p>
            <p>
              Other Member Information:
            </p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
            <p>
              Please Enter any other Bands the Member has been in.
            </p>
            <p>
              Other Bands:
            </p>
            <input type="text" name="otherBands" size=30 />
            <br/>
            <br/>
            <input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>
          </form>

Then this code processes you data from the form:

   <?php

// This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);

// This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];


// Connects to your Database
mysqli_connect("yourhost", "username", "password") or die(mysqli_error()) ;
mysqli_select_db("dbName") or die(mysqli_error()) ;

// Writes the information to the database
mysqli_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;

// Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

// Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

// Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?> 

Code edited from www.about.com

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

Try this:

location / {
    root /path/to/root;
    expires 30d;
    access_log off;
}

location ~* ^.*\.php$ {
    if (!-f $request_filename) {
        return 404;
    }
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

Hopefully it works. Regular expressions have higher priority than plain strings, so all requests ending in .php should be forwared to Apache if only a corresponding .php file exists. Rest will be handled as static files. The actual algorithm of evaluating location is here.

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

Try this only if you are ok with uninstalling python.

I uninstalled python using

brew uninstall python

then later installed using

brew install python

then it worked!

Load a bitmap image into Windows Forms using open file dialog

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog open = new OpenFileDialog();
    if (open.ShowDialog() == DialogResult.OK)
        pictureBox1.Image = Bitmap.FromFile(open.FileName);
}

Python conversion between coordinates

There is a better way to write polar(), here it is:

def polar(x,y):
  `returns r, theta(degrees)`
  return math.hypot(x,y),math.degrees(math.atan2(y,x))

Detect encoding and make everything UTF-8

Ÿ is Mojibake for ß. In your database, you may have hex

DF if the column is "latin1",
C39F if the column is utf8 -- OR -- it is latin1, but "double-encoded"
C383C5B8 if double-encoded into a utf8 column

You should not use any encoding/decoding functions in PHP; instead, you should set up the database and the connection to it correctly.

If MySQL is involved, see: Trouble with utf8 characters; what I see is not what I stored

How to convert seconds to HH:mm:ss in moment.js

From this post I would try this to avoid leap issues

moment("2015-01-01").startOf('day')
    .seconds(s)
    .format('H:mm:ss');

I did not run jsPerf, but I would think this is faster than creating new date objects a million times

function pad(num) {
    return ("0"+num).slice(-2);
}
function hhmmss(secs) {
  var minutes = Math.floor(secs / 60);
  secs = secs%60;
  var hours = Math.floor(minutes/60)
  minutes = minutes%60;
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}

_x000D_
_x000D_
function pad(num) {_x000D_
    return ("0"+num).slice(-2);_x000D_
}_x000D_
function hhmmss(secs) {_x000D_
  var minutes = Math.floor(secs / 60);_x000D_
  secs = secs%60;_x000D_
  var hours = Math.floor(minutes/60)_x000D_
  minutes = minutes%60;_x000D_
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;_x000D_
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers_x000D_
}_x000D_
_x000D_
for (var i=60;i<=60*60*5;i++) {_x000D_
 document.write(hhmmss(i)+'<br/>');_x000D_
}_x000D_
_x000D_
_x000D_
/* _x000D_
function show(s) {_x000D_
  var d = new Date();_x000D_
  var d1 = new Date(d.getTime()+s*1000);_x000D_
  var  hms = hhmmss(s);_x000D_
  return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);_x000D_
}    _x000D_
*/
_x000D_
_x000D_
_x000D_

"Sources directory is already netbeans project" error when opening a project from existing sources

If it helps anyone else, I had the same problem and the solution was to reinstall NetBeans.

I had tried all sorts of fixes: Deleting the NetBeansProjects folders, checking/unchecking "Put Netbeans metadata in a separate directory", killing/restarting NetBeans, restarting the system, etc. Nothing cleared the message...except the reinstall.

Append a tuple to a list - what's the difference between two ways?

It has nothing to do with append. tuple(3, 4) all by itself raises that error.

The reason is that, as the error message says, tuple expects an iterable argument. You can make a tuple of the contents of a single object by passing that single object to tuple. You can't make a tuple of two things by passing them as separate arguments.

Just do (3, 4) to make a tuple, as in your first example. There's no reason not to use that simple syntax for writing a tuple.

JavaScript CSS how to add and remove multiple CSS classes to an element

the Element.className += " MyClass"; is not recommended approach because it will always add these classes whether they were exit or not.

in my case, I was uploading an image file and adding classes to it, now with this each time you upload an image it will add these class whether they exist or not,

the recommended way is Element.classList.add("class1" , "class2" , "class3"); this way will not add extra classes if they already there.

Has anyone gotten HTML emails working with Twitter Bootstrap?

I spent some time recently looking into building html email templates, the best solution I found was to use this http://htmlemailboilerplate.com/. I have since built 3 quite complex templates and they have worked well in the various email clients.

Display string multiple times

Python 2.x:

print '-' * 3

Python 3.x:

print('-' * 3)

Serializing with Jackson (JSON) - getting "No serializer found"?

Add a

getter

and a

setter

and the problem is solved.

StringUtils.isBlank() vs String.isEmpty()

StringUtils isEmpty = String isEmpty checks + checks for null.

StringUtils isBlank = StringUtils isEmpty checks + checks if the text contains only whitespace character(s).

Useful links for further investigation:

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

The approved answer to this question is not valid.

You need to set headers on your server-side code

app.use((req,res,next)=>{
    res.setHeader('Acces-Control-Allow-Origin','*');
    res.setHeader('Acces-Control-Allow-Methods','GET,POST,PUT,PATCH,DELETE');
    res.setHeader('Acces-Contorl-Allow-Methods','Content-Type','Authorization');
    next(); 
})

Convert an image to grayscale in HTML/CSS

Support for CSS filters has landed in Webkit. So we now have a cross-browser solution.

_x000D_
_x000D_
img {_x000D_
  filter: gray; /* IE6-9 */_x000D_
  -webkit-filter: grayscale(1); /* Google Chrome, Safari 6+ & Opera 15+ */_x000D_
  filter: grayscale(1); /* Microsoft Edge and Firefox 35+ */_x000D_
}_x000D_
_x000D_
/* Disable grayscale on hover */_x000D_
img:hover {_x000D_
  -webkit-filter: grayscale(0);_x000D_
  filter: none;_x000D_
}
_x000D_
<img src="http://lorempixel.com/400/200/">
_x000D_
_x000D_
_x000D_


What about Internet Explorer 10?

You can use a polyfill like gray.

Get all object attributes in Python?

What you probably want is dir().

The catch is that classes are able to override the special __dir__ method, which causes dir() to return whatever the class wants (though they are encouraged to return an accurate list, this is not enforced). Furthermore, some objects may implement dynamic attributes by overriding __getattr__, may be RPC proxy objects, or may be instances of C-extension classes. If your object is one these examples, they may not have a __dict__ or be able to provide a comprehensive list of attributes via __dir__: many of these objects may have so many dynamic attrs it doesn't won't actually know what it has until you try to access it.

In the short run, if dir() isn't sufficient, you could write a function which traverses __dict__ for an object, then __dict__ for all the classes in obj.__class__.__mro__; though this will only work for normal python objects. In the long run, you may have to use duck typing + assumptions - if it looks like a duck, cross your fingers, and hope it has .feathers.

Android overlay a view ontop of everything?

You can use bringToFront:

    View view=findViewById(R.id.btnStartGame);
    view.bringToFront();

Returning a value even if no result

k-a-f's answer works for selecting one column, if selecting multiple column, we can.

DECLARE a BIGINT DEFAULT 1;
DECLARE b BIGINT DEFAULT "name";

SELECT id, name from table into a,b;

Then we just need to check a,b for values.

Get value (String) of ArrayList<ArrayList<String>>(); in Java

The right way to iterate on a list inside list is:

//iterate on the general list
for(int i = 0 ; i < collection.size() ; i++) {
    ArrayList<String> currentList = collection.get(i);
    //now iterate on the current list
    for (int j = 0; j < currentList.size(); j++) {
        String s = currentList.get(1);
    }
}

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

Get img src with PHP

There could be two easy solutions:

  1. HTML it self is an xml so you can use any XML parsing method if u load the tag as XML and get its attribute tottally dynamically even dom data attribute (like data-time or anything).....
  2. Use any html parser for php like http://mbe.ro/2009/06/21/php-html-to-array-working-one/ or php parse html to array Google this

Download and open PDF file using Ajax

_x000D_
_x000D_
var xhr;_x000D_
var beforeSend = function(){_x000D_
    $('#pleasewaitDL').modal('show');_x000D_
}_x000D_
$(function () {_x000D_
    $('#print_brochure_link').click(function(){_x000D_
        beforeSend();_x000D_
        xhr = new XMLHttpRequest();_x000D_
        xhr.open("GET",$('#preparedPrintModalForm').attr('action'), true); _x000D_
        xhr.responseType = "blob";_x000D_
        xhr.onload = function (e) {_x000D_
            if (this.status === 200) {_x000D_
                var file = window.URL.createObjectURL(this.response);_x000D_
                var a = document.createElement("a");_x000D_
                a.href = file;_x000D_
                a.download = this.response.name || "Property Brochure";_x000D_
                console.log(file);_x000D_
                document.body.appendChild(a);_x000D_
                a.click();_x000D_
                _x000D_
                window.onfocus = function () {                     _x000D_
                  document.body.removeChild(a)_x000D_
                }_x000D_
                $('#pleasewaitDL').modal('hide');_x000D_
            };_x000D_
        };_x000D_
        xhr.send($('#preparedPrintModalForm').serialize());_x000D_
    });_x000D_
    $('#pleasewaitDLCancel').click(function() {_x000D_
        xhr.abort();_x000D_
    });_x000D_
});
_x000D_
_x000D_
_x000D_

Get current url in Angular

You can make use of location service available in @angular/common and via this below code you can get the location or current URL

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-top-nav',
  templateUrl: './top-nav.component.html',
  styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {

  route: string;

  constructor(location: Location, router: Router) {
    router.events.subscribe((val) => {
      if(location.path() != ''){
        this.route = location.path();
      } else {
        this.route = 'Home'
      }
    });
  }

  ngOnInit() {
  }

}

here is the reference link from where I have copied thing to get location for my project. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

Easiest way is probably to convert from a VARCHAR to a DATE; then format it back to a VARCHAR again in the format you want;

SELECT TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') FROM EmpTable;

An SQLfiddle to test with.

Logging in Scala

I find very convenient using some kind of java logger, sl4j for example, with simple scala wrapper, which brings me such syntax

val #! = new Logger(..) // somewhere deep in dsl.logging.

object User with dsl.logging {

  #! ! "info message"
  #! dbg "debug message"
  #! trace "var a=true"

}

In my opinion very usefull mixin of java proven logging frameworks and scala's fancy syntax.

How to Create simple drag and Drop in angularjs

adapt-strap has very light weight module for this. here is the fiddle. Here are some attributes that are supported. There are more.

ad-drag="true"
ad-drag-data="car"
ad-drag-begin="onDragStart($data, $dragElement, $event);"
ad-drag-end="onDataEnd($data, $dragElement, $event);"

ReferenceError: Invalid left-hand side in assignment

Common reasons for the error:

  • use of assignment (=) instead of equality (==/===)
  • assigning to result of function foo() = 42 instead of passing arguments (foo(42))
  • simply missing member names (i.e. assuming some default selection) : getFoo() = 42 instead of getFoo().theAnswer = 42 or array indexing getArray() = 42 instead of getArray()[0]= 42

In this particular case you want to use == (or better === - What exactly is Type Coercion in Javascript?) to check for equality (like if(one === "rock" && two === "rock"), but it the actual reason you are getting the error is trickier.

The reason for the error is Operator precedence. In particular we are looking for && (precedence 6) and = (precedence 3).

Let's put braces in the expression according to priority - && is higher than = so it is executed first similar how one would do 3+4*5+6 as 3+(4*5)+6:

 if(one= ("rock" && two) = "rock"){...

Now we have expression similar to multiple assignments like a = b = 42 which due to right-to-left associativity executed as a = (b = 42). So adding more braces:

 if(one= (  ("rock" && two) = "rock" )  ){...

Finally we arrived to actual problem: ("rock" && two) can't be evaluated to l-value that can be assigned to (in this particular case it will be value of two as truthy).

Note that if you'd use braces to match perceived priority surrounding each "equality" with braces you get no errors. Obviously that also producing different result than you'd expect - changes value of both variables and than do && on two strings "rock" && "rock" resulting in "rock" (which in turn is truthy) all the time due to behavior of logial &&:

if((one = "rock") && (two = "rock"))
{
   // always executed, both one and two are set to "rock"
   ...
}

For even more details on the error and other cases when it can happen - see specification:

Assignment

LeftHandSideExpression = AssignmentExpression
...
Throw a SyntaxError exception if the following conditions are all true:
...
IsStrictReference(lref) is true

Left-Hand-Side Expressions

and The Reference Specification Type explaining IsStrictReference:

... function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference...

Validate email with a regex in jQuery

You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:

var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i

if(!pattern.test(userinput))
{
  alert('not a valid e-mail address');
}?

Git - Won't add files?

If the file is excluded by .gitignore and you want to add it anyway, you can force it with:

git add -f path/to/file.ext

Visual studio equivalent of java System.out

In System.Diagnostics,

Debug.Write()
Debug.WriteLine()

etc. will print to the Output window in VS.

How to get the id of the element clicked using jQuery

update as you loading contents dynamically so you use.

$(document).on('click', 'span', function () {
    alert(this.id);
});

old code

$('span').click(function(){
    alert(this.id);
});

or you can use .on

$('span').on('click', function () {
    alert(this.id);
});

this refers to current span element clicked

this.id will give the id of the current span clicked

How do I check form validity with angularjs?

Example

<div ng-controller="ExampleController">
  <form name="myform">
   Name: <input type="text" ng-model="user.name" /><br>
   Email: <input type="email" ng-model="user.email" /><br>
  </form>
</div>

<script>
  angular.module('formExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

     //if form is not valid then return the form.
     if(!$scope.myform.$valid) {
       return;
     }
  }]);
</script>

java.net.SocketException: Software caused connection abort: recv failed

Look if you have another service or program running on the http port. It happened to me when I tried to use the port and it was taken by another program.

Microsoft Visual C++ Compiler for Python 3.4

For the different python versions:

Visual C++ |CPython
--------------------
14.0       |3.5
10.0       |3.3, 3.4
9.0        |2.6, 2.7, 3.0, 3.1, 3.2

Source: Windows Compilers for py

Also refer: this answer

difference between iframe, embed and object elements

iframe have "sandbox" attribute that may block pop up etc

How to get parameters from a URL string?

you can use below code to get email address after ? in the URL

_x000D_
_x000D_
<?php_x000D_
if (isset($_GET['email'])) {_x000D_
    echo $_GET['email'];_x000D_
}
_x000D_
_x000D_
_x000D_

Linker Error C++ "undefined reference "

This error tells you everything:

undefined reference toHash::insert(int, char)

You're not linking with the implementations of functions defined in Hash.h. Don't you have a Hash.cpp to also compile and link?

How to find controls in a repeater header or footer

Find control into Repeater (Header, Item, Footer)

public static class FindControlInRepeater
{
    public static Control FindControl(this Repeater repeater, string controlName)
    {
        for (int i = 0; i < repeater.Controls.Count; i++)
            if (repeater.Controls[i].Controls[0].FindControl(controlName) != null)
                return repeater.Controls[i].Controls[0].FindControl(controlName);
        return null;
    }
}

Conditional Count on a field

Using COUNT instead of SUM removes the requirement for an ELSE statement:

SELECT jobId, jobName,
    COUNT(CASE WHEN Priority=1 THEN 1 END) AS Priority1,
    COUNT(CASE WHEN Priority=2 THEN 1 END) AS Priority2,
    COUNT(CASE WHEN Priority=3 THEN 1 END) AS Priority3,
    COUNT(CASE WHEN Priority=4 THEN 1 END) AS Priority4,
    COUNT(CASE WHEN Priority=5 THEN 1 END) AS Priority5
FROM TableName
GROUP BY jobId, jobName

Adding options to select with javascript

You could achieve this with a simple for loop:

var min = 12,
    max = 100,
    select = document.getElementById('selectElementId');

for (var i = min; i<=max; i++){
    var opt = document.createElement('option');
    opt.value = i;
    opt.innerHTML = i;
    select.appendChild(opt);
}

JS Fiddle demo.

JS Perf comparison of both mine and Sime Vidas' answer, run because I thought his looked a little more understandable/intuitive than mine and I wondered how that would translate into implementation. According to Chromium 14/Ubuntu 11.04 mine is somewhat faster, other browsers/platforms are likely to have differing results though.


Edited in response to comment from OP:

[How] do [I] apply this to more than one element?

function populateSelect(target, min, max){
    if (!target){
        return false;
    }
    else {
        var min = min || 0,
            max = max || min + 100;

        select = document.getElementById(target);

        for (var i = min; i<=max; i++){
            var opt = document.createElement('option');
            opt.value = i;
            opt.innerHTML = i;
            select.appendChild(opt);
        }
    }
}
// calling the function with all three values:
populateSelect('selectElementId',12,100);

// calling the function with only the 'id' ('min' and 'max' are set to defaults):
populateSelect('anotherSelect');

// calling the function with the 'id' and the 'min' (the 'max' is set to default):
populateSelect('moreSelects', 50);

JS Fiddle demo.

And, finally (after quite a delay...), an approach extending the prototype of the HTMLSelectElement in order to chain the populate() function, as a method, to the DOM node:

HTMLSelectElement.prototype.populate = function (opts) {
    var settings = {};

    settings.min = 0;
    settings.max = settings.min + 100;

    for (var userOpt in opts) {
        if (opts.hasOwnProperty(userOpt)) {
            settings[userOpt] = opts[userOpt];
        }
    }

    for (var i = settings.min; i <= settings.max; i++) {
        this.appendChild(new Option(i, i));
    }
};

document.getElementById('selectElementId').populate({
    'min': 12,
    'max': 40
});

JS Fiddle demo.

References:

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

Reading and displaying data from a .txt file

public class PassdataintoFile {

    public static void main(String[] args) throws IOException  {
        try {
            PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
            PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
             pw1.println("Hi chinni");
             pw1.print("your succesfully entered text into file");
             pw1.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
           String line;
           while((line = br.readLine())!= null)
           {
               System.out.println(line);
           }
           br.close();
    }

}

How to find out mySQL server ip address from phpmyadmin

MySQL doesn't care what IP its on. Closest you could get would be hostname:

select * from GLOBAL_variables where variable_name like 'hostname';

What's the HTML to have a horizontal space between two objects?

PHP does not do styling. You need to use html or css. Take a look at http://www.w3schools.com/tags/tag_hr.asp

In HTML 4.01, the


tag represents a horizontal rule.

In HTML 4.01, the <hr> tag represents a horizontal rule.

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

We had the same problem on a CentOS7 machine. Disabling the VERIFYHOST VERIFYPEER did not solve the problem, we did not have the cURL error anymore but the response still was invalid. Doing a wget to the same link as the cURL was doing also resulted in a certificate error.

-> Our solution also was to reboot the VPS, this solved it and we were able to complete the request again.

For us this seemed to be a memory corruption problem. Rebooting the VPS reloaded the libary in the memory again and now it works. So if the above solution from @clover does not work try to reboot your machine.

Difference between Statement and PreparedStatement

Statement will be used for executing static SQL statements and it can't accept input parameters.

PreparedStatement will be used for executing SQL statements many times dynamically. It will accept input parameters.

moment.js - UTC gives wrong date

Both Date and moment will parse the input string in the local time zone of the browser by default. However Date is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD, using hyphens, or if it is YYYY-MM-DD HH:mm:ss, it will interpret it as local time. Unlike Date, moment will always be consistent about how it parses.

The correct way to parse an input moment as UTC in the format you provided would be like this:

moment.utc('07-18-2013', 'MM-DD-YYYY')

Refer to this documentation.

If you want to then format it differently for output, you would do this:

moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')

You do not need to call toString explicitly.

Note that it is very important to provide the input format. Without it, a date like 01-04-2013 might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.

What does Ruby have that Python doesn't, and vice versa?

"Variables that start with a capital letter becomes constants and can't be modified"

Wrong. They can.

You only get a warning if you do.

Finding rows containing a value (or values) in any column

How about

apply(df, 1, function(r) any(r %in% c("M017", "M018")))

The ith element will be TRUE if the ith row contains one of the values, and FALSE otherwise. Or, if you want just the row numbers, enclose the above statement in which(...).

Show values from a MySQL database table inside a HTML table on a webpage

OOP Style : At first connection with database.

<?php
class database
{

 public $host = "localhost";
 public $user = "root";
 public $pass = "";
 public $db   = "db";
 public $link;

 public function __construct()
 {
    $this->connect();
 }

 private function connect()
 {
   $this->link = new mysqli($this->host, $this->user, $this->pass, $this->db);
    return $this->link;
 }

 public function select($query)
 {
    $result = $this->link->query($query) or die($this->link->error.__LINE__);

    if($result->num_rows>0)
    {
      return $result;
    } 
    else 
    {
      return false;
    }
}
?>

Then :

    <?php
        $db = new database();

        $query = "select * from data";
        $result = $db->select($query);

        echo "<table>";
         echo "<tr>";
            echo "<th>Name </th>";
            echo "<th>Roll </th>";
         echo "</tr>";
         while($row = mysqli_fetch_array($result)) 
         {
            echo "<tr>";
            echo "<td> $row[name]</td>";
            echo "<td> $row[roll]</td>";
            echo "</tr>";
         }
       echo "</table>";
 ?>

Changing the default title of confirm() in JavaScript?

YES YOU CAN do it!! It's a little tricky way ; ) (it almost works on ios)

var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", 'data:text/plain,');
document.documentElement.appendChild(iframe);
if(window.frames[0].window.confirm("Are you sure?")){
    // what to do if answer "YES"
}else{
    // what to do if answer "NO"
}

Enjoy it!

How to set up devices for VS Code for a Flutter emulator

You can connect an Android Phone via USB cable and then it will show the device in the bottom bar.(Please note ADB must be installed. Click here for more)

Or you can completely install Android Studio and setup emulator from there and run the emulator. Then VS Code will recogzine the emulator and show at the bottom bar.

Determine the process pid listening on a certain port

Syntax:

kill -9 $(lsof -t -i:portnumber)

Example: To kill the process running at port 4200, run following command

kill -9 $(lsof -t -i:4200)

Tested in Ubuntu.

How do I convert a column of text URLs into active hyperlinks in Excel?

There is a very simple way to do this. Create one hyperlink, and then use the Format Painter to copy down the formatting. It will create a hyperlink for every item.

Determine installed PowerShell version

You can also call the "host" command from the PowerShell commandline. It should give you the value of the $host variable.

Validating an XML against referenced XSD in C#

You need to create an XmlReaderSettings instance and pass that to your XmlReader when you create it. Then you can subscribe to the ValidationEventHandler in the settings to receive validation errors. Your code will end up looking like this:

using System.Xml;
using System.Xml.Schema;
using System.IO;

public class ValidXSD
{
    public static void Main()
    {

        // Set the validation settings.
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
        settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

        // Create the XmlReader object.
        XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);

        // Parse the file. 
        while (reader.Read()) ;

    }
    // Display any warnings or errors.
    private static void ValidationCallBack(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.WriteLine("\tWarning: Matching schema not found.  No validation occurred." + args.Message);
        else
            Console.WriteLine("\tValidation error: " + args.Message);

    }
}

Upload files with HTTPWebrequest (multipart/form-data)

For me, the following works (mostly inspirated from all of the following answers), I started from Elad's answer and modify/simplify things to match my need (remove not file form inputs, only one file, ...).

Hope it can helps somebody :)

(PS: I know that exception handling is not implemented and it assumes that it was written inside a class, so I may need some integration effort...)

private void uploadFile()
    {
        Random rand = new Random();
        string boundary = "----boundary" + rand.Next().ToString();
        Stream data_stream;
        byte[] header = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"file_path\"; filename=\"" + System.IO.Path.GetFileName(this.file) + "\"\r\nContent-Type: application/octet-stream\r\n\r\n");
        byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

        // Do the request
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(MBF_URL);
        request.UserAgent = "My Toolbox";
        request.Method = "POST";
        request.KeepAlive = true;
        request.ContentType = "multipart/form-data; boundary=" + boundary;
        data_stream = request.GetRequestStream();
        data_stream.Write(header, 0, header.Length);
        byte[] file_bytes = System.IO.File.ReadAllBytes(this.file);
        data_stream.Write(file_bytes, 0, file_bytes.Length);
        data_stream.Write(trailer, 0, trailer.Length);
        data_stream.Close();

        // Read the response
        WebResponse response = request.GetResponse();
        data_stream = response.GetResponseStream();
        StreamReader reader = new StreamReader(data_stream);
        this.url = reader.ReadToEnd();

        if (this.url == "") { this.url = "No response :("; }

        reader.Close();
        data_stream.Close();
        response.Close();
    }

Maximum filename length in NTFS (Windows XP and Windows Vista)?

This part of the official documentation says clearly that it’s 255 Unicode characters for NTFS, exFAT and FAT32, and 127 Unicode or 254 ASCII characters for UDF.

Apart from that, the maximum path name length is always 32,760 Unicode characters, with each path component no more than 255 characters.

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

Your compile SDK version must match the support library major version. This is the solution to your problem. You can check it easily in your Gradle Scripts in build.gradle file. Fx: if your compileSdkVersion is 23 your compile library must start at 23.

  compileSdkVersion 23
    buildToolsVersion "23.0.0"
    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 340
        versionName "3.4.0"
    }
dependencies {
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:recyclerview-v7:23.0.1'
}

And always check that your Android Studoi has the supported API Level. You can check it in your Android SDK, like this: enter image description here

Python | change text color in shell

Use Curses or ANSI escape sequences. Before you start spouting escape sequences, you should check that stdout is a tty. You can do this with sys.stdout.isatty(). Here's a function pulled from a project of mine that prints output in red or green, depending on the status, using ANSI escape sequences:

def hilite(string, status, bold):
    attr = []
    if status:
        # green
        attr.append('32')
    else:
        # red
        attr.append('31')
    if bold:
        attr.append('1')
    return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)

How to write multiple conditions of if-statement in Robot Framework

You should use small caps "or" and "and" instead of OR and AND.

And beware also the spaces/tabs between keywords and arguments (you need at least two spaces).

Here is a code sample with your three keywords working fine:

Here is the file ts.txt:

  *** test cases ***
  mytest
    ${color} =  set variable  Red
    Run Keyword If  '${color}' == 'Red'  log to console  \nexecuted with single condition
    Run Keyword If  '${color}' == 'Red' or '${color}' == 'Blue' or '${color}' == 'Pink'  log to console  \nexecuted with multiple or

    ${color} =  set variable  Blue
    ${Size} =  set variable  Small
    ${Simple} =  set variable  Simple
    ${Design} =  set variable  Simple
    Run Keyword If  '${color}' == 'Blue' and '${Size}' == 'Small' and '${Design}' != '${Simple}'  log to console  \nexecuted with multiple and

    ${Size} =  set variable  XL
    ${Design} =  set variable  Complicated
    Run Keyword Unless  '${color}' == 'Black' or '${Size}' == 'Small' or '${Design}' == 'Simple'  log to console  \nexecuted with unless and multiple or

and here is what I get when I execute it:

$ pybot ts.txt
==============================================================================
Ts
==============================================================================
mytest                                                                .
executed with single condition
executed with multiple or
executed with unless and multiple or
mytest                                                                | PASS |
------------------------------------------------------------------------------

Having services in React application

The first answer doesn't reflect the current Container vs Presenter paradigm.

If you need to do something, like validate a password, you'd likely have a function that does it. You'd be passing that function to your reusable view as a prop.

Containers

So, the correct way to do it is to write a ValidatorContainer, which will have that function as a property, and wrap the form in it, passing the right props in to the child. When it comes to your view, your validator container wraps your view and the view consumes the containers logic.

Validation could be all done in the container's properties, but it you're using a 3rd party validator, or any simple validation service, you can use the service as a property of the container component and use it in the container's methods. I've done this for restful components and it works very well.

Providers

If there's a bit more configuration necessary, you can use a Provider/Consumer model. A provider is a high level component that wraps somewhere close to and underneath the top application object (the one you mount) and supplies a part of itself, or a property configured in the top layer, to the context API. I then set my container elements to consume the context.

The parent/child context relations don't have to be near each other, just the child has to be descended in some way. Redux stores and the React Router function in this way. I've used it to provide a root restful context for my rest containers (if I don't provide my own).

(note: the context API is marked experimental in the docs, but I don't think it is any more, considering what's using it).

_x000D_
_x000D_
//An example of a Provider component, takes a preconfigured restful.js_x000D_
//object and makes it available anywhere in the application_x000D_
export default class RestfulProvider extends React.Component {_x000D_
 constructor(props){_x000D_
  super(props);_x000D_
_x000D_
  if(!("restful" in props)){_x000D_
   throw Error("Restful service must be provided");_x000D_
  }_x000D_
 }_x000D_
_x000D_
 getChildContext(){_x000D_
  return {_x000D_
   api: this.props.restful_x000D_
  };_x000D_
 }_x000D_
_x000D_
 render() {_x000D_
  return this.props.children;_x000D_
 }_x000D_
}_x000D_
_x000D_
RestfulProvider.childContextTypes = {_x000D_
 api: React.PropTypes.object_x000D_
};
_x000D_
_x000D_
_x000D_

Middleware

A further way I haven't tried, but seen used, is to use middleware in conjunction with Redux. You define your service object outside the application, or at least, higher than the redux store. During store creation, you inject the service into the middleware and the middleware handles any actions that affect the service.

In this way, I could inject my restful.js object into the middleware and replace my container methods with independent actions. I'd still need a container component to provide the actions to the form view layer, but connect() and mapDispatchToProps have me covered there.

The new v4 react-router-redux uses this method to impact the state of the history, for example.

_x000D_
_x000D_
//Example middleware from react-router-redux_x000D_
//History is our service here and actions change it._x000D_
_x000D_
import { CALL_HISTORY_METHOD } from './actions'_x000D_
_x000D_
/**_x000D_
 * This middleware captures CALL_HISTORY_METHOD actions to redirect to the_x000D_
 * provided history object. This will prevent these actions from reaching your_x000D_
 * reducer or any middleware that comes after this one._x000D_
 */_x000D_
export default function routerMiddleware(history) {_x000D_
  return () => next => action => {_x000D_
    if (action.type !== CALL_HISTORY_METHOD) {_x000D_
      return next(action)_x000D_
    }_x000D_
_x000D_
    const { payload: { method, args } } = action_x000D_
    history[method](...args)_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

php convert datetime to UTC

I sometime use this method:

// It is not importnat what timezone your system is set to.
// Get the UTC offset in seconds:
$offset = date("Z");

// Then subtract if from your original timestamp:
$utc_time = date("Y-m-d H:i:s", strtotime($original_time." -".$offset." Seconds"));

Works all MOST of the time.

URL to load resources from the classpath in Java

Inspire by @Stephen https://stackoverflow.com/a/1769454/980442 and http://docstore.mik.ua/orelly/java/exp/ch09_06.htm

To use

new URL("classpath:org/my/package/resource.extension").openConnection()

just create this class into sun.net.www.protocol.classpath package and run it into Oracle JVM implementation to work like a charm.

package sun.net.www.protocol.classpath;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

public class Handler extends URLStreamHandler {

    @Override
    protected URLConnection openConnection(URL u) throws IOException {
        return Thread.currentThread().getContextClassLoader().getResource(u.getPath()).openConnection();
    }
}

In case you are using another JVM implementation set the java.protocol.handler.pkgs=sun.net.www.protocol system property.

FYI: http://docs.oracle.com/javase/7/docs/api/java/net/URL.html#URL(java.lang.String,%20java.lang.String,%20int,%20java.lang.String)

Calling startActivity() from outside of an Activity?

In my case I have used context for startActivity, after changing that with ActivityName.this . it solves. I'm using method from util class so this happens.

Hope it help some one.

How do I move a file (or folder) from one folder to another in TortoiseSVN?

If you want to move files around and keep the csproj files up to date, the easiest way is to use a Visual Studio plugin like AnkhSVN. That will automatically commit both the move action (as an delete + add with history, because that's how Subversion works) and a change in the .csproj

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

Assuming you're dealing with Windows 7 x64 and something that was previously installed with some sort of an installer, you can open regedit and search the keys under

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

(which references 32-bit programs) for part of the name of the program, or

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

(if it actually was a 64-bit program).

If you find something that matches your program in one of those, the contents of UninstallString in that key usually give you the exact command you are looking for (that you can run in a script).

If you don't find anything relevant in those registry locations, then it may have been "installed" by unzipping a file. Because you mentioned removing it by the Control Panel, I gather this likely isn't then case; if it's in the list of programs there, it should be in one of the registry keys I mentioned.

Then in a .bat script you can do

if exist "c:\program files\whatever\program.exe" (place UninstallString contents here)
if exist "c:\program files (x86)\whatever\program.exe" (place UninstallString contents here)

How do I count columns of a table

this query may help you

SELECT COUNT(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE 
TABLE_CATALOG = 'database' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'tbl_ifo'

Using Mockito to stub and execute methods for testing

You've nearly got it. The problem is that the Class Under Test (CUT) is not built for unit testing - it has not really been TDD'd.

Think of it like this…

  • I need to test a function of a class - let's call it myFunction
  • That function makes a call to a function on another class/service/database
  • That function also calls another method on the CUT

In the unit test

  • Should create a concrete CUT or @Spy on it
  • You can @Mock all of the other class/service/database (i.e. external dependencies)
  • You could stub the other function called in the CUT but it is not really how unit testing should be done

In order to avoid executing code that you are not strictly testing, you could abstract that code away into something that can be @Mocked.

In this very simple example, a function that creates an object will be difficult to test

public void doSomethingCool(String foo) {
    MyObject obj = new MyObject(foo);

    // can't do much with obj in a unit test unless it is returned
}

But a function that uses a service to get MyObject is easy to test, as we have abstracted the difficult/impossible to test code into something that makes this method testable.

public void doSomethingCool(String foo) {
    MyObject obj = MyObjectService.getMeAnObject(foo);
}

as MyObjectService can be mocked and also verified that .getMeAnObject() is called with the foo variable.

Java Minimum and Maximum values in Array

Here you haven't print the max and min values. Print the max and min values in the getMaxVal and getMin val methods or after the call. This is the output.

Enter the numbers now.
5
Max: 5
Min: 0
3
Max: 5
Min: 0
7
Max: 7
Min: 0
3
Max: 7
Min: 0
90
Max: 90
Min: 0
43
Max: 90
Min: 0
100
Max: 100
Min: 0
45
Max: 100
Min: 0
23
Max: 100
Min: 0
22
Max: 100
Min: 3
These are the numbers you have entered.
5 3 7 3 90 43 100 45 23 22

Also when you are declaring an array, it has all 0s initially.

How do I combine two dataframes?

If you want to update/replace the values of first dataframe df1 with the values of second dataframe df2. you can do it by following steps —

Step 1: Set index of the first dataframe (df1)

df1.set_index('id')

Step 2: Set index of the second dataframe (df2)

df2.set_index('id')

and finally update the dataframe using the following snippet —

df1.update(df2)

ASP.NET MVC - Extract parameter of an URL

Update

RouteData.Values["id"] + Request.Url.Query

Will match all your examples


It is not entirely clear what you are trying to achieve. MVC passes URL parameters for you through model binding.

public class CustomerController : Controller {

  public ActionResult Edit(int id) {

    int customerId = id //the id in the URL

    return View();
  }

}


public class ProductController : Controller {

  public ActionResult Edit(int id, bool allowed) { 

    int productId = id; // the id in the URL
    bool isAllowed = allowed  // the ?allowed=true in the URL

    return View();
  }

}

Adding a route mapping to your global.asax.cs file before the default will handle the /administration/ part. Or you might want to look into MVC Areas.

routes.MapRoute(
  "Admin", // Route name
  "Administration/{controller}/{action}/{id}", // URL with parameters
  new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults

If it's the raw URL data you are after then you can use one of the various URL and Request properties available in your controller action

string url = Request.RawUrl;
string query= Request.Url.Query;
string isAllowed= Request.QueryString["allowed"];

It sounds like Request.Url.PathAndQuery could be what you want.

If you want access to the raw posted data you can use

string isAllowed = Request.Params["allowed"];
string id = RouteData.Values["id"];

How can I switch to another branch in git?

I am using this to switch one branch to another anyone you can use it works for me like charm.

git switch [branchName] OR git checkout [branchName]

ex: git switch develop OR
git checkout develop

Send string to stdin

aliases can and can't process piped stdin...

Here we create 3 lines of output

$ echo -e "line 1\nline 2\nline 3"
line 1
line 2
line 3

We then pipe the output to stdin of the sed command to put them all on one line

$ echo -e "line 1\nline 2\nline 3" |  sed -e ":a;N;\$!ba ;s?\n? ?g"
line 1 line 2 line 3

If we define an alias of the same sed command

$ alias oline='sed -e ":a;N;\$!ba ;s?\n? ?g"'

We can pipe the output to the stdin of the alias and it behaves exactly the same

$ echo -e "line 1\nline 2\nline 3" |  oline
line 1 line 2 line 3

The problem arises when we try to define the alias as a function

$ alias oline='function _oline(){ sed -e ":a;N;\$!ba ;s?\n? ?g";}_oline'

Defining the alias as a funstion breaks the pipe

$ echo -e "line 1\nline 2\nline 3" |  oline
>

How to show the last queries executed on MySQL?

If mysql binlog is enabled you can check the commands ran by user by executing following command in linux console by browsing to mysql binlog directory

mysqlbinlog binlog.000001 >  /tmp/statements.sql

enabling

[mysqld]
log = /var/log/mysql/mysql.log

or general log will have an effect on performance of mysql

ImportError: No module named enum

Please use --user at end of this, it is working fine for me.

pip install enum34 --user

jQuery equivalent of JavaScript's addEventListener method

The closest thing would be the bind function:

http://api.jquery.com/bind/

$('#foo').bind('click', function() {
  alert('User clicked on "foo."');
});

TypeError: can't pickle _thread.lock objects

I had the same problem with Pool() in Python 3.6.3.

Error received: TypeError: can't pickle _thread.RLock objects

Let's say we want to add some number num_to_add to each element of some list num_list in parallel. The code is schematically like this:

class DataGenerator:
    def __init__(self, num_list, num_to_add)
        self.num_list = num_list # e.g. [4,2,5,7]
        self.num_to_add = num_to_add # e.g. 1 

        self.run()

    def run(self):
        new_num_list = Manager().list()

        pool = Pool(processes=50)
        results = [pool.apply_async(run_parallel, (num, new_num_list)) 
                      for num in num_list]
        roots = [r.get() for r in results]
        pool.close()
        pool.terminate()
        pool.join()

    def run_parallel(self, num, shared_new_num_list):
        new_num = num + self.num_to_add # uses class parameter
        shared_new_num_list.append(new_num)

The problem here is that self in function run_parallel() can't be pickled as it is a class instance. Moving this parallelized function run_parallel() out of the class helped. But it's not the best solution as this function probably needs to use class parameters like self.num_to_add and then you have to pass it as an argument.

Solution:

def run_parallel(num, shared_new_num_list, to_add): # to_add is passed as an argument
    new_num = num + to_add
    shared_new_num_list.append(new_num)

class DataGenerator:
    def __init__(self, num_list, num_to_add)
        self.num_list = num_list # e.g. [4,2,5,7]
        self.num_to_add = num_to_add # e.g. 1

        self.run()

    def run(self):
        new_num_list = Manager().list()

        pool = Pool(processes=50)
        results = [pool.apply_async(run_parallel, (num, new_num_list, self.num_to_add)) # num_to_add is passed as an argument
                      for num in num_list]
        roots = [r.get() for r in results]
        pool.close()
        pool.terminate()
        pool.join()

Other suggestions above didn't help me.

How to check SQL Server version

Following are possible ways to see the version:

Method 1: Connect to the instance of SQL Server, and then run the following query:

Select @@version

An example of the output of this query is as follows:

Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)   Mar 29 2009 
10:11:52   Copyright (c) 1988-2008 Microsoft Corporation  Express 
Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )

Method 2: Connect to the server by using Object Explorer in SQL Server Management Studio. After Object Explorer is connected, it will show the version information in parentheses, together with the user name that is used to connect to the specific instance of SQL Server.

Method 3: Look at the first few lines of the Errorlog file for that instance. By default, the error log is located at Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\LOG\ERRORLOG and ERRORLOG.n files. The entries may resemble the following:

2011-03-27 22:31:33.50 Server      Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)                 Mar 29 2009 10:11:52                 Copyright (c) 1988-2008 Microsoft Corporation                Express Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )

As you can see, this entry gives all the necessary information about the product, such as version, product level, 64-bit versus 32-bit, the edition of SQL Server, and the OS version on which SQL Server is running.

Method 4: Connect to the instance of SQL Server, and then run the following query:

SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')

Note This query works with any instance of SQL Server 2000 or of a later version

mysql query: SELECT DISTINCT column1, GROUP BY column2

You can just add the DISTINCT(ip), but it has to come at the start of the query. Be sure to escape PHP variables that go into the SQL string.

SELECT DISTINCT(ip), name, COUNT(name) nameCnt, 
time, price, SUM(price) priceSum
FROM tablename 
WHERE time >= $yesterday AND time <$today 
GROUP BY ip, name

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

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

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

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

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

Meaning of 'const' last in a function declaration of a class?

I would like to add the following point.

You can also make it a const & and const &&

So,

struct s{
    void val1() const {
     // *this is const here. Hence this function cannot modify any member of *this
    }
    void val2() const & {
    // *this is const& here
    }
    void val3() const && {
    // The object calling this function should be const rvalue only.
    }
    void val4() && {
    // The object calling this function should be rvalue reference only.
    }

};

int main(){
  s a;
  a.val1(); //okay
  a.val2(); //okay
  // a.val3() not okay, a is not rvalue will be okay if called like
  std::move(a).val3(); // okay, move makes it a rvalue
}

Feel free to improve the answer. I am no expert

How to include "zero" / "0" results in COUNT aggregate?

You want an outer join for this (and you need to use person as the "driving" table)

SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments"
FROM person 
  LEFT JOIN appointment ON person.person_id = appointment.person_id
GROUP BY person.person_id;

The reason why this is working, is that the outer (left) join will return NULL for those persons that do not have an appointment. The aggregate function count() will not count NULL values and thus you'll get a zero.

If you want to learn more about outer joins, here is a nice tutorial: http://sqlzoo.net/wiki/Using_Null

OS X Terminal UTF-8 issues

Go to Terminal -> Preferences -> Advanced (Tab) go down to International and select Unicode (UTF-8) as Character Encoding.

And tick Set locale environment variables on startup.

Get table column names in MySQL?

How about this:

SELECT @cCommand := GROUP_CONCAT( COLUMN_NAME ORDER BY column_name SEPARATOR ',\n')
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';

SET @cCommand = CONCAT( 'SELECT ', @cCommand, ' from my_database.my_table;');
PREPARE xCommand from @cCommand;
EXECUTE xCommand;

Getting input values from text box

you have multiple elements with the same id. That is a big no-no. Make sure your inputs have unique ids.

<td id="pass"><label>Password</label></td>
<tr>
   <td colspan="2"><input class="textBox" id="pass" type="text" maxlength="30" required/></td>
</tr>

see, both the td and the input share the id value pass.

How to override Bootstrap's Panel heading background color?

use this :

.panel-heading {
    background-color: #ececb0 !important;
}

How do I convert an existing callback API to promises?

I don't think the window.onload suggestion by @Benjamin will work all the time, as it doesn't detect whether it is called after the load. I have been bitten by that many times. Here is a version which should always work:

function promiseDOMready() {
    return new Promise(function(resolve) {
        if (document.readyState === "complete") return resolve();
        document.addEventListener("DOMContentLoaded", resolve);
    });
}
promiseDOMready().then(initOnLoad);

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

What is the difference between encrypting and signing in asymmetric encryption?

Yeah think of signing data as giving it your own wax stamp that nobody else has. It is done to achieve integrity and non-repudiation. Encryption is so no-one else can see the data. This is done to achieve confidentiality. See wikipedia http://en.wikipedia.org/wiki/Information_security#Key_concepts

A signature is a hash of your message signed using your private key.

Adding days to a date in Java

Calendar cal = Calendar.getInstance();    
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.YEAR, 2012);
cal.add(Calendar.DAY_OF_MONTH, 5);

You can also substract days like Calendar.add(Calendar.DAY_OF_MONTH, -5);

Get battery level and state in Android

You don't have to register an actual BroadcastReceiver as Android's BatteryManager is using a sticky Intent:

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = registerReceiver(null, ifilter);

int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

float batteryPct = level / (float)scale;

return (int)(batteryPct*100);

This is from the official docs over at https://developer.android.com/training/monitoring-device-state/battery-monitoring.html.

Stacked Bar Plot in R

I'm obviosly not a very good R coder, but if you wanted to do this with ggplot2:

data<- rbind(c(480, 780, 431, 295, 670, 360,  190),
             c(720, 350, 377, 255, 340, 615,  345),
             c(460, 480, 179, 560,  60, 735, 1260),
             c(220, 240, 876, 789, 820, 100,   75))

a <- cbind(data[, 1], 1, c(1:4))
b <- cbind(data[, 2], 2, c(1:4))
c <- cbind(data[, 3], 3, c(1:4))
d <- cbind(data[, 4], 4, c(1:4))
e <- cbind(data[, 5], 5, c(1:4))
f <- cbind(data[, 6], 6, c(1:4))
g <- cbind(data[, 7], 7, c(1:4))

data           <- as.data.frame(rbind(a, b, c, d, e, f, g))
colnames(data) <-c("Time", "Type", "Group")
data$Type      <- factor(data$Type, labels = c("A", "B", "C", "D", "E", "F", "G"))

library(ggplot2)

ggplot(data = data, aes(x = Type, y = Time, fill = Group)) + 
       geom_bar(stat = "identity") +
       opts(legend.position = "none")

enter image description here

Calculating the position of points in a circle

Placing a number in a circular path

// variable

let number = 12; // how many number to be placed
let size = 260; // size of circle i.e. w = h = 260
let cx= size/2; // center of x(in a circle)
let cy = size/2; // center of y(in a circle)
let r = size/2; // radius of a circle

for(let i=1; i<=number; i++) {
  let ang = i*(Math.PI/(number/2));
  let left = cx + (r*Math.cos(ang));
  let top = cy + (r*Math.sin(ang));
  console.log("top: ", top, ", left: ", left);
}

Is there a rule-of-thumb for how to divide a dataset into training and validation sets?

There are two competing concerns: with less training data, your parameter estimates have greater variance. With less testing data, your performance statistic will have greater variance. Broadly speaking you should be concerned with dividing data such that neither variance is too high, which is more to do with the absolute number of instances in each category rather than the percentage.

If you have a total of 100 instances, you're probably stuck with cross validation as no single split is going to give you satisfactory variance in your estimates. If you have 100,000 instances, it doesn't really matter whether you choose an 80:20 split or a 90:10 split (indeed you may choose to use less training data if your method is particularly computationally intensive).

Assuming you have enough data to do proper held-out test data (rather than cross-validation), the following is an instructive way to get a handle on variances:

  1. Split your data into training and testing (80/20 is indeed a good starting point)
  2. Split the training data into training and validation (again, 80/20 is a fair split).
  3. Subsample random selections of your training data, train the classifier with this, and record the performance on the validation set
  4. Try a series of runs with different amounts of training data: randomly sample 20% of it, say, 10 times and observe performance on the validation data, then do the same with 40%, 60%, 80%. You should see both greater performance with more data, but also lower variance across the different random samples
  5. To get a handle on variance due to the size of test data, perform the same procedure in reverse. Train on all of your training data, then randomly sample a percentage of your validation data a number of times, and observe performance. You should now find that the mean performance on small samples of your validation data is roughly the same as the performance on all the validation data, but the variance is much higher with smaller numbers of test samples

How to grep for contents after pattern?

This will print everything after each match, on that same line only:

perl -lne 'print $1 if /^potato:\s*(.*)/' file.txt

This will do the same, except it will also print all subsequent lines:

perl -lne 'if ($found){print} elsif (/^potato:\s*(.*)/){print $1; $found++}' file.txt

These command-line options are used:

  • -n loop around each line of the input file
  • -l removes newlines before processing, and adds them back in afterwards
  • -e execute the perl code

How can I find the number of arguments of a Python function?

someMethod.func_code.co_argcount

or, if the current function name is undetermined:

import sys

sys._getframe().func_code.co_argcount

Error when testing on iOS simulator: Couldn't register with the bootstrap server

No rebuild or reinstall needed for my issue, and in my case the error appeared when trying to run the app on the iPhone. Simulator worked fine.

Solution: Delete app off phone, do a cold restart of phone and now all is well.

Add x and y labels to a pandas plot

pandas uses matplotlib for basic dataframe plots. So, if you are using pandas for basic plot you can use matplotlib for plot customization. However, I propose an alternative method here using seaborn which allows more customization of the plot while not going into the basic level of matplotlib.

Working Code:

import pandas as pd
import seaborn as sns
values = [[1, 2], [2, 5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], 
                   index=['Index 1', 'Index 2'])
ax= sns.lineplot(data=df2, markers= True)
ax.set(xlabel='xlabel', ylabel='ylabel', title='Video streaming dropout by category') 

enter image description here

Checkbox for nullable boolean

I had a similar issue in the past.

Create a Checkbox input in HTML, and set the attribute name="Foo" This should still post properly.

<input type="checkbox" name="Foo" checked="@model.Foo.Value" /> Foo Checkbox<br />

Javascript return number of days,hours,minutes,seconds between two dates

Here's my take:

timeSince(123456) => "1 day, 10 hours, 17 minutes, 36 seconds"

And the code:

function timeSince(date, longText) {
    let seconds = null;
    let leadingText = null;

    if (date instanceof Date) {
        seconds = Math.floor((new Date() - date) / 1000);
        if (seconds < 0) {
            leadingText = " from now";
        } else {
            leadingText = " ago";
        }
        seconds = Math.abs(seconds);
    } else {
        seconds = date;
        leadingText = "";
    }

    const intervals = [
        [31536000, "year"  ],
        [ 2592000, "month" ],
        [   86400, "day"   ],
        [    3600, "hour"  ],
        [      60, "minute"],
        [       1, "second"],
    ];

    let interval = seconds;
    let intervalStrings = [];
    for (let i = 0; i < intervals.length; i++) {
        let divResult = Math.floor(interval / intervals[i][0]);
        if (divResult > 0) {
            intervalStrings.push(divResult + " " + intervals[i][1] + ((divResult > 1) ? "s" : ""));
            interval = interval % intervals[i][0];
            if (!longText) {
                break;
            }
        }
    }
    let intStr = intervalStrings.join(", ");

    return intStr + leadingText;
}

How to do a LIKE query with linq?

Try like this

var results = db.costumers.Where(X=>X.FullName.Contains(FirstName)&&(X=>X.FullName.EndsWith(LastName))
                          .Select(X=>X);

How do I multiply each element in a list by a number?

I found it interesting to use list comprehension or map with just one object name x. Note that whenever x is reassigned, its id(x) changes, i.e. points to a different object.

x = [1, 2, 3]
id(x)
2707834975552
x = [1.5 * x for x in x]
id(x)
2707834976576
x
[1.5, 3.0, 4.5]
list(map(lambda x : 2 * x / 3, x))
[1.0, 2.0, 3.0]
id(x) # not reassigned
2707834976576
x = list(map(lambda x : 2 * x / 3, x))
x
[1.0, 2.0, 3.0]
id(x)
2707834980928

Java Currency Number format

I was crazy enough to write my own function:

This will convert integer to currency format (can be modified for decimals as well):

 String getCurrencyFormat(int v){
        String toReturn = "";
        String s =  String.valueOf(v);
        int length = s.length();
        for(int i = length; i >0 ; --i){
            toReturn += s.charAt(i - 1);
            if((i - length - 1) % 3 == 0 && i != 1) toReturn += ',';
        }
        return "$" + new StringBuilder(toReturn).reverse().toString();
    }

Triggering a checkbox value changed event in DataGridView

cellEndEditTimer.Start();

this line makes the datagridview update the list of checked boxes

Thank you.

What is the difference between Html.Hidden and Html.HiddenFor

Most of the MVC helper methods have a XXXFor variant. They are intended to be used in conjunction with a concrete model class. The idea is to allow the helper to derive the appropriate "name" attribute for the form-input control based on the property you specify in the lambda. This means that you get to eliminate "magic strings" that you would otherwise have to employ to correlate the model properties with your views. For example:

Html.Hidden("Name", "Value")

Will result in:

<input id="Name" name="Name" type="hidden" value="Value">

In your controller, you might have an action like:

[HttpPost]
public ActionResult MyAction(MyModel model) 
{
}

And a model like:

public class MyModel 
{
    public string Name { get; set; }
}

The raw Html.Hidden we used above will get correlated to the Name property in the model. However, it's somewhat distasteful that the value "Name" for the property must be specified using a string ("Name"). If you rename the Name property on the Model, your code will break and the error will be somewhat difficult to figure out. On the other hand, if you use HiddenFor, you get protected from that:

Html.HiddenFor(x => x.Name, "Value");

Now, if you rename the Name property, you will get an explicit runtime error indicating that the property can't be found. In addition, you get other benefits of static analysis, such as getting a drop-down of the members after typing x..

why numpy.ndarray is object is not callable in my simple for python loop

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function.

Use

Z=XY[0]+XY[1]

Instead of

Z=XY(i,0)+XY(i,1)

Rails: Can't verify CSRF token authenticity when making a POST request

The simplest solution for the problem is do standard things in your controller or you can directely put it into ApplicationController

class ApplicationController < ActionController::Base protect_from_forgery with: :exception, prepend: true end

Print execution time of a shell command

If I'm starting a long-running process like a copy or hash and I want to know later how long it took, I just do this:

$ date; sha1sum reallybigfile.txt; date

Which will result in the following output:

Tue Jun  2 21:16:03 PDT 2015
5089a8e475cc41b2672982f690e5221469390bc0  reallybigfile.txt
Tue Jun  2 21:33:54 PDT 2015

Granted, as implemented here it isn't very precise and doesn't calculate the elapsed time. But it's dirt simple and sometimes all you need.

Format number to 2 decimal places

When formatting number to 2 decimal places you have two options TRUNCATE and ROUND. You are looking for TRUNCATE function.

Examples:

Without rounding:

TRUNCATE(0.166, 2)
-- will be evaluated to 0.16

TRUNCATE(0.164, 2)
-- will be evaluated to 0.16

docs: http://www.w3resource.com/mysql/mathematical-functions/mysql-truncate-function.php

With rounding:

ROUND(0.166, 2)
-- will be evaluated to 0.17

ROUND(0.164, 2)
-- will be evaluated to 0.16

docs: http://www.w3resource.com/mysql/mathematical-functions/mysql-round-function.php

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

How to return 2 values from a Java method?

Here is the really simple and short solution with SimpleEntry:

AbstractMap.Entry<String, Float> myTwoCents=new AbstractMap.SimpleEntry<>("maximum possible performance reached" , 99.9f);

String question=myTwoCents.getKey();
Float answer=myTwoCents.getValue();

Only uses Java built in functions and it comes with the type safty benefit.

How to override the path of PHP to use the MAMP path?

Sometimes, it's easier to do this:

sudo ln -s /Applications/MAMP/bin/php/php5.6.10/bin/php /usr/bin/php;

Mamps version of PHP at the time of posting was php5.6.10, so make sure you change that to the version you're using.

You'll be up in a jiffy.

convert big endian to little endian in C [without using provided func]

If you are running on a x86 or x86_64 processor, the big endian is native. so

for 16 bit values

unsigned short wBigE = value;
unsigned short wLittleE = ((wBigE & 0xFF) << 8) | (wBigE >> 8);

for 32 bit values

unsigned int   iBigE = value;
unsigned int   iLittleE = ((iBigE & 0xFF) << 24)
                        | ((iBigE & 0xFF00) << 8)
                        | ((iBigE >> 8) & 0xFF00)
                        | (iBigE >> 24);

This isn't the most efficient solution unless the compiler recognises that this is byte level manipulation and generates byte swapping code. But it doesn't depend on any memory layout tricks and can be turned into a macro pretty easily.

Get input type="file" value when it has multiple files selected

You use input.files property. It's a collection of File objects and each file has a name property:

onmouseout="for (var i = 0; i < this.files.length; i++) alert(this.files[i].name);"

HTTP Status 504

CheckUpDown has a nice explanation of the 504 error:

A server (not necessarily a Web server) is acting as a gateway or proxy to fulfil the request by the client (e.g. your Web browser or our CheckUpDown robot) to access the requested URL. This server did not receive a timely response from an upstream server it accessed to deal with your HTTP request.

This usually means that the upstream server is down (no response to the gateway/proxy), rather than that the upstream server and the gateway/proxy do not agree on the protocol for exchanging data.

This problem is entirely due to slow IP communication between back-end computers, possibly including the Web server. Only the people who set up the network at the site which hosts the Web server can fix this problem.

Output of git branch in tree like fashion

It's not quite what you asked for, but

git log --graph --simplify-by-decoration --pretty=format:'%d' --all

does a pretty good job. It shows tags and remote branches as well. This may not be desirable for everyone, but I find it useful. --simplifiy-by-decoration is the big trick here for limiting the refs shown.

I use a similar command to view my log. I've been able to completely replace my gitk usage with it:

git log --graph --oneline --decorate --all

I use it by including these aliases in my ~/.gitconfig file:

[alias]
    l = log --graph --oneline --decorate
    ll = log --graph --oneline --decorate --branches --tags
    lll = log --graph --oneline --decorate --all

Edit: Updated suggested log command/aliases to use simpler option flags.

Is it correct to use DIV inside FORM?

Absolutely not! It will render, but it will not validate. Use a label.

It is not correct. It is not accessible. You see it on some websites because some developers are just lazy. When I am hiring developers, this is one of the first things I check for in candidates work. Forms are nasty, but take the time and learn to do them properly

Is it possible to use a div as content for Twitter's Popover

In addition to other replies. If you allow html in options you can pass jQuery object to content, and it will be appended to popover's content with all events and bindings. Here is the logic from source code:

  • if you pass a function it will be called to unwrap content data
  • if html is not allowed content data will be applied as text
  • if html allowed and content data is string it will be applied as html
  • otherwise content data will be appended to popover's content container
$("#popover-button").popover({
    content: $("#popover-content"),
    html: true,
    title: "Popover title"
});

"Uncaught Error: [$injector:unpr]" with angular after deployment

If you follow your link, it tells you that the error results from the $injector not being able to resolve your dependencies. This is a common issue with angular when the javascript gets minified/uglified/whatever you're doing to it for production.

The issue is when you have e.g. a controller;

angular.module("MyApp").controller("MyCtrl", function($scope, $q) {
  // your code
})

The minification changes $scope and $q into random variables that doesn't tell angular what to inject. The solution is to declare your dependencies like this:

angular.module("MyApp")
  .controller("MyCtrl", ["$scope", "$q", function($scope, $q) {
  // your code
}])

That should fix your problem.

Just to re-iterate, everything I've said is at the link the error message provides to you.

How to access environment variable values?

There's also a number of great libraries. Envs for example will allow you to parse objects out of your environment variables, which is rad. For example:

from envs import env
env('SECRET_KEY') # 'your_secret_key_here'
env('SERVER_NAMES',var_type='list') #['your', 'list', 'here']

How to safely open/close files in python 2.4

No need to close the file according to the docs if you use with:

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:

>>> with open('workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

More here: https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

SVN 405 Method Not Allowed

The quickest way for me to fix it was to duplicate the affected folder, and commit it with an alternative name. Then svn mv duplicateFolder originalFolder. Pretty easy.

So, take folder1 and make a folder1Copy:

svn delete folder1
svn add folder1Copy

Commit and update:

svn mv folder1Copy/ folder1/

Commit again and it's fixed.

when do you need .ascx files and how would you use them?

ASCX files are server-side Web application framework designed for Web development to produce dynamic Web pages.They like DLL codes but you can use there's TAGS You can write them once and use them in any places in your ASP pages.If you have a file named "Controll.ascx" then its code will named "Controll.ascx.cs". You can embed it in a ASP page to use it:

How to sort a NSArray alphabetically?

-(IBAction)SegmentbtnCLK:(id)sender
{ [self sortArryofDictionary];
    [self.objtable reloadData];}
-(void)sortArryofDictionary
{ NSSortDescriptor *sorter;
    switch (sortcontrol.selectedSegmentIndex)
    {case 0:
            sorter=[[NSSortDescriptor alloc]initWithKey:@"Name" ascending:YES];
            break;
        case 1:
            sorter=[[NSSortDescriptor alloc]initWithKey:@"Age" ascending:YES];
            default:
            break; }
    NSArray *sortdiscriptor=[[NSArray alloc]initWithObjects:sorter, nil];
    [arr sortUsingDescriptors:sortdiscriptor];
    }

Spring configure @ResponseBody JSON format

For Spring version 4.1.3+

I tried Jama's solution, but then all responses were returned with Content-type 'application/json', including the main, generated HTML page.

Overriding configureMessageConverters(...) prevents spring from setting up the default converters. Spring 4.1.3 allows modification of already configured converters by overriding extendMessageConverters(...):

@Configuration
public class ConverterConfig extends WebMvcConfigurerAdapter {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof AbstractJackson2HttpMessageConverter) {
                AbstractJackson2HttpMessageConverter c = (AbstractJackson2HttpMessageConverter) converter;
                ObjectMapper objectMapper = c.getObjectMapper();
                objectMapper.setSerializationInclusion(Include.NON_NULL);
            }
        }

        super.extendMessageConverters(converters);
    }
}

see org.springframework..WebMvcConfigurationSupport#getMessageConverters()

see org.springframework..WebMvcConfigurationSupport#addDefaultHttpMessageConverters(...)

What is the Swift equivalent of isEqualToString in Objective-C?

Actually, it feels like swift is trying to promote strings to be treated less like objects and more like values. However this doesn't mean under the hood swift doesn't treat strings as objects, as am sure you all noticed that you can still invoke methods on strings and use their properties.

For example:-

//example of calling method (String to Int conversion)
let intValue = ("12".toInt())
println("This is a intValue now \(intValue)")


//example of using properties (fetching uppercase value of string)
let caUpperValue = "ca".uppercaseString
println("This is the uppercase of ca \(caUpperValue)")

In objectC you could pass the reference to a string object through a variable, on top of calling methods on it, which pretty much establishes the fact that strings are pure objects.

Here is the catch when you try to look at String as objects, in swift you cannot pass a string object by reference through a variable. Swift will always pass a brand new copy of the string. Hence, strings are more commonly known as value types in swift. In fact, two string literals will not be identical (===). They are treated as two different copies.

let curious = ("ca" === "ca")
println("This will be false.. and the answer is..\(curious)")

As you can see we are starting to break aways from the conventional way of thinking of strings as objects and treating them more like values. Hence .isEqualToString which was treated as an identity operator for string objects is no more a valid as you can never get two identical string objects in Swift. You can only compare its value, or in other words check for equality(==).

 let NotSoCuriousAnyMore = ("ca" == "ca")
 println("This will be true.. and the answer is..\(NotSoCuriousAnyMore)")

This gets more interesting when you look at the mutability of string objects in swift. But thats for another question, another day. Something you should probably look into, cause its really interesting. :) Hope that clears up some confusion. Cheers!

Android: android.content.res.Resources$NotFoundException: String resource ID #0x5

Just wanted to point out another reason this error can be thrown is if you defined a string resource for one translation of your app but did not provide a default string resource.

Example of the Issue:

As you can see below, I had a string resource for a Spanish string "get_started". It can still be referenced in code, but if the phone is not in Spanish it will have no resource to load and crash when calling getString().

values-es/strings.xml

<string name="get_started">SIGUIENTE</string>

Reference to resource

textView.setText(getString(R.string.get_started)

Logcat:

06-11 11:46:37.835    7007-7007/? E/AndroidRuntime? FATAL EXCEPTION: main
Process: com.app.test PID: 7007
android.content.res.Resources$NotFoundException: String resource ID #0x7f0700fd
        at android.content.res.Resources.getText(Resources.java:299)
        at android.content.res.Resources.getString(Resources.java:385)
        at com.juvomobileinc.tigousa.ui.signin.SignInFragment$4.onClick(SignInFragment.java:188)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Solution to the Issue

Preventing this is quite simple, just make sure that you always have a default string resource in values/strings.xml so that if the phone is in another language it will always have a resource to fall back to.

values/strings.xml

<string name="get_started">Get Started</string>

values-en/strings.xml

<string name="get_started">Get Started</string>

values-es/strings.xml

<string name="get_started">Siguiente</string>

values-de/strings.xml

<string name="get_started">Ioslegen</string>

make arrayList.toArray() return more specific types

I got the answer...this seems to be working perfectly fine

public int[] test ( int[]b )
{
    ArrayList<Integer> l = new ArrayList<Integer>();
    Object[] returnArrayObject = l.toArray();
    int returnArray[] = new int[returnArrayObject.length];
    for (int i = 0; i < returnArrayObject.length; i++){
         returnArray[i] = (Integer)  returnArrayObject[i];
    }

    return returnArray;
}

How to get the index with the key in Python dictionary?

Dictionaries in python have no order. You could use a list of tuples as your data structure instead.

d = { 'a': 10, 'b': 20, 'c': 30}
newd = [('a',10), ('b',20), ('c',30)]

Then this code could be used to find the locations of keys with a specific value

locations = [i for i, t in enumerate(newd) if t[0]=='b']

>>> [1]

What does it mean by command cd /d %~dp0 in Windows

~dp0 : d=drive, p=path, %0=full path\name of this batch-file.

cd /d %~dp0 will change the path to the same, where the batch file resides.

See for /? or call / for more details about the %~... modifiers.
See cd /? about the /d switch.

How do I run Visual Studio as an administrator by default?

For Windows 8

  1. right click on the shortcut
  2. click on properties
  3. click on the "Shortcut" tab
  4. click on Advanced

You will find Run As administrator (Checkbox)

Online SQL Query Syntax Checker

A lot of people, including me, use sqlfiddle.com to test SQL.

Specifying number of decimal places in Python

I'm astonished by the second number you mention (and confirm by your requested rounding) -- at first I thought my instinct for mental arithmetic was starting to fail me (I am getting older, after all, so that might be going the same way as my once-sharp memory!-)... but then I confirmed it hasn't, yet, by using, as I imagine you are, Python 3.1, and copying and pasting..:

>>> def input_meal():  
...     mealPrice = input('Enter the meal subtotal: $')  
...     mealPrice = float (mealPrice)  
...     return mealPrice  
... 
>>> def calc_tax(mealPrice):  
...     tax = mealPrice*.06  
...     return tax
... 
>>> m = input_meal()
Enter the meal subtotal: $34.45
>>> print(calc_tax(m))
2.067
>>> 

...as expected -- yet, you say it instead "returns a display of $ 2.607"... which might be a typo, just swapping two digits, except that you then ask "How can I set that to $2.61 instead?" so it really seems you truly mean 2.607 (which might be rounded to 2.61 in various ways) and definitely not the arithmetically correct result, 2.067 (which at best might be rounded to 2.07... definitely not to 2.61 as you request).

I imagine you first had the typo occur in transcription, and then mentally computed the desired rounding from the falsified-by-typo 2.607 rather than the actual original result -- is that what happened? It sure managed to confuse me for a while!-)

Anyway, to round a float to two decimal digits, simplest approach is the built-in function round with a second argument of 2:

>>> round(2.067, 2)
2.07
>>> round(2.607, 2)
2.61

For numbers exactly equidistant between two possibilities, it rounds-to-even:

>>> round(2.605, 2)
2.6
>>> round(2.615, 2)
2.62

or, as the docs put it (exemplifying with the single-argument form of round, which rounds to the closest integer):

if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).

However, for computations on money, I second the recommendation, already given in other answers, to stick with what the decimal module offers, instead of float numbers.

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

Adding to the thread, there's a new console in town called babun, im running tmux in it without a problem. lets you run bash or the zsh.

click here for github

Maintain model of scope when changing between views in AngularJS

$rootScope is a big global variable, which is fine for one-off things, or small apps. Use a service if you want to encapsulate your model and/or behavior (and possibly reuse it elsewhere). In addition to the google group post the OP mentioned, see also https://groups.google.com/d/topic/angular/eegk_lB6kVs/discussion.

How to convert an int array to String with toString method in Java

This function returns a array of int in the string form like "6097321041141011026"

private String IntArrayToString(byte[] array) {
        String strRet="";
        for(int i : array) {
            strRet+=Integer.toString(i);
        }
        return strRet;
    }

Get integer value of the current year in Java

Use the following code for java 8 :

LocalDate localDate = LocalDate.now();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int date = localDate.getDayOfMonth();

Postman - How to see request with headers and body data with variables substituted

Even though they are separate windows but the request you send from Postman, it's details should be available in network tab of developer tools. Just make sure you are not sending any other http traffic during that time, just for clarity.

Git merge with force overwrite

You can try "ours" option in git merge,

git merge branch -X ours

This option forces conflicting hunks to be auto-resolved cleanly by favoring our version. Changes from the other tree that do not conflict with our side are reflected to the merge result. For a binary file, the entire contents are taken from our side.

PHP and MySQL Select a Single Value

You do this by using mysqli_fetch_field method.

session_start();
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' limit 1";
$result = mysqli_query($link, $sql);
if ($result !== false) {
    $value = mysqli_fetch_field($result);
    $_SESSION['myid'] = $value;
}

Note: you can do that by using mysql_fetch_field() method as well, but it will be deprecated in php v5.5

Basic Apache commands for a local Windows machine

Going back to absolute basics here. The answers on this page and a little googling have brought me to the following resolution to my issue. Steps to restart the apache service with Xampp installed:-

  1. Click the start button and type CMD (if on Windows Vista or later and Apache is installed as a service make sure this is an elevated command prompt)
  2. In the command window that appears type cd C:\xampp\apache\bin (the default installation path for Xampp)
  3. Then type httpd -k restart

I hope that this is of use to others just starting out with running a local Apache server.

How to call jQuery function onclick?

JS

 $(function () {
    var url = $(location).attr('href');
    $('#spn_url').html('<strong>' + url + '</strong>');
    $("#submit").click(function () {
        alert('button clicked');
    });
});

html

<input id="submit" type="submit" value="submit" name="submit">

How to do a for loop in windows command line?

The commandline interpreter does indeed have a FOR construct that you can use from the command prompt or from within a batch file.

For your purpose, you probably want something like:

FOR %i IN (*.ext) DO my-function %i

Which will result in the name of each file with extension *.ext in the current directory being passed to my-function (which could, for example, be another .bat file).

The (*.ext) part is the "filespec", and is pretty flexible with how you specify sets of files. For example, you could do:

FOR %i IN (C:\Some\Other\Dir\*.ext) DO my-function %i

To perform an operation in a different directory.

There are scores of options for the filespec and FOR in general. See

HELP FOR

from the command prompt for more information.

Conversion failed when converting the varchar value 'simple, ' to data type int

In order to avoid such error you could use CASE + ISNUMERIC to handle scenarios when you cannot convert to int.
Change

CONVERT(INT, CONVERT(VARCHAR(12), a.value))

To

CONVERT(INT,
        CASE
        WHEN IsNumeric(CONVERT(VARCHAR(12), a.value)) = 1 THEN CONVERT(VARCHAR(12),a.value)
        ELSE 0 END) 

Basically this is saying if you cannot convert me to int assign value of 0 (in my example)

Alternatively you can look at this article about creating a custom function that will check if a.value is number: http://www.tek-tips.com/faqs.cfm?fid=6423

What are these ^M's that keep showing up in my files in emacs?

^M is 0x0d, i.e. the carriage return character. If your display looks like

line 1^M
line 2^M

then the file must have come from Windows because the standard newline sequence on Windows is CR LF (0x0d 0x0a) whereas the standard newline sequence consists solely of LF on Unices.

If the file had come from a Mac OS 9 or earlier system, you would see it as

line 1^Mline 2^M

because there would be no line feeds following the carriage returns.

Execute bash script from URL

You can also do this:

wget -O - https://raw.github.com/luismartingil/commands/master/101_remote2local_wireshark.sh | bash

Get environment variable value in Dockerfile

Load environment variables from a file you create at runtime.

export MYVAR="my_var_outside"
cat > build/env.sh <<EOF
MYVAR=${MYVAR}
EOF

... then in the Dockerfile

ADD build /build
RUN /build/test.sh

where test.sh loads MYVAR from env.sh

#!/bin/bash
. /build/env.sh
echo $MYVAR > /tmp/testfile

Better naming in Tuple classes than "Item1", "Item2"

(double, int) t1 = (4.5, 3);
Console.WriteLine($"Tuple with elements {t1.Item1} and {t1.Item2}.");
// Output:
// Tuple with elements 4.5 and 3.

(double Sum, int Count) t2 = (4.5, 3);
Console.WriteLine($"Sum of {t2.Count} elements is {t2.Sum}.");
// Output:
// Sum of 3 elements is 4.5.
From Docs https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples

change html input type by JS?

Changing the type of an <input type=password> throws a security error in some browsers (old IE and Firefox versions).

You’ll need to create a new input element, set its type to the one you want, and clone all other properties from the existing one.

I do this in my jQuery placeholder plugin: https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js#L80-84

To work in Internet Explorer:

  • dynamically create a new element
  • copy the properties of the old element into the new element
  • set the type of the new element to the new type
  • replace the old element with the new element

The function below accomplishes the above tasks for you:

<script>
function changeInputType(oldObject, oType) {
    var newObject = document.createElement('input');
    newObject.type = oType;
    if(oldObject.size) newObject.size = oldObject.size;
    if(oldObject.value) newObject.value = oldObject.value;
    if(oldObject.name) newObject.name = oldObject.name;
    if(oldObject.id) newObject.id = oldObject.id;
    if(oldObject.className) newObject.className = oldObject.className;
    oldObject.parentNode.replaceChild(newObject,oldObject);
    return newObject;
}
</script>

How to detect if numpy is installed

If you use eclipse, you simply type "import numpy" and eclipse will "complain" if doesn't find.

Group by with union mysql select query

Try this EDITED:

(SELECT COUNT(motorbike.owner_id),owner.name,transport.type FROM transport,owner,motorbike WHERE transport.type='motobike' AND owner.owner_id=motorbike.owner_id AND transport.type_id=motorbike.motorbike_id GROUP BY motorbike.owner_id)

UNION ALL

(SELECT COUNT(car.owner_id),owner.name,transport.type FROM transport,owner,car WHERE transport.type='car' AND owner.owner_id=car.owner_id AND transport.type_id=car.car_id GROUP BY car.owner_id)

How to effectively work with multiple files in Vim

I use the command line and git a lot, so I have this alias in my bashrc:

alias gvim="gvim --servername \$(git rev-parse --show-toplevel || echo 'default') --remote-tab"

This will open each new file in a new tab on an existing window and will create one window for each git repository. So if you open two files from repo A, and 3 files from repo B, you will end up with two windows, one for repo A with two tabs and one for repo B with three tabs.

If the file you are opening is not contained in a git repo it will go to a default window.

To jump between tabs I use these mappings:

nmap <C-p> :tabprevious<CR>
nmap <C-n> :tabnext<CR>

To open multiple files at once you should combine this with one of the other solutions.

How to remove decimal part from a number in C#

Because the numbers after point is only zero, the best solution is to use the Math.Round(MyNumber)

jQuery selector first td of each row

Use:

$("tr").find("td:first");

js fiddle - this example has .text() on the end to show that it is returning the elements.

Alternatively, you can use:

$("td:first-child");

.find() - jQuery API Documentation

Lambda function in list comprehensions

The other answers are correct, but if you are trying to make a list of functions, each with a different parameter, that can be executed later, the following code will do that:

import functools
a = [functools.partial(lambda x: x*x, x) for x in range(10)]

b = []
for i in a:
    b.append(i())

In [26]: b
Out[26]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

While the example is contrived, I found it useful when I wanted a list of functions that each print something different, i.e.

import functools
a = [functools.partial(lambda x: print(x), x) for x in range(10)]

for i in a:
    i()

Add Custom Headers using HttpWebRequest

IMHO it is considered as malformed header data.

You actually want to send those name value pairs as the request content (this is the way POST works) and not as headers.

The second way is true.

JBoss vs Tomcat again

I have also read that for some servers one for example needs only annotate persistence contexts, but in some servers, the injection should be done manually.

Text editor to open big (giant, huge, large) text files

Free read-only viewers:

  • Large Text File Viewer (Windows) – Fully customizable theming (colors, fonts, word wrap, tab size). Supports horizontal and vertical split view. Also support file following and regex search. Very fast, simple, and has small executable size.
  • klogg (Windows, macOS, Linux) – A maintained fork of glogg, its main feature is regular expression search. It can also watch files, allows the user to mark lines, and has serious optimizations built in. But from a UI standpoint, it's ugly and clunky.
  • LogExpert (Windows) – "A GUI replacement for tail." It's really a log file analyzer, not a large file viewer, and in one test it required 10 seconds and 700 MB of RAM to load a 250 MB file. But its killer features are the columnizer (parse logs that are in CSV, JSONL, etc. and display in a spreadsheet format) and the highlighter (show lines with certain words in certain colors). Also supports file following, tabs, multifiles, bookmarks, search, plugins, and external tools.
  • Lister (Windows) – Very small and minimalist. It's one executable, barely 500 KB, but it still supports searching (with regexes), printing, a hex editor mode, and settings.
  • loxx (Windows) – Supports file following, highlighting, line numbers, huge files, regex, multiple files and views, and much more. The free version can not: process regex, filter files, synchronize timestamps, and save changed files.

Free editors:

  • Your regular editor or IDE. Modern editors can handle surprisingly large files. In particular, Vim (Windows, macOS, Linux), Emacs (Windows, macOS, Linux), Notepad++ (Windows), Sublime Text (Windows, macOS, Linux), and VS Code (Windows, macOS, Linux) support large (~4 GB) files, assuming you have the RAM.
  • Large File Editor (Windows) – Opens and edits TB+ files, supports Unicode, uses little memory, has XML-specific features, and includes a binary mode.
  • GigaEdit (Windows) – Supports searching, character statistics, and font customization. But it's buggy – with large files, it only allows overwriting characters, not inserting them; it doesn't respect LF as a line terminator, only CRLF; and it's slow.

Builtin programs (no installation required):

  • less (macOS, Linux) – The traditional Unix command-line pager tool. Lets you view text files of practically any size. Can be installed on Windows, too.
  • Notepad (Windows) – Decent with large files, especially with word wrap turned off.
  • MORE (Windows) – This refers to the Windows MORE, not the Unix more. A console program that allows you to view a file, one screen at a time.

Web viewers:

Paid editors:

  • 010 Editor (Windows, macOS, Linux) – Opens giant (as large as 50 GB) files.
  • SlickEdit (Windows, macOS, Linux) – Opens large files.
  • UltraEdit (Windows, macOS, Linux) – Opens files of more than 6 GB, but the configuration must be changed for this to be practical: Menu » Advanced » Configuration » File Handling » Temporary Files » Open file without temp file...
  • EmEditor (Windows) – Handles very large text files nicely (officially up to 248 GB, but as much as 900 GB according to one report).
  • BssEditor (Windows) – Handles large files and very long lines. Don’t require an installation. Free for non commercial use.

Using Notepad++ to validate XML against an XSD

  1. In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager then find Xml Tools plugin. Tick the box and click Install

    enter image description here

  2. Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now).
    Following dialog will open: enter image description here

  3. Click on .... Point to XSD file and I am pretty sure you'll be able to handle things from here.

Hope this saves you some time.

EDIT: Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1 plugin manager is back under a different guise... Plugin Admin so now you can simply update notepad++ and have it back.

enter image description here

Android getText from EditText field

Sample code for How to get text from EditText.

Android Java Syntax

EditText text = (EditText)findViewById(R.id.vnosEmaila);
String value = text.getText().toString();

Kotlin Syntax

val text = findViewById<View>(R.id.vnosEmaila) as EditText
val value = text.text.toString()

JavaScript: Difference between .forEach() and .map()

One thing to point out is that foreach skips uninitialized values while map does not.

var arr = [1, , 3];

arr.forEach(function(element) {
    console.log(element);
});
//Expected output: 1 3

console.log(arr.map(element => element));
//Expected output: [1, undefined, 3];

How to add custom Http Header for C# Web Service Client consuming Axis 1.4 Web service

Instead of modding the auto-generated code or wrapping every call in duplicate code, you can inject your custom HTTP headers by adding a custom message inspector, it's easier than it sounds:

public class CustomMessageInspector : IClientMessageInspector
{
    readonly string _authToken;

    public CustomMessageInspector(string authToken)
    {
        _authToken = authToken;
    }

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        var reqMsgProperty = new HttpRequestMessageProperty();
        reqMsgProperty.Headers.Add("Auth-Token", _authToken);
        request.Properties[HttpRequestMessageProperty.Name] = reqMsgProperty;
        return null;
    }

    public void AfterReceiveReply(ref Message reply, object correlationState)
    { }
}


public class CustomAuthenticationBehaviour : IEndpointBehavior
{
    readonly string _authToken;

    public CustomAuthenticationBehaviour (string authToken)
    {
        _authToken = authToken;
    }
    public void Validate(ServiceEndpoint endpoint)
    { }

    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    { }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    { }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.ClientMessageInspectors.Add(new CustomMessageInspector(_authToken));
    }
}

And when instantiating your client class you can simply add it as a behavior:

this.Endpoint.EndpointBehaviors.Add(new CustomAuthenticationBehaviour("Auth Token"));

This will make every outgoing service call to have your custom HTTP header.

Basic calculator in Java

import java.util.Scanner;
public class JavaApplication1 {


    public static void main(String[] args) {

         int x,
         int y;

         Scanner input=new Scanner(System.in);
         System.out.println("Enter Number 1");
         x=input.nextInt();
         System.out.println("Enter Number 2");
         y=input.nextInt();

         System.out.println("Please enter operation + - / or *");
         Scanner op=new Scanner(System.in);
         String operation = op.next();

         if (operation.equals("+")){
             System.out.println("Your Answer: " + (x+y));
         }
         if (operation.equals("-")){
             System.out.println("Your Answer: "+ (x-y));
         }
         if (operation.equals("/")){
             System.out.println("Your Answer: "+ (x/y));
         }
         if (operation.equals("*")){
            System.out.println("Your Answer: "+ (x*y));
         }
    }

}

How do I iterate over a range of numbers defined by variables in Bash?

This works fine in bash:

END=5
i=1 ; while [[ $i -le $END ]] ; do
    echo $i
    ((i = i + 1))
done

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

There is a difference.

When the ^ character appears outside of [] matches the beginning of the line (or string). When the ^ character appears inside the [], it matches any character not appearing inside the [].

PHP function to get the subdomain of a URL

Try this...

$domain = 'en.example.com';
$tmp = explode('.', $domain);
$subdomain = current($tmp);
echo($subdomain);     // echo "en"

Java difference between FileWriter and BufferedWriter

http://docs.oracle.com/javase/1.5.0/docs/api/java/io/BufferedWriter.html

In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. For example,

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));

will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.

Byte Array to Image object

From Database.
Blob blob = resultSet.getBlob("pictureBlob");               
byte [] data = blob.getBytes( 1, ( int ) blob.length() );
BufferedImage img = null;
try {
img = ImageIO.read(new ByteArrayInputStream(data));
} catch (IOException e) {
    e.printStackTrace();
}
drawPicture(img);  //  void drawPicture(Image img);

Mismatch Detected for 'RuntimeLibrary'

Issue can be solved by adding CRT of msvcrtd.lib in the linker library. Because cryptlib.lib used CRT version of debug.

Detect Windows version in .net

This is a relatively old question but I've recently had to solve this problem and didn't see my solution posted anywhere.

The easiest (and simplest way in my opinion) is to just use a pinvoke call to RtlGetVersion

[DllImport("ntdll.dll", SetLastError = true)]
internal static extern uint RtlGetVersion(out Structures.OsVersionInfo versionInformation); // return type should be the NtStatus enum

[StructLayout(LayoutKind.Sequential)]
internal struct OsVersionInfo
{
    private readonly uint OsVersionInfoSize;

    internal readonly uint MajorVersion;
    internal readonly uint MinorVersion;

    private readonly uint BuildNumber;

    private readonly uint PlatformId;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
    private readonly string CSDVersion;
}

Where Major and Minor version numbers in this struct correspond to the values in the table of the accepted answer.

This returns the correct Windows version number unlike the deprecated GetVersion & GetVersionEx functions from kernel32

Browser Timeouts

It's browser dependent. "By default, Internet Explorer has a KeepAliveTimeout value of one minute and an additional limiting factor (ServerInfoTimeout) of two minutes. Either setting can cause Internet Explorer to reset the socket." - from IE support http://support.microsoft.com/kb/813827

Firefox is around the same value I think as well.

Usually though server timeout are set lower than browser timeouts, but at least you can control that and set it higher.

You'd rather handle the timeout though, so that way you can act upon such an event. See this thread: How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?

opening a window form from another form programmatically

This is an old question, but answering for gathering knowledge. We have an original form with a button to show the new form.

enter image description here

The code for the button click is below

private void button1_Click(object sender, EventArgs e)
{
    New_Form new_Form = new New_Form();
    new_Form.Show();
}

Now when click is made, New Form is shown. Since, you want to hide after 2 seconds we are adding a onload event to the new form designer

this.Load += new System.EventHandler(this.OnPageLoad);

This OnPageLoad function runs when that form is loaded

In NewForm.cs ,

public partial class New_Form : Form
{
    private Timer formClosingTimer;

    private void OnPageLoad(object sender, EventArgs e)
    {
        formClosingTimer = new Timer();  // Creating a new timer 
        formClosingTimer.Tick += new EventHandler(CloseForm); // Defining tick event to invoke after a time period
        formClosingTimer.Interval = 2000; // Time Interval in miliseconds
        formClosingTimer.Start(); // Starting a timer
    }
    private void CloseForm(object sender, EventArgs e)
    {
        formClosingTimer.Stop(); // Stoping timer. If we dont stop, function will be triggered in regular intervals
        this.Close(); // Closing the current form
    }
}

In this new form , a timer is used to invoke a method which closes that form.

Here is the new form which automatically closes after 2 seconds, we will be able operate on both the forms where no interference between those two forms.

enter image description here

For your knowledge,

form.close() will free the memory and we can never interact with that form again form.hide() will just hide the form, where the code part can still run

For more details about timer refer this link, https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.7.2

Disabling the long-running-script message in Internet Explorer

The unresponsive script dialog box shows when some javascript thread takes too long too complete. Editing the registry could work, but you would have to do it on all client machines. You could use a "recursive closure" as follows to alleviate the problem. It's just a coding structure in which allows you to take a long running for loop and change it into something that does some work, and keeps track where it left off, yielding to the browser, then continuing where it left off until we are done.

Figure 1, Add this Utility Class RepeatingOperation to your javascript file. You will not need to change this code:

RepeatingOperation = function(op, yieldEveryIteration) {

  //keeps count of how many times we have run heavytask() 
  //before we need to temporally check back with the browser.
  var count = 0;   

  this.step = function() {

    //Each time we run heavytask(), increment the count. When count
    //is bigger than the yieldEveryIteration limit, pass control back 
    //to browser and instruct the browser to immediately call op() so
    //we can pick up where we left off.  Repeat until we are done.
    if (++count >= yieldEveryIteration) {
      count = 0;

      //pass control back to the browser, and in 1 millisecond, 
      //have the browser call the op() function.  
      setTimeout(function() { op(); }, 1, [])

      //The following return statement halts this thread, it gives 
      //the browser a sigh of relief, your long-running javascript
      //loop has ended (even though technically we havn't yet).
      //The browser decides there is no need to alarm the user of
      //an unresponsive javascript process.
      return;
      }
    op();
  };
};

Figure 2, The following code represents your code that is causing the 'stop running this script' dialog because it takes so long to complete:

process10000HeavyTasks = function() {
  var len = 10000;  
  for (var i = len - 1; i >= 0; i--) {
    heavytask();   //heavytask() can be run about 20  times before
                   //an 'unresponsive script' dialog appears.
                   //If heavytask() is run more than 20 times in one
                   //javascript thread, the browser informs the user that
                   //an unresponsive script needs to be dealt with.  

                   //This is where we need to terminate this long running
                   //thread, instruct the browser not to panic on an unresponsive
                   //script, and tell it to call us right back to pick up
                   //where we left off.
  }
}

Figure 3. The following code is the fix for the problematic code in Figure 2. Notice the for loop is replaced with a recursive closure which passes control back to the browser every 10 iterations of heavytask()

process10000HeavyTasks = function() {

  var global_i = 10000; //initialize your 'for loop stepper' (i) here.

  var repeater = new this.RepeatingOperation(function() {

    heavytask();

    if (--global_i >= 0){     //Your for loop conditional goes here.
      repeater.step();        //while we still have items to process,
                              //run the next iteration of the loop.
    }
    else {
       alert("we are done");  //when this line runs, the for loop is complete.
    }
  }, 10);                   //10 means process 10 heavytask(), then
                            //yield back to the browser, and have the
                            //browser call us right back.

  repeater.step();          //this command kicks off the recursive closure.

};

Adapted from this source:

http://www.picnet.com.au/blogs/Guido/post/2010/03/04/How-to-prevent-Stop-running-this-script-message-in-browsers

matplotlib colorbar for scatter

If you're looking to scatter by two variables and color by the third, Altair can be a great choice.

Creating the dataset

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame(40*np.random.randn(10, 3), columns=['A', 'B','C'])

Altair plot

from altair import *
Chart(df).mark_circle().encode(x='A',y='B', color='C').configure_cell(width=200, height=150)

Plot

enter image description here

SQL - using alias in Group By

Caution that using alias in the Group By (for services that support it, such as postgres) can have unintended results. For example, if you create an alias that already exists in the inner statement, the Group By will chose the inner field name.

-- Working example in postgres
select col1 as col1_1, avg(col3) as col2_1
from
    (select gender as col1, maritalstatus as col2, 
    yearlyincome as col3 from customer) as layer_1
group by col1_1;

-- Failing example in postgres
select col2 as col1, avg(col3)
from
    (select gender as col1, maritalstatus as col2,
    yearlyincome as col3 from customer) as layer_1
group by col1;

There is no tracking information for the current branch

I run into this exact message often because I create a local branches via git checkout -b <feature-branch-name> without first creating the remote branch.

After all the work was finished and committed locally the fix was git push -u which created the remote branch, pushed all my work, and then the merge-request URL.

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

What worked for me:

  1. Add a folder to the project call it ThirdParty.
  2. Add in the ThirdParty folder both DocumentFormat.OpenXML.dll and WindowsBase.dll
  3. Make sure the the project uses the ThirdParty dir as reference for both the DLLs
  4. Build and published to an external server.

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

Here is snippet that allowed me to log out programmatically from facebook. Let me know if you see anything that I might need to improve.

private void logout(){
    // clear any user information
    mApp.clearUserPrefs();
    // find the active session which can only be facebook in my app
    Session session = Session.getActiveSession();
    // run the closeAndClearTokenInformation which does the following
    // DOCS : Closes the local in-memory Session object and clears any persistent 
    // cache related to the Session.
    session.closeAndClearTokenInformation();
    // return the user to the login screen
    startActivity(new Intent(getApplicationContext(), LoginActivity.class));
    // make sure the user can not access the page after he/she is logged out
    // clear the activity stack
    finish();
}

Firefox and SSL: sec_error_unknown_issuer

Just had the same problem with a Comodo Wildcard SSL cert. After reading the docs the solution is to ensure you include the certificate chain file they send you in your config i.e.

SSLCertificateChainFile /etc/ssl/crt/yourSERVERNAME.ca-bundle

Full details on Comodo site

How do I set path while saving a cookie value in JavaScript?

document.cookie = "cookiename=Some Name; path=/";

This will do

How do I install Python OpenCV through Conda?

On Linux, as discussed here, the best way to get opencv at present is from loopbio at conda-forge:

conda install -c loopbio -c conda-forge -c pkgw-forge ffmpeg-feature ffmpeg gtk2 opencv

If you have 'a modern CPU' there exists also a compiled version "enabling all modern CPU instruction set extensions [...] and against libjpeg-turbo":

conda install -c loopbio -c conda-forge -c pkgw-forge ffmpeg-feature ffmpeg gtk2 opencv-turbo`

Two of the solutions mentioned in other answers don't work unconditionally:

  • The conda you get through conda install opencv or pip install opencv-python doesn't have gtk2 support, so you can't display images through imshow.
  • Conda built by Menpo (conda install -c menpo opencv3) has gtk2 support, but
    • they have only built OpenCV 3.2 for Python 3.5, not Python 3.6
    • Ubuntu 16.10 has deprecated libpng12, leading to a missing dependency and the following error when trying to import cv2: ImportError: libpng12.so.0: cannot open shared object file: No such file or directory, as discussed here

EDIT: @Yamaneko points out that as of 14 June 2017, "there is an issue with loopbio's OpenCV version 3.2.0. It silently fails to read and write videos. It is due to a combination of an upstream OpenCV issue in combination with an old GCC. More details here. There is a PR on its way to solve the issue."

Making the main scrollbar always visible

body { 
    min-height: 101vh; 
} 

works the best for me

How to change colour of blue highlight on select box dropdown

I believe you are looking for the outline CSS property (in conjunction with active and hover psuedo attributes):

/* turn it off completely */
select:active, select:hover {
  outline: none
}

/* make it red instead (with with same width and style) */
select:active, select:hover {
  outline-color: red
}

Full details of outline, outline-color, outline-style, and outline-width https://developer.mozilla.org/en-US/docs/Web/CSS/outline

Calling a function from a string in C#

Yes. You can use reflection. Something like this:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

iOS Detection of Screenshot?

Swift 4 Examples

Example #1 using closure

NotificationCenter.default.addObserver(forName: .UIApplicationUserDidTakeScreenshot, 
                                       object: nil, 
                                       queue: OperationQueue.main) { notification in
    print("\(notification) that a screenshot was taken!")
}

Example #2 with selector

NotificationCenter.default.addObserver(self, 
                                       selector: #selector(screenshotTaken), 
                                       name: .UIApplicationUserDidTakeScreenshot, 
                                       object: nil)

@objc func screenshotTaken() {
    print("Screenshot taken!")
}