Programs & Examples On #Javascript

JavaScript (not to be confused with Java) is a high-level, dynamic, multi-paradigm, weakly-typed language used for both client-side and server-side scripting. Its primary use is in rendering and allowing manipulation of web pages. Use this tag for questions regarding ECMAScript and its various dialects/implementations (excluding ActionScript and Google-Apps-Script).

Using 24 hour time in bootstrap timepicker

Use capitals letter for hours HH = 24 hour format an hh = 12 hour format

_x000D_
_x000D_
$('#fecha').datetimepicker({_x000D_
   format : 'DD/MM/YYYY HH:mm'_x000D_
});
_x000D_
_x000D_
_x000D_

How to edit a JavaScript alert box title?

No, you can't.

It's a security/anti-phishing feature.

How do I set the default value for an optional argument in Javascript?

If str is null, undefined or 0, this code will set it to "hai"

function(nodeBox, str) {
  str = str || "hai";
.
.
.

If you also need to pass 0, you can use:

function(nodeBox, str) {
  if (typeof str === "undefined" || str === null) { 
    str = "hai"; 
  }
.
.
.

How to create a jQuery function (a new jQuery method or plugin)?

From the Docs:

(function( $ ){
   $.fn.myfunction = function() {
      alert('hello world');
      return this;
   }; 
})( jQuery );

Then you do

$('#my_div').myfunction();

JavaScript: How do I print a message to the error console?

The WebKit Web Inspector also supports Firebug's console API (just a minor addition to Dan's answer).

Simplest code for array intersection in javascript

Building on Anon's excellent answer, this one returns the intersection of two or more arrays.

function arrayIntersect(arrayOfArrays)
{        
    var arrayCopy = arrayOfArrays.slice(),
        baseArray = arrayCopy.pop();

    return baseArray.filter(function(item) {
        return arrayCopy.every(function(itemList) {
            return itemList.indexOf(item) !== -1;
        });
    });
}

Moment Js UTC to Local Time

To convert UTC time to Local you have to use moment.local().

For more info see docs

Example:

var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');

console.log(date); // 2015-09-13 03:39:27

var stillUtc = moment.utc(date).toDate();
var local = moment(stillUtc).local().format('YYYY-MM-DD HH:mm:ss');

console.log(local); // 2015-09-13 09:39:27

Demo:

_x000D_
_x000D_
var date = moment.utc().format();_x000D_
console.log(date, "- now in UTC"); _x000D_
_x000D_
var local = moment.utc(date).local().format();_x000D_
console.log(local, "- UTC now to local"); 
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Get the _id of inserted document in Mongo database in NodeJS

As ktretyak said, to get inserted document's ID best way is to use insertedId property on result object. In my case result._id didn't work so I had to use following:

db.collection("collection-name")
  .insertOne(document)
  .then(result => {
    console.log(result.insertedId);
  })
  .catch(err => {
    // handle error
  });

It's the same thing if you use callbacks.

What's the best way to detect a 'touch screen' device using JavaScript?

It looks like Chrome 24 now support touch events, probably for Windows 8. So the code posted here no longer works. Instead of trying to detect if touch is supported by the browser, I'm now binding both touch and click events and making sure only one is called:

myCustomBind = function(controlName, callback) {

  $(controlName).bind('touchend click', function(e) {
    e.stopPropagation();
    e.preventDefault();

    callback.call();
  });
};

And then calling it:

myCustomBind('#mnuRealtime', function () { ... });

Hope this helps !

Angular 2 optional route parameter

It's recommended to use a query parameter when the information is optional.

Route Parameters or Query Parameters?

There is no hard-and-fast rule. In general,

prefer a route parameter when

  • the value is required.
  • the value is necessary to distinguish one route path from another.

prefer a query parameter when

  • the value is optional.
  • the value is complex and/or multi-variate.

from https://angular.io/guide/router#optional-route-parameters

You just need to take out the parameter from the route path.

@RouteConfig([
{
    path: '/user/',
    component: User,
    as: 'User'
}])

fetch gives an empty response body

I just ran into this. As mentioned in this answer, using mode: "no-cors" will give you an opaque response, which doesn't seem to return data in the body.

opaque: Response for “no-cors” request to cross-origin resource. Severely restricted.

In my case I was using Express. After I installed cors for Express and configured it and removed mode: "no-cors", I was returned a promise. The response data will be in the promise, e.g.

fetch('http://example.com/api/node', {
  // mode: 'no-cors',
  method: 'GET',
  headers: {
    Accept: 'application/json',
  },
},
).then(response => {
  if (response.ok) {
    response.json().then(json => {
      console.log(json);
    });
  }
});

How to find first element of array matching a boolean condition in JavaScript?

If you're using underscore.js you can use its find and indexOf functions to get exactly what you want:

var index = _.indexOf(your_array, _.find(your_array, function (d) {
    return d === true;
}));

Documentation:

How to get the first element of an array?

array.find(e => !!e);  // return the first element 

since "find" return the first element that matches the filter && !!e match any element.

Note This works only when the first element is not a "Falsy" : null, false, NaN, "", 0, undefined

Clear the value of bootstrap-datepicker

I came across this thread while trying to figure out why the dates weren't being cleared in IE7/IE8.
It has to do with the fact that IE8 and older require a second parameter for the Array.prototype.splice() method. Here's the original code in bootstrap.datepicker.js:

clear: function(){
    this.splice(0);
},

Adding the second parameter resolved my issue:

clear: function(){
    this.splice(0,this.length);
},

Is it possible to import modules from all files in a directory, using a wildcard?

I've used them a few times (in particular for building massive objects splitting the data over many files (e.g. AST nodes)), in order to build them I made a tiny script (which I've just added to npm so everyone else can use it).

Usage (currently you'll need to use babel to use the export file):

$ npm install -g folder-module
$ folder-module my-cool-module/

Generates a file containing:

export {default as foo} from "./module/foo.js"
export {default as default} from "./module/default.js"
export {default as bar} from "./module/bar.js"
...etc

Then you can just consume the file:

import * as myCoolModule from "my-cool-module.js"
myCoolModule.foo()

getElementById returns null?

It can be caused by:

  1. Invalid HTML syntax (some tag is not closed or similar error)
  2. Duplicate IDs - there are two HTML DOM elements with the same ID
  3. Maybe element you are trying to get by ID is created dynamically (loaded by ajax or created by script)?

Please, post your code.

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

how to display a javascript var in html body

Try This...

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script>_x000D_
    function myFunction() {_x000D_
      var number = "123";_x000D_
      document.getElementById("myText").innerHTML = number;_x000D_
    }_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body onload="myFunction()">_x000D_
_x000D_
  <h1>"The value for number is: " <span id="myText"></span></h1>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Moment.js - how do I get the number of years since a date, not rounded up?

I prefer this small method.

function getAgeFromBirthday(birthday) {
    if(birthday){
      var totalMonths = moment().diff(birthday, 'months');
      var years = parseInt(totalMonths / 12);
      var months = totalMonths % 12;
        if(months !== 0){
           return parseFloat(years + '.' + months);
         }
    return years;
      }
    return null;
}

Populate one dropdown based on selection in another

_x000D_
_x000D_
function configureDropDownLists(ddl1, ddl2) {_x000D_
  var colours = ['Black', 'White', 'Blue'];_x000D_
  var shapes = ['Square', 'Circle', 'Triangle'];_x000D_
  var names = ['John', 'David', 'Sarah'];_x000D_
_x000D_
  switch (ddl1.value) {_x000D_
    case 'Colours':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < colours.length; i++) {_x000D_
        createOption(ddl2, colours[i], colours[i]);_x000D_
      }_x000D_
      break;_x000D_
    case 'Shapes':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < shapes.length; i++) {_x000D_
        createOption(ddl2, shapes[i], shapes[i]);_x000D_
      }_x000D_
      break;_x000D_
    case 'Names':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < names.length; i++) {_x000D_
        createOption(ddl2, names[i], names[i]);_x000D_
      }_x000D_
      break;_x000D_
    default:_x000D_
      ddl2.options.length = 0;_x000D_
      break;_x000D_
  }_x000D_
_x000D_
}_x000D_
_x000D_
function createOption(ddl, text, value) {_x000D_
  var opt = document.createElement('option');_x000D_
  opt.value = value;_x000D_
  opt.text = text;_x000D_
  ddl.options.add(opt);_x000D_
}
_x000D_
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">_x000D_
  <option value=""></option>_x000D_
  <option value="Colours">Colours</option>_x000D_
  <option value="Shapes">Shapes</option>_x000D_
  <option value="Names">Names</option>_x000D_
</select>_x000D_
_x000D_
<select id="ddl2">_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to read a local text file?

After the introduction of fetch api in javascript, reading file contents could not be simpler.

reading a text file

fetch('file.txt')
  .then(response => response.text())
  .then(text => console.log(text))
  // outputs the content of the text file

reading a json file

fetch('file.json')
  .then(response => response.json())
  .then(jsonResponse => console.log(jsonResponse))     
   // outputs a javascript object from the parsed json

Update 30/07/2018 (disclaimer):

This technique works fine in Firefox, but it seems like Chrome's fetch implementation does not support file:/// URL scheme at the date of writing this update (tested in Chrome 68).

Update-2 (disclaimer):

This technique does not work with Firefox above version 68 (Jul 9, 2019) for the same (security) reason as Chrome: CORS request not HTTP. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp.

Get text of the selected option with jQuery

Close, you can use

$('#select_2 option:selected').html()

jQuery function to open link in new window

Button click event only.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script language="javascript" type="text/javascript">
            $(document).ready(function () {
                $("#btnext").click(function () {                    
                    window.open("HTMLPage.htm", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
                });
            });
</script>

Bootstrap modal z-index

Resolved this issue for vue, by adding to the options an id: 'alertBox' so now every modal container has its parent set to something like alertBox__id0whatver which can easily be changed with css:

div[id*="alertBox"] { background: red; }

(meaning if id name contains ( *= ) 'alertBox' it will be applied.

How can I parse a CSV string with JavaScript, which contains comma in data?

Disclaimer

2014-12-01 Update: The answer below works only for one very specific format of CSV. As correctly pointed out by DG in the comments, this solution does not fit the RFC 4180 definition of CSV and it also does not fit Microsoft Excel format. This solution simply demonstrates how one can parse one (non-standard) CSV line of input which contains a mix of string types, where the strings may contain escaped quotes and commas.

A non-standard CSV solution

As austincheney correctly points out, you really need to parse the string from start to finish if you wish to properly handle quoted strings that may contain escaped characters. Also, the OP does not clearly define what a "CSV string" really is. First we must define what constitutes a valid CSV string and its individual values.

Given: "CSV String" Definition

For the purpose of this discussion, a "CSV string" consists of zero or more values, where multiple values are separated by a comma. Each value may consist of:

  1. A double quoted string (may contain unescaped single quotes).
  2. A single quoted string (may contain unescaped double quotes).
  3. A non-quoted string (may not contain quotes, commas or backslashes).
  4. An empty value. (An all whitespace value is considered empty.)

Rules/Notes:

  • Quoted values may contain commas.
  • Quoted values may contain escaped-anything, e.g. 'that\'s cool'.
  • Values containing quotes, commas, or backslashes must be quoted.
  • Values containing leading or trailing whitespace must be quoted.
  • The backslash is removed from all: \' in single quoted values.
  • The backslash is removed from all: \" in double quoted values.
  • Non-quoted strings are trimmed of any leading and trailing spaces.
  • The comma separator may have adjacent whitespace (which is ignored).

Find:

A JavaScript function which converts a valid CSV string (as defined above) into an array of string values.

Solution:

The regular expressions used by this solution are complex. And (IMHO) all non-trivial regular expressions should be presented in free-spacing mode with lots of comments and indentation. Unfortunately, JavaScript does not allow free-spacing mode. Thus, the regular expressions implemented by this solution are first presented in native regular expressions syntax (expressed using Python's handy r'''...''' raw-multi-line-string syntax).

First here is a regular expression which validates that a CVS string meets the above requirements:

Regular expression to validate a "CSV string":

re_valid = r"""
# Validate a CSV string having single, double or un-quoted values.
^                                   # Anchor to start of string.
\s*                                 # Allow whitespace before value.
(?:                                 # Group for value alternatives.
  '[^'\\]*(?:\\[\S\s][^'\\]*)*'     # Either Single quoted string,
| "[^"\\]*(?:\\[\S\s][^"\\]*)*"     # or Double quoted string,
| [^,'"\s\\]*(?:\s+[^,'"\s\\]+)*    # or Non-comma, non-quote stuff.
)                                   # End group of value alternatives.
\s*                                 # Allow whitespace after value.
(?:                                 # Zero or more additional values
  ,                                 # Values separated by a comma.
  \s*                               # Allow whitespace before value.
  (?:                               # Group for value alternatives.
    '[^'\\]*(?:\\[\S\s][^'\\]*)*'   # Either Single quoted string,
  | "[^"\\]*(?:\\[\S\s][^"\\]*)*"   # or Double quoted string,
  | [^,'"\s\\]*(?:\s+[^,'"\s\\]+)*  # or Non-comma, non-quote stuff.
  )                                 # End group of value alternatives.
  \s*                               # Allow whitespace after value.
)*                                  # Zero or more additional values
$                                   # Anchor to end of string.
"""

If a string matches the above regular expression, then that string is a valid CSV string (according to the rules previously stated) and may be parsed using the following regular expression. The following regular expression is then used to match one value from the CSV string. It is applied repeatedly until no more matches are found (and all values have been parsed).

Regular expression to parse one value from a valid CSV string:

re_value = r"""
# Match one value in valid CSV string.
(?!\s*$)                            # Don't match empty last value.
\s*                                 # Strip whitespace before value.
(?:                                 # Group for value alternatives.
  '([^'\\]*(?:\\[\S\s][^'\\]*)*)'   # Either $1: Single quoted string,
| "([^"\\]*(?:\\[\S\s][^"\\]*)*)"   # or $2: Double quoted string,
| ([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)  # or $3: Non-comma, non-quote stuff.
)                                   # End group of value alternatives.
\s*                                 # Strip whitespace after value.
(?:,|$)                             # Field ends on comma or EOS.
"""

Note that there is one special case value that this regular expression does not match - the very last value when that value is empty. This special "empty last value" case is tested for and handled by the JavaScript function which follows.

JavaScript function to parse CSV string:

// Return array of string values, or NULL if CSV string not well formed.
function CSVtoArray(text) {
    var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/;
    var re_value = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;

    // Return NULL if input string is not well formed CSV string.
    if (!re_valid.test(text)) return null;

    var a = []; // Initialize array to receive values.
    text.replace(re_value, // "Walk" the string using replace with callback.
        function(m0, m1, m2, m3) {

            // Remove backslash from \' in single quoted values.
            if (m1 !== undefined) a.push(m1.replace(/\\'/g, "'"));

            // Remove backslash from \" in double quoted values.
            else if (m2 !== undefined) a.push(m2.replace(/\\"/g, '"'));
            else if (m3 !== undefined) a.push(m3);
            return ''; // Return empty string.
        });

    // Handle special case of empty last value.
    if (/,\s*$/.test(text)) a.push('');
    return a;
};

Example input and output:

In the following examples, curly braces are used to delimit the {result strings}. (This is to help visualize leading/trailing spaces and zero-length strings.)

// Test 1: Test string from original question.
var test = "'string, duppi, du', 23, lala";
var a = CSVtoArray(test);
/* Array has three elements:
    a[0] = {string, duppi, du}
    a[1] = {23}
    a[2] = {lala} */
// Test 2: Empty CSV string.
var test = "";
var a = CSVtoArray(test);
/* Array has zero elements: */
// Test 3: CSV string with two empty values.
var test = ",";
var a = CSVtoArray(test);
/* Array has two elements:
    a[0] = {}
    a[1] = {} */
// Test 4: Double quoted CSV string having single quoted values.
var test = "'one','two with escaped \' single quote', 'three, with, commas'";
var a = CSVtoArray(test);
/* Array has three elements:
    a[0] = {one}
    a[1] = {two with escaped ' single quote}
    a[2] = {three, with, commas} */
// Test 5: Single quoted CSV string having double quoted values.
var test = '"one","two with escaped \" double quote", "three, with, commas"';
var a = CSVtoArray(test);
/* Array has three elements:
    a[0] = {one}
    a[1] = {two with escaped " double quote}
    a[2] = {three, with, commas} */
// Test 6: CSV string with whitespace in and around empty and non-empty values.
var test = "   one  ,  'two'  ,  , ' four' ,, 'six ', ' seven ' ,  ";
var a = CSVtoArray(test);
/* Array has eight elements:
    a[0] = {one}
    a[1] = {two}
    a[2] = {}
    a[3] = { four}
    a[4] = {}
    a[5] = {six }
    a[6] = { seven }
    a[7] = {} */

Additional notes:

This solution requires that the CSV string be "valid". For example, unquoted values may not contain backslashes or quotes, e.g. the following CSV string is not valid:

var invalid1 = "one, that's me!, escaped \, comma"

This is not really a limitation because any sub-string may be represented as either a single or double quoted value. Note also that this solution represents only one possible definition for "comma-separated values".

Edit history

  • 2014-05-19: Added disclaimer.
  • 2014-12-01: Moved disclaimer to top.

Adding close button in div to close the box

Updated your fiddle: http://jsfiddle.net/xftr5/11/ Hope, everything is clear?

$(document).ready(function() {
    $('.fragment i').on('click', function(e) { $(e.target).closest('a').remove(); });
});

Added jQuery and inserted an <i> as close trigger...

AngularJS : automatically detect change in model

And if you need to style your form elements according to it's state (modified/not modified) dynamically or to test whether some values has actually changed, you can use the following module, developed by myself: https://github.com/betsol/angular-input-modified

It adds additional properties and methods to the form and it's child elements. With it, you can test whether some element contains new data or even test if entire form has new unsaved data.

You can setup the following watch: $scope.$watch('myForm.modified', handler) and your handler will be called if some form elements actually contains new data or if it reversed to initial state.

Also, you can use modified property of individual form elements to actually reduce amount of data sent to a server via AJAX call. There is no need to send unchanged data.

As a bonus, you can revert your form to initial state via call to form's reset() method.

You can find the module's demo here: http://plnkr.co/edit/g2MDXv81OOBuGo6ORvdt?p=preview

Cheers!

Expected corresponding JSX closing tag for input Reactjs

You need to close the input element with /> at the end. In React, we have to close every element. Your code should be:

<input id="icon_prefix" type="text" class="validate/">

How to redirect to another page in node.js

In another way you can use window.location.href="your URL"

e.g.:

res.send('<script>window.location.href="your URL";</script>');

or:

return res.redirect("your url");

How to read response headers in angularjs?

According the MDN custom headers are not exposed by default. The server admin need to expose them using "Access-Control-Expose-Headers" in the same fashion they deal with "access-control-allow-origin"

See this MDN link for confirmation [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers]

How can I trigger a JavaScript event click

Use a testing framework

This might be helpful - http://seleniumhq.org/ - Selenium is a web application automated testing system.

You can create tests using the Firefox plugin Selenium IDE

Manual firing of events

To manually fire events the correct way you will need to use different methods for different browsers - either el.dispatchEvent or el.fireEvent where el will be your Anchor element. I believe both of these will require constructing an Event object to pass in.

The alternative, not entirely correct, quick-and-dirty way would be this:

var el = document.getElementById('anchorelementid');
el.onclick(); // Not entirely correct because your event handler will be called
              // without an Event object parameter.

internal/modules/cjs/loader.js:582 throw err

try following command

remove node_modules and package-lock.json

rm -rf node_modules package-lock.json

then run following command to install dependencies

npm install

finally, run your package by following command.

npm start

How to get height of entire document with JavaScript?

For anyone having trouble scrolling a page on demand, using feature detection, I've come up with this hack to detect which feature to use in an animated scroll.

The issue was both document.body.scrollTop and document.documentElement always returned true in all browsers.

However you can only actually scroll a document with either one or the other. d.body.scrollTop for Safari and document.documentElement for all others according to w3schools (see examples)

element.scrollTop works in all browsers, not so for document level.

    // get and test orig scroll pos in Saf and similar 
    var ORG = d.body.scrollTop; 

    // increment by 1 pixel
    d.body.scrollTop += 1;

    // get new scroll pos in Saf and similar 
    var NEW = d.body.scrollTop;

    if(ORG == NEW){
        // no change, try scroll up instead
        ORG = d.body.scrollTop;
        d.body.scrollTop -= 1;
        NEW = d.body.scrollTop;

        if(ORG == NEW){
            // still no change, use document.documentElement
            cont = dd;
        } else {
            // we measured movement, use document.body
            cont = d.body;
        }
    } else {
        // we measured movement, use document.body
        cont = d.body;
    }

Javascript loading CSV file into an array

You can't use AJAX to fetch files from the user machine. This is absolutely the wrong way to go about it.

Use the FileReader API:

<input type="file" id="file input">

js:

console.log(document.getElementById("file input").files); // list of File objects

var file = document.getElementById("file input").files[0];
var reader = new FileReader();
content = reader.readAsText(file);
console.log(content);

Then parse content as CSV. Keep in mind that your parser currently does not deal with escaped values in CSV like: value1,value2,"value 3","value ""4"""

return value after a promise

The best way to do this would be to use the promise returning function as it is, like this

lookupValue(file).then(function(res) {
    // Write the code which depends on the `res.val`, here
});

The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.

So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.

How to create a responsive image that also scales up in Bootstrap 3

Bootstrap's responsive image class sets max-width to 100%. This limits its size, but does not force it to stretch to fill parent elements larger than the image itself. You'd have to use the width attribute to force upscaling.

http://getbootstrap.com/css/#images-responsive

Is there any way to wait for AJAX response and halt execution?

The simple answer is to turn off async. But that's the wrong thing to do. The correct answer is to re-think how you write the rest of your code.

Instead of writing this:

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: function(data) {
            return data;
        }
    });
}

function foo () {
    var response = functABC();
    some_result = bar(response);
    // and other stuff and
    return some_result;
}

You should write it like this:

function functABC(callback){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: callback
    });
}

function foo (callback) {
    functABC(function(data){
        var response = data;
        some_result = bar(response);
        // and other stuff and
        callback(some_result);
    })
}

That is, instead of returning result, pass in code of what needs to be done as callbacks. As I've shown, callbacks can be nested to as many levels as you have function calls.


A quick explanation of why I say it's wrong to turn off async:

Turning off async will freeze the browser while waiting for the ajax call. The user cannot click on anything, cannot scroll and in the worst case, if the user is low on memory, sometimes when the user drags the window off the screen and drags it in again he will see empty spaces because the browser is frozen and cannot redraw. For single threaded browsers like IE7 it's even worse: all websites freeze! Users who experience this may think you site is buggy. If you really don't want to do it asynchronously then just do your processing in the back end and refresh the whole page. It would at least feel not buggy.

Trim specific character from a string

_x000D_
_x000D_
const special = ':;"<>?/!`~@#$%^&*()+=-_ '.split("");
const trim = (input) => {
    const inTrim = (str) => {
        const spStr = str.split("");
        let deleteTill = 0;
        let startChar = spStr[deleteTill];
        while (special.some((s) => s === startChar)) {
            deleteTill++;
            if (deleteTill <= spStr.length) {
                startChar = spStr[deleteTill];
            } else {
                deleteTill--;
                break;
            }
        }
        spStr.splice(0, deleteTill);
        return spStr.join("");
    };
input = inTrim(input);
input = inTrim(input.split("").reverse().join("")).split("").reverse().join("");
return input;
};
alert(trim('@#This is what I use$%'));
_x000D_
_x000D_
_x000D_

window.open with target "_blank" in Chrome

You can't do it because you can't have control on the manner Chrome opens its windows

Adding div element to body or document in JavaScript

The modern way is to use ParentNode.append(), like so:

_x000D_
_x000D_
let element = document.createElement('div');_x000D_
element.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';_x000D_
document.body.append(element);
_x000D_
_x000D_
_x000D_

jQuery / Javascript code check, if not undefined

I like this:

if (wlocation !== undefined)

But if you prefer the second way wouldn't be as you posted. It would be:

if (typeof wlocation  !== "undefined")

Converting JavaScript object with numeric keys into array

It's actually very straight forward with jQuery's $.map

var arr = $.map(obj, function(el) { return el });

FIDDLE

and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map

var arr = Object.keys(obj).map(function(k) { return obj[k] });

FIDDLE

That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is a string format, in that case a run through JSON.parse would be necessary as well.

In ES2015 there's Object.values to the rescue, which makes this a breeze

var arr = Object.values(obj);

How do you clear the focus in javascript?

You can call window.focus();

but moving or losing the focus is bound to interfere with anyone using the tab key to get around the page.

you could listen for keycode 13, and forego the effect if the tab key is pressed.

Twitter bootstrap collapse: change display of toggle button

You do like this. the function return the old text.

$('button').click(function(){ 
        $(this).text(function(i,old){
            return old=='Read More' ?  'Read Less' : 'Read More';
        });
    });

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

I was creating a mp3 player for android, I wanted to update the current time every 500ms so I did it like this

setInterval

private void update() {
    new android.os.Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            long cur = player.getCurrentPosition();
            long dur = player.getDuration();
            currentTime = millisecondsToTime(cur);
            currentTimeView.setText(currentTime);
            if (cur < dur) {
                updatePlayer();
            }

            // update seekbar
            seekBar.setProgress( (int) Math.round((float)cur / (float)dur * 100f));
        }
    }, 500);
}

which calls the same method recursively

How to scroll to specific item using jQuery?

I agree with Kevin and others, using a plugin for this is pointless.

window.scrollTo(0, $("#element").offset().top);

How to get array keys in Javascript?

Seems to work.

var widthRange = new Array();
widthRange[46] = { sel:46, min:0,  max:52 };
widthRange[66] = { sel:66, min:52, max:70 };
widthRange[90] = { sel:90, min:70, max:94 };

for (var key in widthRange)
{
    document.write(widthRange[key].sel + "<br />");
    document.write(widthRange[key].min + "<br />");
    document.write(widthRange[key].max + "<br />");
}

Mongoose and multiple database in single node.js project

A bit optimized(for me atleast) solution. write this to a file db.js and require this to wherever required and call it with a function call and you are good to go.

   const MongoClient = require('mongodb').MongoClient;
    async function getConnections(url,db){
        return new Promise((resolve,reject)=>{
            MongoClient.connect(url, { useUnifiedTopology: true },function(err, client) {
                if(err) { console.error(err) 
                    resolve(false);
                }
                else{
                    resolve(client.db(db));
                }
            })
        });
    }

    module.exports = async function(){
        let dbs      = [];
        dbs['db1']     = await getConnections('mongodb://localhost:27017/','db1');
        dbs['db2']     = await getConnections('mongodb://localhost:27017/','db2');
        return dbs;
    };

Best way to store a key=>value array in JavaScript?

If I understood you correctly:

var hash = {};
hash['bob'] = 123;
hash['joe'] = 456;

var sum = 0;
for (var name in hash) {
    sum += hash[name];
}
alert(sum); // 579

How to call multiple functions with @click in vue?

On Vue 2.3 and above you can do this:

<div v-on:click="firstFunction(); secondFunction();"></div>
// or
<div @click="firstFunction(); secondFunction();"></div>

how to use html2canvas and jspdf to export to pdf in a proper and simple way

I have made a jsfiddle for you.

 <canvas id="canvas" width="480" height="320"></canvas> 
      <button id="download">Download Pdf</button>

'

        html2canvas($("#canvas"), {
            onrendered: function(canvas) {         
                var imgData = canvas.toDataURL(
                    'image/png');              
                var doc = new jsPDF('p', 'mm');
                doc.addImage(imgData, 'PNG', 10, 10);
                doc.save('sample-file.pdf');
            }
        });

jsfiddle: http://jsfiddle.net/rpaul/p4s5k59s/5/

Tested in Chrome38, IE11 and Firefox 33. Seems to have issues with Safari. However, Andrew got it working in Safari 8 on Mac OSx by switching to JPEG from PNG. For details, see his comment below.

Can a for loop increment/decrement by more than one?

Use the += assignment operator:

for (var i = 0; i < myVar.length; i += 3) {

Technically, you can place any expression you'd like in the final expression of the for loop, but it is typically used to update the counter variable.

For more information about each step of the for loop, check out the MDN article.

JavaScript for detecting browser language preference

I've been using Hamid's answer for a while, but it in cases where the languages array is like ["en", "en-GB", "en-US", "fr-FR", "fr", "en-ZA"] it will return "en", when "en-GB" would be a better match.

My update (below) will return the first long format code e.g. "en-GB", otherwise it will return the first short code e.g. "en", otherwise it will return null.

_x000D_
_x000D_
function getFirstBrowserLanguage() {_x000D_
        var nav = window.navigator,_x000D_
            browserLanguagePropertyKeys = ['language', 'browserLanguage', 'systemLanguage', 'userLanguage'],_x000D_
            i,_x000D_
            language,_x000D_
            len,_x000D_
            shortLanguage = null;_x000D_
_x000D_
        // support for HTML 5.1 "navigator.languages"_x000D_
        if (Array.isArray(nav.languages)) {_x000D_
            for (i = 0; i < nav.languages.length; i++) {_x000D_
                language = nav.languages[i];_x000D_
                len = language.length;_x000D_
                if (!shortLanguage && len) {_x000D_
                    shortLanguage = language;_x000D_
                }_x000D_
                if (language && len>2) {_x000D_
                    return language;_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
_x000D_
        // support for other well known properties in browsers_x000D_
        for (i = 0; i < browserLanguagePropertyKeys.length; i++) {_x000D_
            language = nav[browserLanguagePropertyKeys[i]];_x000D_
            //skip this loop iteration if property is null/undefined.  IE11 fix._x000D_
            if (language == null) { continue; } _x000D_
            len = language.length;_x000D_
            if (!shortLanguage && len) {_x000D_
                shortLanguage = language;_x000D_
            }_x000D_
            if (language && len > 2) {_x000D_
                return language;_x000D_
            }_x000D_
        }_x000D_
_x000D_
        return shortLanguage;_x000D_
    }_x000D_
_x000D_
console.log(getFirstBrowserLanguage());
_x000D_
_x000D_
_x000D_

Update: IE11 was erroring when some properties were undefined. Added a check to skip those properties.

How to import js-modules into TypeScript file?

You can import the whole module as follows:

import * as FriendCard from './../pages/FriendCard';

For more details please refer the modules section of Typescript official docs.

Extract time from moment js object

You can do something like this

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

How to change the playing speed of videos in HTML5?

According to this site, this is supported in the playbackRate and defaultPlaybackRate attributes, accessible via the DOM. Example:

/* play video twice as fast */
document.querySelector('video').defaultPlaybackRate = 2.0;
document.querySelector('video').play();

/* now play three times as fast just for the heck of it */
document.querySelector('video').playbackRate = 3.0;

The above works on Chrome 43+, Firefox 20+, IE 9+, Edge 12+.

Create an empty object in JavaScript with {} or new Object()?

Yes, There is a difference, they're not the same. It's true that you'll get the same results but the engine works in a different way for both of them. One of them is an object literal, and the other one is a constructor, two different ways of creating an object in javascript.

var objectA = {} //This is an object literal

var objectB = new Object() //This is the object constructor

In JS everything is an object, but you should be aware about the following thing with new Object(): It can receive a parameter, and depending on that parameter, it will create a string, a number, or just an empty object.

For example: new Object(1), will return a Number. new Object("hello") will return a string, it means that the object constructor can delegate -depending on the parameter- the object creation to other constructors like string, number, etc... It's highly important to keep this in mind when you're managing dynamic data to create objects..

Many authors recommend not to use the object constructor when you can use a certain literal notation instead, where you will be sure that what you're creating is what you're expecting to have in your code.

I suggest you to do a further reading on the differences between literal notation and constructors on javascript to find more details.

Regex to check whether a string contains only numbers

var reg = /^\d+$/;

should do it. The original matches anything that consists of exactly one digit.

Bootstrap 4 File Input

Here is the answer with blue box-shadow,border,outline removed with file name fix in custom-file input of bootstrap appear on choose filename and if you not choose any file then show No file chosen.

_x000D_
_x000D_
    $(document).on('change', 'input[type="file"]', function (event) { _x000D_
        var filename = $(this).val();_x000D_
        if (filename == undefined || filename == ""){_x000D_
        $(this).next('.custom-file-label').html('No file chosen');_x000D_
        }_x000D_
        else _x000D_
        { $(this).next('.custom-file-label').html(event.target.files[0].name); }_x000D_
    });
_x000D_
    input[type=file]:focus,.custom-file-input:focus~.custom-file-label {_x000D_
        outline:none!important;_x000D_
        border-color: transparent;_x000D_
        box-shadow: none!important;_x000D_
    }_x000D_
    .custom-file,_x000D_
    .custom-file-label,_x000D_
    .custom-file-input {_x000D_
        cursor: pointer;_x000D_
    }
_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
    <div class="container py-5">_x000D_
    <div class="input-group mb-3">_x000D_
      <div class="input-group-prepend">_x000D_
        <span class="input-group-text">Upload</span>_x000D_
      </div>_x000D_
      <div class="custom-file">_x000D_
        <input type="file" class="custom-file-input" id="inputGroupFile01">_x000D_
        <label class="custom-file-label" for="inputGroupFile01">Choose file</label>_x000D_
      </div>_x000D_
    </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Allow Google Chrome to use XMLHttpRequest to load a URL from a local file

startup chrome with --disable-web-security

On Windows:

chrome.exe --disable-web-security

On Mac:

open /Applications/Google\ Chrome.app/ --args --disable-web-security

This will allow for cross-domain requests.
I'm not aware of if this also works for local files, but let us know !

And mention, this does exactly what you expect, it disables the web security, so be careful with it.

Javascript Uncaught Reference error Function is not defined

Change the wrapping from "onload" to "No wrap - in <body>"

The function defined has a different scope.

How to measure time elapsed on Javascript?

The Date documentation states that :

The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC

Click on start button then on end button. It will show you the number of seconds between the 2 clicks.

The milliseconds diff is in variable timeDiff. Play with it to find seconds/minutes/hours/ or what you need

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = new Date();_x000D_
  var timeDiff = endTime - startTime; //in ms_x000D_
  // strip the ms_x000D_
  timeDiff /= 1000;_x000D_
_x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

OR another way of doing it for modern browser

Using performance.now() which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.

The time origin is a standard time which is considered to be the beginning of the current document's lifetime.

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = performance.now();_x000D_
  var timeDiff = endTime - startTime; //in ms _x000D_
  // strip the ms _x000D_
  timeDiff /= 1000; _x000D_
  _x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

Getting DOM element value using pure JavaScript

There is no difference if we look on effect - value will be the same. However there is something more...

Solution 3:

_x000D_
_x000D_
function doSomething() {_x000D_
  console.log( theId.value );_x000D_
}
_x000D_
<input id="theId" value="test" onclick="doSomething()" />
_x000D_
_x000D_
_x000D_

if DOM element has id then you can use it in js directly

Creating Accordion Table with Bootstrap

In the accepted answer you get annoying spacing between the visible rows when the expandable row is hidden. You can get rid of that by adding this to css:

.collapse-row.collapsed + tr {
     display: none;
}

'+' is adjacent sibling selector, so if you want your expandable row to be the next row, this selects the next tr following tr named collapse-row.

Here is updated fiddle: http://jsfiddle.net/Nb7wy/2372/

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations

Then you can do things like:

var day = moment("12-25-1995", "MM-DD-YYYY");

or

var day = moment("25/12/1995", "DD/MM/YYYY");

then operate on the date

day.add('days', 7)

and to get the native javascript date

day.toDate();

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

$ is a function provided by the jQuery library, it won't be available unless you have loaded the jQuery library.

You need to add jQuery (typically with a <script> element which can point at a local copy of the library or one hosted on a CDN). Make sure you are using a current and supported version: Many answers on this question recommend using 1.x or 2.x versions of jQuery which are no longer supported and have known security issues.

<script src="/path/to/jquery.js"></script>

Make sure you load jQuery before you run any script which depends on it.

The jQuery homepage will have a link to download the current version of the library (at the time of writing it is 3.5.1 but that may change by the time you read this).

Further down the page you will find a section on using jQuery with a CDN which links to a number of places that will host the library for you.


(NB: Some other libraries provide a $ function, and browsers have native $ variables which are only available in the Developer Tools Console, but this question isn't about those).

Add a tooltip to a div

Here's a nice jQuery Tooltip:

https://jqueryui.com/tooltip/

To implement this, just follow these steps:

  1. Add this code in your <head></head> tags:

    <script type="text/javascript" src="http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js"></script>    
    <script type="text/javascript">
    $("[title]").tooltip();
    </script> 
    <style type="text/css"> 
    
    /* tooltip styling. by default the element to be styled is .tooltip  */
    .tooltip {
        display:none;
        background:transparent url(https://dl.dropboxusercontent.com/u/25819920/tooltip/black_arrow.png);
        font-size:12px;
        height:70px;
        width:160px;
        padding:25px;
        color:#fff;
    }
    </style> 
    
  2. On the HTML elements that you want to have the tooltip, just add a title attribute to it. Whatever text is in the title attribute will be in the tooltip.

Note: When JavaScript is disabled, it will fallback to the default browser/operating system tooltip.

how to remove css property using javascript?

You have two options:

OPTION 1:

You can use removeProperty method. It will remove a style from an element.

el.style.removeProperty('zoom');

OPTION 2:

You can set it to the default value:

el.style.zoom = "";

The effective zoom will now be whatever follows from the definitions set in the stylesheets (through link and style tags). So this syntax will only modify the local style of this element.

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

I was trying to save a JSON object from a XHR request into a HTML5 data-* attribute. I tried many of above solutions with no success.

What I finally end up doing was replacing the single quote ' with it code &#39; using a regex after the stringify() method call the following way:

var productToString = JSON.stringify(productObject);
var quoteReplaced = productToString.replace(/'/g, "&#39;");
var anchor = '<a data-product=\'' + quoteReplaced + '\' href=\'#\'>' + productObject.name + '</a>';
// Here you can use the "anchor" variable to update your DOM element.

How to get an HTML element's style values in javascript?

You can make function getStyles that'll take an element and other arguments are properties that's values you want.

const convertRestArgsIntoStylesArr = ([...args]) => {
    return args.slice(1);
}

const getStyles = function () {
    const args = [...arguments];
    const [element] = args;

    let stylesProps = [...args][1] instanceof Array ? args[1] : convertRestArgsIntoStylesArr(args);

    const styles = window.getComputedStyle(element);
    const stylesObj = stylesProps.reduce((acc, v) => {
        acc[v] = styles.getPropertyValue(v);
        return acc;
    }, {});

    return stylesObj;
};

Now, you can use this function like this:

const styles = getStyles(document.body, "height", "width");

OR

const styles = getStyles(document.body, ["height", "width"]);

Variable not accessible when initialized outside function

Declare systemStatus in an outer scope and assign it in an onload handler.

systemStatus = null;

function onloadHandler(evt) {
    systemStatus = document.getElementById("....");
}

Or if you don't want the onload handler, put your script tag at the bottom of your HTML.

Javascript geocoding from address to latitude and longitude numbers not working

Try using this instead:

var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();

It's bit hard to navigate Google's api but here is the relevant documentation.

One thing I had trouble finding was how to go in the other direction. From coordinates to an address. Here is the code I neded upp using. Please not that I also use jquery.

$.each(results[0].address_components, function(){
    $("#CreateDialog").find('input[name="'+ this.types+'"]').attr('value', this.long_name);
});

What I'm doing is to loop through all the returned address_components and test if their types match any input element names I have in a form. And if they do I set the value of the element to the address_components value.
If you're only interrested in the whole formated address then you can follow Google's example

SyntaxError: Cannot use import statement outside a module

simple just change it to : const uuidv1 = require('uuid'); it will work fine.

Origin null is not allowed by Access-Control-Allow-Origin

Adding a bit to use Gokhan's solution for using:

--allow-file-access-from-files

Now you just need to append above text in Target text followed by a space. make sure you close all the instances of chrome browser after adding above property. Now restart chrome by the icon where you added this property. It should work for all.

Move the mouse pointer to a specific position?

You can't move the mouse pointer using javascript, and thus for obvious security reasons. The best way to achieve this effect would be to actually place the control under the mouse pointer.

Test if something is not undefined in JavaScript

Actually you must surround it with an Try/Catch block so your code won't stop from working. Like this:

try{
    if(typeof response[0].title !== 'undefined') {
        doSomething();
    }
  }catch(e){
    console.log('responde[0].title is undefined'); 
  }

How to check if element is visible after scrolling?

I adapted this short jQuery function extension, which you can feel free to use (MIT licence).

/**
 * returns true if an element is visible, with decent performance
 * @param [scope] scope of the render-window instance; default: window
 * @returns {boolean}
 */
jQuery.fn.isOnScreen = function(scope){
    var element = this;
    if(!element){
        return;
    }
    var target = $(element);
    if(target.is(':visible') == false){
        return false;
    }
    scope = $(scope || window);
    var top = scope.scrollTop();
    var bot = top + scope.height();
    var elTop = target.offset().top;
    var elBot = elTop + target.height();

    return ((elBot <= bot) && (elTop >= top));
};

How to reject in async/await syntax?

You can create a wrapper function that takes in a promise and returns an array with data if no error and the error if there was an error.

function safePromise(promise) {
  return promise.then(data => [ data ]).catch(error => [ null, error ]);
}

Use it like this in ES7 and in an async function:

async function checkItem() {
  const [ item, error ] = await safePromise(getItem(id));
  if (error) { return null; } // handle error and return
  return item; // no error so safe to use item
}

Maximum size of an Array in Javascript

I have shamelessly pulled some pretty big datasets in memory, and altough it did get sluggish it took maybe 15 Mo of data upwards with pretty intense calculations on the dataset. I doubt you will run into problems with memory unless you have intense calculations on the data and many many rows. Profiling and benchmarking with different mock resultsets will be your best bet to evaluate performance.

Conditional logic in AngularJS template

You can use ng-show on every div element in the loop. Is this what you've wanted: http://jsfiddle.net/pGwRu/2/ ?

<div class="from" ng-show="message.from">From: {{message.from.name}}</div>

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.

Working with $scope.$emit and $scope.$on

You can call a service from your controller that returns a promise and then use it in your controller. And further use $emit or $broadcast to inform other controllers about it. In my case, I had to make http calls through my service, so I did something like this :

function ParentController($scope, testService) {
    testService.getList()
        .then(function(data) {
            $scope.list = testService.list;
        })
        .finally(function() {
            $scope.$emit('listFetched');
        })


    function ChildController($scope, testService) {
        $scope.$on('listFetched', function(event, data) {
            // use the data accordingly
        })
    }

and my service looks like this

    app.service('testService', ['$http', function($http) {

        this.list = [];

        this.getList = function() {
            return $http.get(someUrl)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        list = response.data.results;

                        return response.data;
                    } else {
                        // invalid response
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    // something went wrong
                    return $q.reject(response.data);
                });

        }

    }])

Executing <script> injected by innerHTML after AJAX call

My conclusion is HTML doesn't allows NESTED SCRIPT tags. If you are using javascript for injecting HTML code that include script tags inside is not going to work because the javascript goes in a script tag too. You can test it with the next code and you will be that it's not going to work. The use case is you are calling a service with AJAX or similar, you are getting HTML and you want to inject it in the HTML DOM straight forward. If the injected HTML code has inside SCRIPT tags is not going to work.

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"></head><body></body><script>document.getElementsByTagName("body")[0].innerHTML = "<script>console.log('hi there')</script>\n<div>hello world</div>\n"</script></html>

how to compare two string dates in javascript?

var d1 = Date.parse("2012-11-01");
var d2 = Date.parse("2012-11-04");
if (d1 < d2) {
    alert ("Error!");
}

Demo Jsfiddle

Node.js Generate html

Node.js does not run in a browser, therefore you will not have a document object available. Actually, you will not even have a DOM tree at all. If you are a bit confused at this point, I encourage you to read more about it before going further.

There are a few methods you can choose from to do what you want.


Method 1: Serving the file directly via HTTP

Because you wrote about opening the file in the browser, why don't you use a framework that will serve the file directly as an HTTP service, instead of having a two-step process? This way, your code will be more dynamic and easily maintainable (not mentioning your HTML always up-to-date).

There are plenty frameworks out there for that :

The most basic way you could do what you want is this :

var http = require('http');

http.createServer(function (req, res) {
  var html = buildHtml(req);

  res.writeHead(200, {
    'Content-Type': 'text/html',
    'Content-Length': html.length,
    'Expires': new Date().toUTCString()
  });
  res.end(html);
}).listen(8080);

function buildHtml(req) {
  var header = '';
  var body = '';

  // concatenate header string
  // concatenate body string

  return '<!DOCTYPE html>'
       + '<html><head>' + header + '</head><body>' + body + '</body></html>';
};

And access this HTML with http://localhost:8080 from your browser.

(Edit: you could also serve them with a small HTTP server.)


Method 2: Generating the file only

If what you are trying to do is simply generating some HTML files, then go simple. To perform IO access on the file system, Node has an API for that, documented here.

var fs = require('fs');

var fileName = 'path/to/file';
var stream = fs.createWriteStream(fileName);

stream.once('open', function(fd) {
  var html = buildHtml();

  stream.end(html);
});

Note: The buildHtml function is exactly the same as in Method 1.


Method 3: Dumping the file directly into stdout

This is the most basic Node.js implementation and requires the invoking application to handle the output itself. To output something in Node (ie. to stdout), the best way is to use console.log(message) where message is any string, or object, etc.

var html = buildHtml();

console.log(html);

Note: The buildHtml function is exactly the same as in Method 1 (again)

If your script is called html-generator.js (for example), in Linux/Unix based system, simply do

$ node html-generator.js > path/to/file

Conclusion

Because Node is a modular system, you can even put the buildHtml function inside it's own module and simply write adapters to handle the HTML however you like. Something like

var htmlBuilder = require('path/to/html-builder-module');

var html = htmlBuilder(options);
...

You have to think "server-side" and not "client-side" when writing JavaScript for Node.js; you are not in a browser and/or limited to a sandbox, other than the V8 engine.

Extra reading, learn about npm. Hope this helps.

How to make a JSON call to a url?

In modern-day JS, you can get your JSON data by calling ES6's fetch() on your URL and then using ES7's async/await to "unpack" the Response object from the fetch to get the JSON data like so:

_x000D_
_x000D_
const getJSON = async url => {
  try {
    const response = await fetch(url);
    if(!response.ok) // check if response worked (no 404 errors etc...)
      throw new Error(response.statusText);

    const data = await response.json(); // get JSON from the response
    return data; // returns a promise, which resolves to this data value
  } catch(error) {
    return error;
  }
}

console.log("Fetching data...");
getJSON("https://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json").then(data => {
  console.log(data);
}).catch(error => {
  console.error(error);
});
_x000D_
_x000D_
_x000D_

The above method can be simplified down to a few lines if you ignore the exception/error handling (usually not recommended as this can lead to unwanted errors):

_x000D_
_x000D_
const getJSON = async url => {
  const response = await fetch(url);
  return response.json(); // get JSON from the response 
}

console.log("Fetching data...");
getJSON("https://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json")
  .then(data => console.log(data));
_x000D_
_x000D_
_x000D_

When tracing out variables in the console, How to create a new line?

Why not just use separate console.log() for each var, and separate with a comma rather than converting them all to strings? That would give you separate lines, AND give you the true value of each variable rather than the string representation of each (assuming they may not all be strings).

console.log('roleName',roleName);
console.log('role_ID',role_ID);
console.log('modal_ID',modal_ID);
console.log('related',related);

And I think it would be easier to read/maintain.

Why is using onClick() in HTML a bad practice?

  • onclick events run in the global scope and may cause unexpected error.
  • Adding onclick events to many DOM elements will slow down the
    performance and efficiency.

How to get the day of week and the month of the year?

That's simple. You can set option to display only week days in toLocaleDateString() to get the names. For example:

(new Date()).toLocaleDateString('en-US',{ weekday: 'long'}) will return only the day of the week. And (new Date()).toLocaleDateString('en-US',{ month: 'long'}) will return only the month of the year.

Javascript find json value

Just use the ES6 find() function in a functional way:

_x000D_
_x000D_
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];

let country = data.find(el => el.code === "AL");
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
_x000D_
_x000D_
_x000D_

or Lodash _.find:

_x000D_
_x000D_
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];

let country = _.find(data, ["code", "AL"]);
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

How do I access an access array item by index in handlebars?

Please try this, if you want to fetch first/last.

{{#each list}}

    {{#if @first}}
        <div class="active">
    {{else}}
        <div>
    {{/if}}

{{/each}}


{{#each list}}

    {{#if @last}}
        <div class="last-element">
    {{else}}
        <div>
    {{/if}}

{{/each}}

How to scroll to top of the page in AngularJS?

use: $anchorScroll();

with $anchorScroll property

Handling Enter Key in Vue.js

In vue 2, You can catch enter event with v-on:keyup.enter check the documentation:

https://vuejs.org/v2/guide/events.html#Key-Modifiers

I leave a very simple example:

_x000D_
_x000D_
var vm = new Vue({_x000D_
  el: '#app',_x000D_
  data: {msg: ''},_x000D_
  methods: {_x000D_
    onEnter: function() {_x000D_
       this.msg = 'on enter event';_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdn.jsdelivr.net/npm/vue"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <input v-on:keyup.enter="onEnter" />_x000D_
  <h1>{{ msg }}</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Good luck

Check if input is number or letter javascript

You could use the isNaN Function. It returns true if the data is not a number. That would be something like that:

function checkInp()
{
    var x=document.forms["myForm"]["age"].value;
    if (isNaN(x)) // this is the code I need to change
    {
        alert("Must input numbers");
        return false;
    }
}

Note: isNan considers 10.2 as a valid number.

How to Automatically Close Alerts using Twitter Bootstrap

With delay and fade :

setTimeout(function(){
    $(".alert").each(function(index){
        $(this).delay(200*index).fadeTo(1500,0).slideUp(500,function(){
            $(this).remove();
        });
    });
},2000);

What do these three dots in React do?

This is a new feature in ES6/Harmony. It is called the Spread Operator. It lets you either separate the constituent parts of an array/object, or take multiple items/parameters and glue them together. Here is an example:

let array = [1,2,3]
let array2 = [...array]
// array2 is now filled with the items from array

And with an object/keys:

// lets pass an object as props to a react component
let myParameters = {myKey: 5, myOtherKey: 7}
let component = <MyComponent {...myParameters}/>
// this is equal to <MyComponent myKey=5 myOtherKey=7 />

What's really cool is you can use it to mean "the rest of the values".

const myFunc = (value1, value2, ...values) {
    // Some code
}

myFunc(1, 2, 3, 4, 5)
// when myFunc is called, the rest of the variables are placed into the "values" array

Wait until flag=true

_x000D_
_x000D_
//function a(callback){_x000D_
setTimeout(function() {_x000D_
  console.log('Hi I am order 1');_x000D_
}, 3000);_x000D_
 // callback();_x000D_
//}_x000D_
_x000D_
//function b(callback){_x000D_
setTimeout(function() {_x000D_
  console.log('Hi I am order 2');_x000D_
}, 2000);_x000D_
//   callback();_x000D_
//}_x000D_
_x000D_
_x000D_
_x000D_
//function c(callback){_x000D_
setTimeout(function() {_x000D_
  console.log('Hi I am order 3');_x000D_
}, 1000);_x000D_
//   callback();_x000D_
_x000D_
//}_x000D_
_x000D_
 _x000D_
/*function d(callback){_x000D_
  a(function(){_x000D_
    b(function(){_x000D_
      _x000D_
      c(callback);_x000D_
      _x000D_
    });_x000D_
    _x000D_
  });_x000D_
  _x000D_
  _x000D_
}_x000D_
d();*/_x000D_
_x000D_
_x000D_
async function funa(){_x000D_
  _x000D_
  var pr1=new Promise((res,rej)=>{_x000D_
    _x000D_
   setTimeout(()=>res("Hi4 I am order 1"),3000)_x000D_
        _x000D_
  })_x000D_
  _x000D_
  _x000D_
   var pr2=new Promise((res,rej)=>{_x000D_
    _x000D_
   setTimeout(()=>res("Hi4 I am order 2"),2000)_x000D_
        _x000D_
  })_x000D_
   _x000D_
    var pr3=new Promise((res,rej)=>{_x000D_
    _x000D_
   setTimeout(()=>res("Hi4 I am order 3"),1000)_x000D_
        _x000D_
  })_x000D_
_x000D_
              _x000D_
  var res1 = await pr1;_x000D_
  var res2 = await pr2;_x000D_
  var res3 = await pr3;_x000D_
  console.log(res1,res2,res3);_x000D_
  console.log(res1);_x000D_
   console.log(res2);_x000D_
   console.log(res3);_x000D_
_x000D_
}   _x000D_
    funa();_x000D_
              _x000D_
_x000D_
_x000D_
async function f1(){_x000D_
  _x000D_
  await new Promise(r=>setTimeout(r,3000))_x000D_
    .then(()=>console.log('Hi3 I am order 1'))_x000D_
    return 1;                        _x000D_
_x000D_
}_x000D_
_x000D_
async function f2(){_x000D_
  _x000D_
  await new Promise(r=>setTimeout(r,2000))_x000D_
    .then(()=>console.log('Hi3 I am order 2'))_x000D_
         return 2;                   _x000D_
_x000D_
}_x000D_
_x000D_
async function f3(){_x000D_
  _x000D_
  await new Promise(r=>setTimeout(r,1000))_x000D_
    .then(()=>console.log('Hi3 I am order 3'))_x000D_
        return 3;                    _x000D_
_x000D_
}_x000D_
_x000D_
async function finaloutput2(arr){_x000D_
  _x000D_
  return await Promise.all([f3(),f2(),f1()]);_x000D_
}_x000D_
_x000D_
//f1().then(f2().then(f3()));_x000D_
//f3().then(f2().then(f1()));_x000D_
  _x000D_
//finaloutput2();_x000D_
_x000D_
//var pr1=new Promise(f3)_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
async function f(){_x000D_
  console.log("makesure");_x000D_
  var pr=new Promise((res,rej)=>{_x000D_
  setTimeout(function() {_x000D_
  console.log('Hi2 I am order 1');_x000D_
}, 3000);_x000D_
  });_x000D_
    _x000D_
  _x000D_
  var result=await pr;_x000D_
  console.log(result);_x000D_
}_x000D_
_x000D_
 // f(); _x000D_
_x000D_
async function g(){_x000D_
  console.log("makesure");_x000D_
  var pr=new Promise((res,rej)=>{_x000D_
  setTimeout(function() {_x000D_
  console.log('Hi2 I am order 2');_x000D_
}, 2000);_x000D_
  });_x000D_
    _x000D_
  _x000D_
  var result=await pr;_x000D_
  console.log(result);_x000D_
}_x000D_
  _x000D_
// g(); _x000D_
_x000D_
async function h(){_x000D_
  console.log("makesure");_x000D_
  var pr=new Promise((res,rej)=>{_x000D_
  setTimeout(function() {_x000D_
  console.log('Hi2 I am order 3');_x000D_
}, 1000);_x000D_
  });_x000D_
    _x000D_
  _x000D_
  var result=await pr;_x000D_
  console.log(result);_x000D_
}_x000D_
_x000D_
async function finaloutput(arr){_x000D_
  _x000D_
  return await Promise.all([f(),g(),h()]);_x000D_
}_x000D_
  _x000D_
//finaloutput();_x000D_
_x000D_
 //h(); _x000D_
  _x000D_
  _x000D_
  _x000D_
  _x000D_
  _x000D_
  
_x000D_
_x000D_
_x000D_

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

how to automatically scroll down a html page?

You can use two different techniques to achieve this.

The first one is with javascript: set the scrollTop property of the scrollable element (e.g. document.body.scrollTop = 1000;).

The second is setting the link to point to a specific id in the page e.g.

<a href="mypage.html#sectionOne">section one</a>

Then if in your target page you'll have that ID the page will be scrolled automatically.

How to inject Javascript in WebBrowser control?

I believe the most simple method to inject Javascript in a WebBrowser Control HTML Document from c# is to invoke the "execScript" method with the code to be injected as argument.

In this example the javascript code is injected and executed at global scope:

var jsCode="alert('hello world from injected code');";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });

If you want to delay execution, inject functions and call them after:

var jsCode="function greet(msg){alert(msg);};";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });
...............
WebBrowser.Document.InvokeScript("greet",new object[] {"hello world"});

This is valid for Windows Forms and WPF WebBrowser controls.

This solution is not cross browser because "execScript" is defined only in IE and Chrome. But the question is about Microsoft WebBrowser controls and IE is the only one supported.

For a valid cross browser method to inject javascript code, create a Function object with the new Keyword. This example creates an anonymous function with injected code and executes it (javascript implements closures and the function has access to global space without local variable pollution).

var jsCode="alert('hello world');";
(new Function(code))();

Of course, you can delay execution:

var jsCode="alert('hello world');";
var inserted=new Function(code);
.................
inserted();

Hope it helps

box-shadow on bootstrap 3 container

You should give the container an id and use that in your custom css file (which should be linked after the bootstrap css):

#container { box-shadow: values }

Adding asterisk to required fields in Bootstrap 3

The other two answers are correct. When you include spaces in your CSS selectors you're targeting child elements so:

.form-group .required {
    styles
}

Is targeting an element with the class of "required" that is inside an element with the class of "form-group".

Without the space it's targeting an element that has both classes. 'required' and 'form-group'

Bootstrap 4 Change Hamburger Toggler Color

Check the best solution for custom hamburger nav.

_x000D_
_x000D_
@import "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css";_x000D_
.bg-iconnav {_x000D_
  background: #f0323d;_x000D_
  /* Old browsers */_x000D_
  background: -moz-linear-gradient(top, #f0323d 0%, #e6366c 100%);_x000D_
  /* FF3.6-15 */_x000D_
  background: -webkit-linear-gradient(top, #f0323d 0%, #e6366c 100%);_x000D_
  /* Chrome10-25,Safari5.1-6 */_x000D_
  background: linear-gradient(to bottom, #f0323d 0%, #e6366c 100%);_x000D_
  /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f0323d', endColorstr='#e6366c', GradientType=0);_x000D_
  /* IE6-9 */_x000D_
  border-radius: 0;_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
.navbar-toggler-icon {_x000D_
  background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(255,255,255, 1)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 8h24M4 16h24M4 24h24'/%3E%3C/svg%3E");_x000D_
}
_x000D_
<button class="navbar-toggler bg-iconnav" type="button">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>
_x000D_
_x000D_
_x000D_

demo image

How to customize the back button on ActionBar

tray this:

getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);

inside onCreate();

ASP.NET MVC 3 Razor - Adding class to EditorFor

As of ASP.NET MVC 5.1, adding a class to an EditorFor is possible (the original question specified ASP.NET MVC 3, and the accepted answer is still the best with that considered).

@Html.EditorFor(x=> x.MyProperty,
    new { htmlAttributes = new { @class = "MyCssClass" } })

See: What's New in ASP.NET MVC 5.1, Bootstrap support for editor templates

How to update an object in a List<> in C#

This was a new discovery today - after having learned the class/struct reference lesson!

You can use Linq and "Single" if you know the item will be found, because Single returns a variable...

myList.Single(x => x.MyProperty == myValue).OtherProperty = newValue;

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

Thought I'd give a full answer combining some of the possible intricacies required for completeness.

  1. Check if you have 32-bit or 64-bit IIS installed:
    • Go to IIS Manager ? Application Pools, choose the appropriate app pool then Advanced Settings.
    • Check the setting "Enable 32-bit Applications". If that's true, that means the worker process is forced to run in 32-bit. If the setting is false, then the app pool is running in 64-bit mode.
    • You can also open up Task Manager and check w3wp.exe. If it's showing as w3wp*32.exe then it's 32-bit.
  2. Download the appropriate version here: https://www.iis.net/downloads/microsoft/url-rewrite#additionalDownloads.
  3. Install it.
  4. Close and reopen IIS Manager to ensure the URL Rewrite module appears.

Quick Sort Vs Merge Sort

Quicksort is in place. You need very little extra memory. Which is extremely important.

Good choice of median makes it even more efficient but even a bad choice of median quarantees Theta(nlogn).

Create XML in Javascript

Disclaimer: The following answer assumes that you are using the JavaScript environment of a web browser.

JavaScript handles XML with 'XML DOM objects'. You can obtain such an object in three ways:

1. Creating a new XML DOM object

var xmlDoc = document.implementation.createDocument(null, "books");

The first argument can contain the namespace URI of the document to be created, if the document belongs to one.

Source: https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument

2. Fetching an XML file with XMLHttpRequest

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {

    var xmlDoc = xhttp.responseXML; //important to use responseXML here
}
xhttp.open("GET", "books.xml", true);
xhttp.send();

3. Parsing a string containing serialized XML

var xmlString = "<root></root>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml"); //important to use "text/xml"

When you have obtained an XML DOM object, you can use methods to manipulate it like

var node = xmlDoc.createElement("heyHo");
var elements = xmlDoc.getElementsByTagName("root");
elements[0].appendChild(node);

For a full reference, see http://www.w3schools.com/xml/dom_intro.asp

Note: It is important, that you don't use the methods provided by the document namespace, i. e.

var node = document.createElement("Item");

This will create HTML nodes instead of XML nodes and will result in a node with lower-case tag names. XML tag names are case-sensitive in contrast to HTML tag names.

You can serialize XML DOM objects like this:

var serializer = new XMLSerializer();
var xmlString = serializer.serializeToString(xmlDoc);

Extract substring from a string

substring():

str.substring(startIndex, endIndex); 

If two cells match, return value from third

All you have to do is write an IF condition in the column d like this:

=IF(A1=C1;B1;" ")

After that just apply this formula to all rows above that one.

How do I merge dictionaries together in Python?

Starting in Python 3.9, the operator | creates a new dictionary with the merged keys and values from two dictionaries:

# d1 = { 'a': 1, 'b': 2 }
# d2 = { 'b': 1, 'c': 3 }
d3 = d2 | d1
# d3: {'b': 2, 'c': 3, 'a': 1}

This:

Creates a new dictionary d3 with the merged keys and values of d2 and d1. The values of d1 take priority when d2 and d1 share keys.


Also note the |= operator which modifies d2 by merging d1 in, with priority on d1 values:

# d1 = { 'a': 1, 'b': 2 }
# d2 = { 'b': 1, 'c': 3 }
d2 |= d1
# d2: {'b': 2, 'c': 3, 'a': 1}

?

How do I read all classes from a Java package in the classpath?

use dependency maven:

groupId: net.sf.extcos
artifactId: extcos
version: 0.4b

then use this code :

ComponentScanner scanner = new ComponentScanner();
        Set classes = scanner.getClasses(new ComponentQuery() {
            @Override
            protected void query() {
                select().from("com.leyton").returning(allExtending(DynamicForm.class));
            }
        });

Applying a single font to an entire website with CSS

Ok so I was having this issue where I tried several different options.

The font i'm using is Ubuntu-LI , I created a font folder in my working directory. under the folder fonts

I was able to apply it... eventually here is my working code

I wanted this to apply to my entire website so I put it at the top of the css doc. above all of the Div tags (not that it matters, just know that any individual fonts you assign post your script will take precedence)

@font-face{
    font-family: "Ubuntu-LI";
    src: url("/fonts/Ubuntu/(Ubuntu-LI.ttf"),
    url("../fonts/Ubuntu/Ubuntu-LI.ttf");
}

*{
    font-family:"Ubuntu-LI";
}

If i then wanted all of my H1 tags to be something else lets say sans sarif I would do something like

h1{
   font-family: Sans-sarif;
}

From which case only my H1 tags would be the sans-sarif font and the rest of my page would be the Ubuntu-LI font

Difference between webdriver.Dispose(), .Close() and .Quit()

Close() - It is used to close the browser or page currently which is having the focus.

Quit() - It is used to shut down the web driver instance or destroy the web driver instance(Close all the windows).

Dispose() - I am not aware of this method.

Creating temporary files in bash

You might want to look at mktemp

The mktemp utility takes the given filename template and overwrites a portion of it to create a unique filename. The template may be any filename with some number of 'Xs' appended to it, for example /tmp/tfile.XXXXXXXXXX. The trailing 'Xs' are replaced with a combination of the current process number and random letters.

For more details: man mktemp

How can I add raw data body to an axios request?

I got same problem. So I looked into the axios document. I found it. you can do it like this. this is easiest way. and super simple.

https://www.npmjs.com/package/axios#using-applicationx-www-form-urlencoded-format

var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

You can use .then,.catch.

How to redirect stdout to both file and console with scripting?

I devised an easier solution. Just define a function that will print to file or to screen or to both of them. In the example below I allow the user to input the outputfile name as an argument but that is not mandatory:

OutputFile= args.Output_File
OF = open(OutputFile, 'w')

def printing(text):
    print text
    if args.Output_File:
        OF.write(text + "\n")

After this, all that is needed to print a line both to file and/or screen is: printing(Line_to_be_printed)

Counting number of words in a file

import java.io.BufferedReader;
import java.io.FileReader;

public class CountWords {

    public static void main (String args[]) throws Exception {

       System.out.println ("Counting Words");       
       FileReader fr = new FileReader ("c:\\Customer1.txt");        
       BufferedReader br = new BufferedReader (fr);     
       String line = br.readLin ();
       int count = 0;
       while (line != null) {
          String []parts = line.split(" ");
          for( String w : parts)
          {
            count++;        
          }
          line = br.readLine();
       }         
       System.out.println(count);
    }
}

How to add spacing between columns?

According to Bootstrap 4 documentation you should give the parent a negative margin mx-n*, and the children a positive padding px-*

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="row mx-n5">_x000D_
  <div class="col px-5">_x000D_
    <div class="p-3 border bg-light">Custom column padding</div>_x000D_
  </div>_x000D_
  <div class="col px-5">_x000D_
    <div class="p-3 border bg-light">Custom column padding</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

XDocument or XmlDocument

I believe that XDocument makes a lot more object creation calls. I suspect that for when you're handling a lot of XML documents, XMLDocument will be faster.

One place this happens is in managing scan data. Many scan tools output their data in XML (for obvious reasons). If you have to process a lot of these scan files, I think you'll have better performance with XMLDocument.

Should I initialize variable within constructor or outside constructor

The only problem I see with the first method is if you are planning to add more constructors. Then you will be repeating code and maintainability would suffer.

Does `anaconda` create a separate PYTHONPATH variable for each new environment?

Anaconda does not use the PYTHONPATH. One should however note that if the PYTHONPATH is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a

unset PYTHONPATH

For instance this PYTHONPATH points to an incorrect pandas lib:

export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
    from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8

unsetting the PYTHONPATH prevents the wrong pandas lib from being loaded:

unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>

How to Get a Specific Column Value from a DataTable?

foreach (DataRow row in Datatable.Rows) 
{
    if (row["CountryName"].ToString() == userInput) 
    {
        return row["CountryID"];
    }
}

While this may not compile directly you should get the idea, also I'm sure it would be vastly superior to do the query through SQL as a huge datatable will take a long time to run through all the rows.

Pass variables from servlet to jsp

It will fail to work when:

  1. You are redirecting the response to a new request by response.sendRedirect("page.jsp"). The newly created request object will of course not contain the attributes anymore and they will not be accessible in the redirected JSP. You need to forward rather than redirect. E.g.

    request.setAttribute("name", "value");
    request.getRequestDispatcher("page.jsp").forward(request, response);
    
  2. You are accessing it the wrong way or using the wrong name. Assuming that you have set it using the name "name", then you should be able to access it in the forwarded JSP page as follows:

    ${name}
    

How to calculate mean, median, mode and range from a set of numbers

    public static Set<Double> getMode(double[] data) {
            if (data.length == 0) {
                return new TreeSet<>();
            }
            TreeMap<Double, Integer> map = new TreeMap<>(); //Map Keys are array values and Map Values are how many times each key appears in the array
            for (int index = 0; index != data.length; ++index) {
                double value = data[index];
                if (!map.containsKey(value)) {
                    map.put(value, 1); //first time, put one
                }
                else {
                    map.put(value, map.get(value) + 1); //seen it again increment count
                }
            }
            Set<Double> modes = new TreeSet<>(); //result set of modes, min to max sorted
            int maxCount = 1;
            Iterator<Integer> modeApperance = map.values().iterator();
            while (modeApperance.hasNext()) {
                maxCount = Math.max(maxCount, modeApperance.next()); //go through all the value counts
            }
            for (double key : map.keySet()) {
                if (map.get(key) == maxCount) { //if this key's value is max
                    modes.add(key); //get it
                }
            }
            return modes;
        }

        //std dev function for good measure
        public static double getStandardDeviation(double[] data) {
            final double mean = getMean(data);
            double sum = 0;
            for (int index = 0; index != data.length; ++index) {
                sum += Math.pow(Math.abs(mean - data[index]), 2);
            }
            return Math.sqrt(sum / data.length);
        }


        public static double getMean(double[] data) {
        if (data.length == 0) {
            return 0;
        }
        double sum = 0.0;
        for (int index = 0; index != data.length; ++index) {
            sum += data[index];
        }
        return sum / data.length;
    }

//by creating a copy array and sorting it, this function can take any data.
    public static double getMedian(double[] data) {
        double[] copy = Arrays.copyOf(data, data.length);
        Arrays.sort(copy);
        return (copy.length % 2 != 0) ? copy[copy.length / 2] : (copy[copy.length / 2] + copy[(copy.length / 2) - 1]) / 2;
    }

How to break lines at a specific character in Notepad++?

  1. Click Ctrl + h or Search -> Replace on the top menu
  2. Under the Search Mode group, select Regular expression
  3. In the Find what text field, type ],\s*
  4. In the Replace with text field, type ],\n
  5. Click Replace All

Setting a WebRequest's body data

The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:

var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic   N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "[email protected]");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

The code above depends on the nuget package RestSharp, which you can easily install.

How to focus on a form input text field on page load using jQuery?

Sorry for bumping an old question. I found this via google.

Its also worth noting that its possible to use more than one selector, thus you can target any form element, and not just one specific type.

eg.

$('#myform input,#myform textarea').first().focus();

This will focus the first input or textarea it finds, and of course you can add other selectors into the mix as well. Handy if you can't be certain of a specific element type being first, or if you want something a bit general/reusable.

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

Android Color Picker

After some searches in the android references, the newcomer QuadFlask Color Picker seems to be a technically and aesthetically good choice. Also it has Transparency slider and supports HEX coded colors.

Take a look:
QuadFlask Color Picker

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

Restart IIS- could be a process attached to the debugger

jQuery - Illegal invocation

If you want to submit a form using Javascript FormData API with uploading files you need to set below two options:

processData: false,
contentType: false

You can try as follows:

//Ajax Form Submission
$(document).on("click", ".afs", function (e) {
    e.preventDefault();
    e.stopPropagation();
    var thisBtn = $(this);
    var thisForm = thisBtn.closest("form");
    var formData = new FormData(thisForm[0]);
    //var formData = thisForm.serializeArray();

    $.ajax({
        type: "POST",
        url: "<?=base_url();?>assignment/createAssignment",
        data: formData,
        processData: false,
        contentType: false,
        success:function(data){
            if(data=='yes')
            {
                alert('Success! Record inserted successfully');
            }
            else if(data=='no')
            {
                alert('Error! Record not inserted successfully')
            }
            else
            {
                alert('Error! Try again');
            }
        }
    });
});

How to add a button programmatically in VBA next to some sheet cell data?

Suppose your function enters data in columns A and B and you want to a custom Userform to appear if the user selects a cell in column C. One way to do this is to use the SelectionChange event:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim clickRng As Range
    Dim lastRow As Long

    lastRow = Range("A1").End(xlDown).Row
    Set clickRng = Range("C1:C" & lastRow) //Dynamically set cells that can be clicked based on data in column A

    If Not Intersect(Target, clickRng) Is Nothing Then
        MyUserForm.Show //Launch custom userform
    End If

End Sub

Note that the userform will appear when a user selects any cell in Column C and you might want to populate each cell in Column C with something like "select cell to launch form" to make it obvious that the user needs to perform an action (having a button naturally suggests that it should be clicked)

How can I print to the same line?

Format your string like so:

[#                    ] 1%\r

Note the \r character. It is the so-called carriage return that will move the cursor back to the beginning of the line.

Finally, make sure you use

System.out.print()

and not

System.out.println()

send mail from linux terminal in one line

mail can represent quite a couple of programs on a linux system. What you want behind it is either sendmail or postfix. I recommend the latter.

You can install it via your favorite package manager. Then you have to configure it, and once you have done that, you can send email like this:

 echo "My message" | mail -s subject [email protected]

See the manual for more information.

As far as configuring postfix goes, there's plenty of articles on the internet on how to do it. Unless you're on a public server with a registered domain, you generally want to forward the email to a SMTP server that you can send email from.

For gmail, for example, follow http://rtcamp.com/tutorials/linux/ubuntu-postfix-gmail-smtp/ or any other similar tutorial.

Check to see if python script is running

ps ax | grep processName

if yor debug script in pycharm always exit

pydevd.py --multiproc --client 127.0.0.1 --port 33882 --file processName

C++ equivalent of java's instanceof

Depending on what you want to do you could do this:

template<typename Base, typename T>
inline bool instanceof(const T*) {
    return std::is_base_of<Base, T>::value;
}

Use:

if (instanceof<BaseClass>(ptr)) { ... }

However, this purely operates on the types as known by the compiler.

Edit:

This code should work for polymorphic pointers:

template<typename Base, typename T>
inline bool instanceof(const T *ptr) {
    return dynamic_cast<const Base*>(ptr) != nullptr;
}

Example: http://cpp.sh/6qir

Random / noise functions for GLSL

Gustavson's implementation uses a 1D texture

No it doesn't, not since 2005. It's just that people insist on downloading the old version. The version that is on the link you supplied uses only 8-bit 2D textures.

The new version by Ian McEwan of Ashima and myself does not use a texture, but runs at around half the speed on typical desktop platforms with lots of texture bandwidth. On mobile platforms, the textureless version might be faster because texturing is often a significant bottleneck.

Our actively maintained source repository is:

https://github.com/ashima/webgl-noise

A collection of both the textureless and texture-using versions of noise is here (using only 2D textures):

http://www.itn.liu.se/~stegu/simplexnoise/GLSL-noise-vs-noise.zip

If you have any specific questions, feel free to e-mail me directly (my email address can be found in the classicnoise*.glsl sources.)

checking if number entered is a digit in jquery

Value validation wouldn't be a responsibility of jQuery. You can use pure JavaScript for this. Two ways that come to my mind are:

/^\d+$/.match(value)
Number(value) == value

How to handle click event in Button Column in Datagridview?

You can try this one, you wouldn't care much about the ordering of the columns.

private void TheGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (TheGrid.Columns[e.ColumnIndex].HeaderText == "Edit")
    {
        // to do: edit actions here
        MessageBox.Show("Edit");
    }
}

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

_x000D_
_x000D_
//find duplicates:_x000D_
//sort, then reduce - concat values equal previous element, skip others_x000D_
_x000D_
//input_x000D_
var a = [1, 2, 3, 1, 2, 1, 2]_x000D_
_x000D_
//short version:_x000D_
var duplicates = a.sort().reduce((d, v, i, a) => i && v === a[i - 1] ? d.concat(v) : d, [])_x000D_
console.log(duplicates); //[1, 1, 2, 2]_x000D_
_x000D_
//readable version:_x000D_
var duplicates = a.sort().reduce((output, element, index, input) => {_x000D_
  if ((index > 0) && (element === input[index - 1]))_x000D_
    return output.concat(element)_x000D_
  return output_x000D_
}, [])_x000D_
console.log(duplicates); //[1, 1, 2, 2]
_x000D_
_x000D_
_x000D_

What's your most controversial programming opinion?

One class per file

Who cares? I much prefer entire programs contained in one file rather than a million different files.

Removing cordova plugins from the project

  • access the folder
  • list the plugins (cordova plugin list)
  • ionic cordova plugin remove "pluginName"

Should be fine!

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

use this syntax: alter table table_name modify column col_name varchar (10000);

Check if current date is between two dates Oracle SQL

TSQL: Dates- need to look for gaps in dates between Two Date

select
distinct
e1.enddate,
e3.startdate,
DATEDIFF(DAY,e1.enddate,e3.startdate)-1 as [Datediff]
from #temp e1 
   join #temp e3 on e1.enddate < e3.startdate          
       /* Finds the next start Time */
and e3.startdate = (select min(startdate) from #temp e5
where e5.startdate > e1.enddate)
and not exists (select *  /* Eliminates e1 rows if it is overlapped */
from #temp e5 
where e5.startdate < e1.enddate and e5.enddate > e1.enddate);

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

This normally happens when the transaction is started and either it is not committed or it is not rollback.

In case the error comes in your stored procedure, this can lock the database tables because transaction is not completed due to some runtime errors in the absence of exception handling You can use Exception handling like below. SET XACT_ABORT

SET XACT_ABORT ON
SET NoCount ON
Begin Try 
     BEGIN TRANSACTION 
        //Insert ,update queries    
     COMMIT
End Try 
Begin Catch 
     ROLLBACK
End Catch

Source

How to animate button in android?

import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;

public class HeightAnimation extends Animation {
    protected final int originalHeight;
    protected final View view;
    protected float perValue;

    public HeightAnimation(View view, int fromHeight, int toHeight) {
        this.view = view;
        this.originalHeight = fromHeight;
        this.perValue = (toHeight - fromHeight);
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        view.getLayoutParams().height = (int) (originalHeight + perValue * interpolatedTime);
        view.requestLayout();
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }
}

uss to:

HeightAnimation heightAnim = new HeightAnimation(view, view.getHeight(), viewPager.getHeight() - otherView.getHeight());
heightAnim.setDuration(1000);
view.startAnimation(heightAnim);

Difference between request.getSession() and request.getSession(true)

A major practical difference is its use:

in security scenario where we always needed a new session, we should use request.getSession(true).

request.getSession(false): will return null if no session found.

Sanitizing strings to make them URL and filename safe?

Solution #1: You have ability to install PHP extensions on server (hosting)

For transliteration of "almost every single language on the planet Earth" to ASCII characters.

  1. Install PHP Intl extension first. This is command for Debian (Ubuntu): sudo aptitude install php5-intl

  2. This is my fileName function (create test.php and paste there following code):

_x000D_
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Test</title>_x000D_
</head>_x000D_
<body>_x000D_
<?php_x000D_
_x000D_
function pr($string) {_x000D_
  print '<hr>';_x000D_
  print '"' . fileName($string) . '"';_x000D_
  print '<br>';_x000D_
  print '"' . $string . '"';_x000D_
}_x000D_
_x000D_
function fileName($string) {_x000D_
  // remove html tags_x000D_
  $clean = strip_tags($string);_x000D_
  // transliterate_x000D_
  $clean = transliterator_transliterate('Any-Latin;Latin-ASCII;', $clean);_x000D_
  // remove non-number and non-letter characters_x000D_
  $clean = str_replace('--', '-', preg_replace('/[^a-z0-9-\_]/i', '', preg_replace(array(_x000D_
    '/\s/', _x000D_
    '/[^\w-\.\-]/'_x000D_
  ), array(_x000D_
    '_', _x000D_
    ''_x000D_
  ), $clean)));_x000D_
  // replace '-' for '_'_x000D_
  $clean = strtr($clean, array(_x000D_
    '-' => '_'_x000D_
  ));_x000D_
  // remove double '__'_x000D_
  $positionInString = stripos($clean, '__');_x000D_
  while ($positionInString !== false) {_x000D_
    $clean = str_replace('__', '_', $clean);_x000D_
    $positionInString = stripos($clean, '__');_x000D_
  }_x000D_
  // remove '_' from the end and beginning of the string_x000D_
  $clean = rtrim(ltrim($clean, '_'), '_');_x000D_
  // lowercase the string_x000D_
  return strtolower($clean);_x000D_
}_x000D_
pr('_replace(\'~&([a-z]{1,2})(ac134/56f4315981743 8765475[]lt7nl2ú5änú138yé73tž7ýlute|');_x000D_
pr(htmlspecialchars('<script>alert(\'hacked\')</script>'));_x000D_
pr('Álix----_Ãxel!?!?');_x000D_
pr('áéíóúÁÉÍÓÚ');_x000D_
pr('üÿÄËÏÖÜ.ŸåÅ');_x000D_
pr('nie4c a a§ônäääaš');_x000D_
pr('??? ??????');_x000D_
pr('???');_x000D_
pr('??? ??? ????');_x000D_
pr('???? ????????');_x000D_
pr('??? ???-????');_x000D_
pr('??? ??????');_x000D_
pr('Mao Tr?ch Ðông');_x000D_
pr('???');_x000D_
pr('???? ??????');_x000D_
?>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

This line is core:

  // transliterate
  $clean = transliterator_transliterate('Any-Latin;Latin-ASCII;', $clean);

Answer based on this post.

Solution #2: You don't have ability to install PHP extensions on server (hosting)

enter image description here

Pretty good job is done in transliteration module for CMS Drupal. It supports almost every single language on the planet Earth. I suggest to check plugin repository if you want to have really complete solution sanitizing strings.

PHP: Split string

$array = explode('.',$string);

Returns an array of split elements.

AngularJS How to dynamically add HTML and bind to controller

I needed to execute an directive AFTER loading several templates so I created this directive:

_x000D_
_x000D_
utilModule.directive('utPreload',_x000D_
    ['$templateRequest', '$templateCache', '$q', '$compile', '$rootScope',_x000D_
    function($templateRequest, $templateCache, $q, $compile, $rootScope) {_x000D_
    'use strict';_x000D_
    var link = function(scope, element) {_x000D_
        scope.$watch('done', function(done) {_x000D_
            if(done === true) {_x000D_
                var html = "";_x000D_
                if(scope.slvAppend === true) {_x000D_
                    scope.urls.forEach(function(url) {_x000D_
                        html += $templateCache.get(url);_x000D_
                    });_x000D_
                }_x000D_
                html += scope.slvHtml;_x000D_
                element.append($compile(html)($rootScope));_x000D_
            }_x000D_
        });_x000D_
    };_x000D_
_x000D_
    var controller = function($scope) {_x000D_
        $scope.done = false;_x000D_
        $scope.html = "";_x000D_
        $scope.urls = $scope.slvTemplate.split(',');_x000D_
        var promises = [];_x000D_
        $scope.urls.forEach(function(url) {_x000D_
            promises.add($templateRequest(url));_x000D_
        });_x000D_
        $q.all(promises).then(_x000D_
            function() { // SUCCESS_x000D_
                $scope.done = true;_x000D_
            }, function() { // FAIL_x000D_
                throw new Error('preload failed.');_x000D_
            }_x000D_
        );_x000D_
    };_x000D_
_x000D_
    return {_x000D_
        restrict: 'A',_x000D_
        scope: {_x000D_
            utTemplate: '=', // the templates to load (comma separated)_x000D_
            utAppend: '=', // boolean: append templates to DOM after load?_x000D_
            utHtml: '=' // the html to append and compile after templates have been loaded_x000D_
        },_x000D_
        link: link,_x000D_
        controller: controller_x000D_
    };_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>_x000D_
_x000D_
<div class="container-fluid"_x000D_
     ut-preload_x000D_
     ut-append="true"_x000D_
     ut-template="'html/one.html,html/two.html'"_x000D_
     ut-html="'<my-directive></my-directive>'">_x000D_
 _x000D_
</div>
_x000D_
_x000D_
_x000D_

how to zip a folder itself using java

Have you tried Zeroturnaround Zip library? It's really neat! Zip a folder is just a one liner:

ZipUtil.pack(new File("D:\\reports\\january\\"), new File("D:\\reports\\january.zip"));

(thanks to Oleg Šelajev for the example)

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

the below lines would also work

!python script.py

How to use a jQuery plugin inside Vue

There's a much, much easier way. Do this:

MyComponent.vue

<template>
  stuff here
</template>
<script>
  import $ from 'jquery';
  import 'selectize';

  $(function() {
      // use jquery
      $('body').css('background-color', 'orange');

      // use selectize, s jquery plugin
      $('#myselect').selectize( options go here );
  });

</script>

Make sure JQuery is installed first with npm install jquery. Do the same with your plugin.

CSS: 100% width or height while keeping aspect ratio?

Not to jump into an old issue, but...

#container img {
      max-width:100%;
      height:auto !important;
}

Even though this is not proper as you use the !important override on the height, if you're using a CMS like WordPress that sets the height and width for you, this works well.

How to put a tooltip on a user-defined function

Not a tooltip solution but an adequate workaround:

Start typing the UDF =MyUDF( then press CTRL + Shift + A and your function parameters will be displayed. So long as those parameters have meaningful names you at-least have a viable prompt

For example, this:

=MyUDF( + CTRL + Shift + A

Turns into this:

=MyUDF(sPath, sFileName)

Ruby: What is the easiest way to remove the first element from an array?

You can use:

 a.delete(a[0])   
 a.delete_at 0

Both can work

Is it possible to specify a different ssh port when using rsync?

I found this solution on Mike Hike Hostetler's site that worked perfectly for me.

# rsync -avz -e "ssh -p $portNumber" user@remoteip:/path/to/files/ /local/path/

Copy Image from Remote Server Over HTTP

Here's the most basic way:

$url = "http://other-site/image.png";
$dir = "/my/local/dir/";

$rfile = fopen($url, "r");
$lfile = fopen($dir . basename($url), "w");

while(!feof($url)) fwrite($lfile, fread($rfile, 1), 1);

fclose($rfile);
fclose($lfile);

But if you're doing lots and lots of this (or your host blocks file access to remote systems), consider using CURL, which is more efficient, mildly faster and available on more shared hosts.

You can also spoof the user agent to look like a desktop rather than a bot!

$url = "http://other-site/image.png";
$dir = "/my/local/dir/";
$lfile = fopen($dir . basename($url), "w");

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
curl_setopt($ch, CURLOPT_FILE, $lfile);

fclose($lfile);
curl_close($ch);

With both instances, you might want to pass it through GD to make sure it really is an image.

PHP to write Tab Characters inside a file?

This should do:

$chunk = "abc\tdef\tghi";

Here is a link to an article with more extensive examples.

Can you recommend a free light-weight MySQL GUI for Linux?

Why not try MySQL GUI Tools? It's light, and does its job well.

find path of current folder - cmd

for /f "delims=" %%i in ("%0") do set "curpath=%%~dpi"
echo "%curpath%"

or

echo "%cd%"

The double quotes are needed if the path contains any & characters.

How to get current relative directory of your Makefile?

Solution found here : https://sourceforge.net/p/ipt-netflow/bugs-requests-patches/53/

The solution is : $(CURDIR)

You can use it like that :

CUR_DIR = $(CURDIR)

## Start :
start:
    cd $(CUR_DIR)/path_to_folder

Flatten nested dictionaries, compressing keys

Here's an algorithm for elegant, in-place replacement. Tested with Python 2.7 and Python 3.5. Using the dot character as a separator.

def flatten_json(json):
    if type(json) == dict:
        for k, v in list(json.items()):
            if type(v) == dict:
                flatten_json(v)
                json.pop(k)
                for k2, v2 in v.items():
                    json[k+"."+k2] = v2

Example:

d = {'a': {'b': 'c'}}                   
flatten_json(d)
print(d)
unflatten_json(d)
print(d)

Output:

{'a.b': 'c'}
{'a': {'b': 'c'}}

I published this code here along with the matching unflatten_json function.

Paste a multi-line Java String in Eclipse

If your building that SQL in a tool like TOAD or other SQL oriented IDE they often have copy markup to the clipboard. For example, TOAD has a CTRL+M which takes the SQL in your editor and does exactly what you have in your code above. It also covers the reverse... when your grabbing a formatted string out of your Java and want to execute it in TOAD. Pasting the SQL back into TOAD and perform a CTRL+P to remove the multi-line quotes.

What's the difference between all the Selection Segues?

The document has moved here it seems: https://help.apple.com/xcode/mac/8.0/#/dev564169bb1

Can't copy the icons here, but here are the descriptions:

  • Show: Present the content in the detail or master area depending on the content of the screen.

    If the app is displaying a master and detail view, the content is pushed onto the detail area. If the app is only displaying the master or the detail, the content is pushed on top of the current view controller stack.

  • Show Detail: Present the content in the detail area.

    If the app is displaying a master and detail view, the new content replaces the current detail. If the app is only displaying the master or the detail, the content replaces the top of the current view controller stack.

  • Present Modally: Present the content modally.

  • Present as Popover: Present the content as a popover anchored to an existing view.

  • Custom: Create your own behaviors by using a custom segue.

How to configure PHP to send e-mail?

This will not work on a local host, but uploaded on a server, this code should do the trick. Just make sure to enter your own email address for the $to line.

<?php
if (isset($_POST['name']) && isset($_POST['email'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $to = '[email protected]';
    $subject = "New Message on YourWebsite.com";
    $body = '<html>
                <body>
                    <h2>Title</h2>
                    <br>
                    <p>Name:<br>'.$name.'</p>
                    <p>Email:<br>'.$email.'</p>

                </body>
            </html>';

//headers
$headers = "From: ".$name." <".$email.">\r\n";
$headers = "Reply-To: ".$email."\r\n";
$headers = "MIME-Version: 1.0\r\n";
$headers = "Content-type: text/html; charset=utf-8";

//send
$send = mail($to, $subject, $body, $headers);
if ($send) {
    echo '<br>';
    echo "Success. Thanks for Your Message.";
} else {
    echo 'Error.';
}
}
?>

<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <form action="" method="post">
            <input type="text" name="name" placeholder="Your Name"><br>
            <input type="text" name="email" placeholder="Your Email"><br>
            <button type="submit">Subscribe</button>
        </form>
    </body>
</html>

Stacked Tabs in Bootstrap 3

You should not need to add this back in. This was removed purposefully. The documentation has changed somewhat and the CSS class that is necessary ("nav-stacked") is only mentioned under the pills component, but should work for tabs as well.

This tutorial shows how to use the Bootstrap 3 setup properly to do vertical tabs:
tutsme-webdesign.info/bootstrap-3-toggable-tabs-and-pills

Find an object in SQL Server (cross-database)

sp_MSforeachdb 'select db_name(), * From ?..sysobjects where xtype in (''U'', ''P'') And name = ''ObjectName'''

Instead of 'ObjectName' insert object you are looking for. First column will display name of database where object is located at.

Not equal <> != operator on NULL

In SQL, anything you evaluate / compute with NULL results into UNKNOWN

This is why SELECT * FROM MyTable WHERE MyColumn != NULL or SELECT * FROM MyTable WHERE MyColumn <> NULL gives you 0 results.

To provide a check for NULL values, isNull function is provided.

Moreover, you can use the IS operator as you used in the third query.

Hope this helps.

Truncate Two decimal places without rounding

If you don't worry too much about performance and your end result can be a string, the following approach will be resilient to floating precision issues:

string Truncate(double value, int precision)
{
    if (precision < 0)
    {
        throw new ArgumentOutOfRangeException("Precision cannot be less than zero");
    }

    string result = value.ToString();

    int dot = result.IndexOf('.');
    if (dot < 0)
    {
        return result;
    }

    int newLength = dot + precision + 1;

    if (newLength == dot + 1)
    {
        newLength--;
    }

    if (newLength > result.Length)
    {
        newLength = result.Length;
    }

    return result.Substring(0, newLength);
}

Convert double to float in Java

To answer your query on "How to convert 2.3423424666767E13 to 23423424666767"

You can use a decimal formatter for formatting decimal numbers.

     double d = 2.3423424666767E13;
     DecimalFormat decimalFormat = new DecimalFormat("#");
     System.out.println(decimalFormat.format(d));

Output : 23423424666767

Convert CString to const char*

To convert a TCHAR CString to ASCII, use the CT2A macro - this will also allow you to convert the string to UTF8 (or any other Windows code page):

// Convert using the local code page
CString str(_T("Hello, world!"));
CT2A ascii(str);
TRACE(_T("ASCII: %S\n"), ascii.m_psz);

// Convert to UTF8
CString str(_T("Some Unicode goodness"));
CT2A ascii(str, CP_UTF8);
TRACE(_T("UTF8: %S\n"), ascii.m_psz);

// Convert to Thai code page
CString str(_T("Some Thai text"));
CT2A ascii(str, 874);
TRACE(_T("Thai: %S\n"), ascii.m_psz);

There is also a macro to convert from ASCII -> Unicode (CA2T) and you can use these in ATL/WTL apps as long as you have VS2003 or greater.

See the MSDN for more info.

How do I get a specific range of numbers from rand()?

The naive way to do it is:

int myRand = rand() % 66; // for 0-65

This will likely be a very slightly non-uniform distribution (depending on your maximum value), but it's pretty close.

To explain why it's not quite uniform, consider this very simplified example:
Suppose RAND_MAX is 4 and you want a number from 0-2. The possible values you can get are shown in this table:

rand()   |  rand() % 3
---------+------------
0        |  0
1        |  1
2        |  2
3        |  0

See the problem? If your maximum value is not an even divisor of RAND_MAX, you'll be more likely to choose small values. However, since RAND_MAX is generally 32767, the bias is likely to be small enough to get away with for most purposes.

There are various ways to get around this problem; see here for an explanation of how Java's Random handles it.

What is the use of verbose in Keras while validating the model?

verbose: Integer. 0, 1, or 2. Verbosity mode.

Verbose=0 (silent)

Verbose=1 (progress bar)

Train on 186219 samples, validate on 20691 samples
Epoch 1/2
186219/186219 [==============================] - 85s 455us/step - loss: 0.5815 - acc: 
0.7728 - val_loss: 0.4917 - val_acc: 0.8029
Train on 186219 samples, validate on 20691 samples
Epoch 2/2
186219/186219 [==============================] - 84s 451us/step - loss: 0.4921 - acc: 
0.8071 - val_loss: 0.4617 - val_acc: 0.8168

Verbose=2 (one line per epoch)

Train on 186219 samples, validate on 20691 samples
Epoch 1/1
 - 88s - loss: 0.5746 - acc: 0.7753 - val_loss: 0.4816 - val_acc: 0.8075
Train on 186219 samples, validate on 20691 samples
Epoch 1/1
 - 88s - loss: 0.4880 - acc: 0.8076 - val_loss: 0.5199 - val_acc: 0.8046

Reading Email using Pop3 in C#

My open source application BugTracker.NET includes a POP3 client that can parse MIME. Both the POP3 code and the MIME code are from other authors, but you can see how it all fits together in my app.

For the MIME parsing, I use http://anmar.eu.org/projects/sharpmimetools/.

See the file POP3Main.cs, POP3Client.cs, and insert_bug.aspx

how to call a onclick function in <a> tag?

You should read up on the onclick html attribute and the window.open() documentation. Below is what you want.

_x000D_
_x000D_
<a href='#' onclick='window.open("http://www.google.com", "myWin", "scrollbars=yes,width=400,height=650"); return false;'>1</a>
_x000D_
_x000D_
_x000D_

JSFiddle: http://jsfiddle.net/TBcVN/

How to install ia32-libs in Ubuntu 14.04 LTS (Trusty Tahr)

Simply install the 32-bit version of the program, instead of the 64-bit version.

This is much safer than installing packages that are not intended for the distribution at hand.

I got this suggestion from the Google Earth installation instructions for Ubuntu 14.04. Google Earth used to employ ia32-libs under 64-bit Ubuntu 12.04.

Quoting webupd8.org:

The ia32-libs package is no longer available in Ubuntu, starting with Ubuntu 13.10. The package was superseded by multiarch support so you don't need it any more, but some 64bit packages (which are actually 32bit applications) still depend on this package and because of this, they can't be installed in Ubuntu 14.04 or 13.10, 64bit. [...]

The "fix" or more specifically the correct way of installing these apps which depend on ia32-libs is to simply install the 32bit package on Ubuntu 64bit. Of course, that will install quite a few 32bit packages, but that's how multiarch works.

The problem with some programs (like Google Earth) is that the 32-bit package does not support multiarch. Consequently, some 32-bit dependencies need to be installed manually to make the 32-bit version of the program run on Ubuntu 64-bit.

sudo dpkg --add-architecture i386 # only needed once
sudo apt-get update
sudo apt-get install libfontconfig1:i386 libx11-6:i386 libxrender1:i386 libxext6:i386 libgl1-mesa-glx:i386 libglu1-mesa:i386 libglib2.0-0:i386 libsm6:i386

Simplest way to detect a pinch

My answer is inspired by Jeffrey's answer. Where that answer gives a more abstract solution, I try to provide more concrete steps on how to potentially implement it. This is simply a guide, one that can be implemented more elegantly. For a more detailed example check out this tutorial by MDN web docs.

HTML:

<div id="zoom_here">....</div>

JS

<script>
var dist1=0;
function start(ev) {
           if (ev.targetTouches.length == 2) {//check if two fingers touched screen
               dist1 = Math.hypot( //get rough estimate of distance between two fingers
                ev.touches[0].pageX - ev.touches[1].pageX,
                ev.touches[0].pageY - ev.touches[1].pageY);                  
           }
    
    }
    function move(ev) {
           if (ev.targetTouches.length == 2 && ev.changedTouches.length == 2) {
                 // Check if the two target touches are the same ones that started
               var dist2 = Math.hypot(//get rough estimate of new distance between fingers
                ev.touches[0].pageX - ev.touches[1].pageX,
                ev.touches[0].pageY - ev.touches[1].pageY);
                //alert(dist);
                if(dist1>dist2) {//if fingers are closer now than when they first touched screen, they are pinching
                  alert('zoom out');
                }
                if(dist1<dist2) {//if fingers are further apart than when they first touched the screen, they are making the zoomin gesture
                   alert('zoom in');
                }
           }
           
    }
        document.getElementById ('zoom_here').addEventListener ('touchstart', start, false);
        document.getElementById('zoom_here').addEventListener('touchmove', move, false);
</script>

Get path to execution directory of Windows Forms application

Check this out:

Imports System.IO
Imports System.Management

Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        TextBox1.Text = Path.GetFullPath(Application.ExecutablePath)
        Process.Start(TextBox1.Text)
    End Sub
End Class

How do you make a div tag into a link

If you have to set your anchor tag inside the div, you can also use CSS to set the anchor to fill the div via display:block.

As such:

<div style="height: 80px"><a href="#" style="display: block">Text</a></div>

Now when the user floats their cursor in that div the anchor tag will fill the div.

break out of if and foreach

A safer way to approach breaking a foreach or while loop in PHP is to nest an incrementing counter variable and if conditional inside of the original loop. This gives you tighter control than break; which can cause havoc elsewhere on a complicated page.

Example:

// Setup a counter
$ImageCounter = 0;

// Increment through repeater fields
while ( condition ):
  $ImageCounter++;

   // Only print the first while instance
   if ($ImageCounter == 1) {
    echo 'It worked just once';
   }

// Close while statement
endwhile;

Catch browser's "zoom" event in JavaScript

I'am replying to a 3 year old link but I guess here's a more acceptable answer,

Create .css file as,

@media screen and (max-width: 1000px) 
{
       // things you want to trigger when the screen is zoomed
}

EG:-

@media screen and (max-width: 1000px) 
{
    .classname
    {
          font-size:10px;
    }
}

The above code makes the size of the font '10px' when the screen is zoomed to approximately 125%. You can check for different zoom level by changing the value of '1000px'.

Select multiple records based on list of Id's with linq

You can use Contains() for that. It will feel a little backwards when you're really trying to produce an IN clause, but this should do it:

var userProfiles = _dataContext.UserProfile
                               .Where(t => idList.Contains(t.Id));

I'm also assuming that each UserProfile record is going to have an int Id field. If that's not the case you'll have to adjust accordingly.

Add Items to Columns in a WPF ListView

Solution With Less XAML and More C#

If you define the ListView in XAML:

<ListView x:Name="listView"/>

Then you can add columns and populate it in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Add columns
    var gridView = new GridView();
    this.listView.View = gridView;
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Id", DisplayMemberBinding = new Binding("Id") });
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Name", DisplayMemberBinding = new Binding("Name") });

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

Solution With More XAML and less C#

However, it's easier to define the columns in XAML (inside the ListView definition):

<ListView x:Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
        </GridView>
    </ListView.View>
</ListView>

And then just populate the list in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

MyItem Definition

MyItem is defined like this:

public class MyItem
{
    public int Id { get; set; }

    public string Name { get; set; }
}

How to write unit testing for Angular / TypeScript for private methods with Jasmine

The answer by Aaron is the best and is working for me :) I would vote it up but sadly I can't (missing reputation).

I've to say testing private methods is the only way to use them and have clean code on the other side.

For example:

class Something {
  save(){
    const data = this.getAllUserData()
    if (this.validate(data))
      this.sendRequest(data)
  }
  private getAllUserData () {...}
  private validate(data) {...}
  private sendRequest(data) {...}
}

It' makes a lot of sense to not test all these methods at once because we would need to mock out those private methods, which we can't mock out because we can't access them. This means we need a lot of configuration for a unit test to test this as a whole.

This said the best way to test the method above with all dependencies is an end to end test, because here an integration test is needed, but the E2E test won't help you if you are practicing TDD (Test Driven Development), but testing any method will.

Simple Android RecyclerView example

Here's a much newer Kotlin solution for this which is much simpler than many of the answers written here, it uses anonymous class.

val items = mutableListOf<String>()

inner class ItemHolder(view: View): RecyclerView.ViewHolder(view) {
    var textField: TextView = view.findViewById(android.R.id.text1) as TextView
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    rvitems.layoutManager = LinearLayoutManager(context)
    rvitems.adapter = object : RecyclerView.Adapter<ItemHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
            return ItemHolder(LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_1, parent, false))
        }

        override fun getItemCount(): Int {
            return items.size
        }

        override fun onBindViewHolder(holder: ItemHolder, position: Int) {
            holder.textField.text = items[position]
            holder.textField.setOnClickListener {
                Toast.makeText(context, "Clicked $position", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

I took the liberty to use android.R.layout.simple_list_item_1 as it's simpler. I wanted to simplify it even further and put ItemHolder as an inner class but couldn't quite figure out how to reference it in a type in the outer class parameter.

what does -zxvf mean in tar -zxvf <filename>?

  • z means (un)z_ip.
  • x means ex_tract files from the archive.
  • v means print the filenames v_erbosely.
  • f means the following argument is a f_ilename.

For more details, see tar's man page.

Rails: How can I rename a database column in a Ruby on Rails migration?

You have two ways to do this:

  1. In this type it automatically runs the reverse code of it, when rollback.

    def change
      rename_column :table_name, :old_column_name, :new_column_name
    end
    
  2. To this type, it runs the up method when rake db:migrate and runs the down method when rake db:rollback:

    def self.up
      rename_column :table_name, :old_column_name, :new_column_name
    end
    
    def self.down
      rename_column :table_name,:new_column_name,:old_column_name
    end
    

How to expand/collapse a diff sections in Vimdiff?

Aside from the ones you mention, I only use frequently when diffing the following:

  • :diffupdate :diffu -> recalculate the diff, useful when after making several changes vim's isn't showing minimal changes anymore. Note that it only works if the files have been modified inside vimdiff. Otherwise, use:
    • :e to reload the files if they have been modified outside of vimdiff.
  • :set noscrollbind -> temporarily disable simultaneous scrolling on both buffers, reenable by :set scrollbind and scrolling.

Most of what you asked for is folding: vim user manual's chapter on folding. Outside of diffs I sometime use:

  • zo -> open fold.
  • zc -> close fold.

But you'll probably be better served by:

  • zr -> reducing folding level.
  • zm -> one more folding level, please.

or even:

  • zR -> Reduce completely the folding, I said!.
  • zM -> fold Most!.

The other thing you asked for, use n lines of folding, can be found at the vim reference manual section on options, via the section on diff:

  • set diffopt=<TAB>, then update or add context:n.

You should also take a look at the user manual section on diff.

How do I print part of a rendered HTML page in JavaScript?

Try this JavaScript code:

function printout() {

    var newWindow = window.open();
    newWindow.document.write(document.getElementById("output").innerHTML);
    newWindow.print();
}

What is the "continue" keyword and how does it work in Java?

Generally, I see continue (and break) as a warning that the code might use some refactoring, especially if the while or for loop declaration isn't immediately in sight. The same is true for return in the middle of a method, but for a slightly different reason.

As others have already said, continue moves along to the next iteration of the loop, while break moves out of the enclosing loop.

These can be maintenance timebombs because there is no immediate link between the continue/break and the loop it is continuing/breaking other than context; add an inner loop or move the "guts" of the loop into a separate method and you have a hidden effect of the continue/break failing.

IMHO, it's best to use them as a measure of last resort, and then to make sure their use is grouped together tightly at the start or end of the loop so that the next developer can see the "bounds" of the loop in one screen.

continue, break, and return (other than the One True Return at the end of your method) all fall into the general category of "hidden GOTOs". They place loop and function control in unexpected places, which then eventually causes bugs.

.gitignore all the .DS_Store files in every folder and subfolder

I think the problem you're having is that in some earlier commit, you've accidentally added .DS_Store files to the repository. Of course, once a file is tracked in your repository, it will continue to be tracked even if it matches an entry in an applicable .gitignore file.

You have to manually remove the .DS_Store files that were added to your repository. You can use

git rm --cached .DS_Store

Once removed, git should ignore it. You should only need the following line in your root .gitignore file: .DS_Store. Don't forget the period!

git rm --cached .DS_Store

removes only .DS_Store from the current directory. You can use

find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch

to remove all .DS_Stores from the repository.

Felt tip: Since you probably never want to include .DS_Store files, make a global rule. First, make a global .gitignore file somewhere, e.g.

echo .DS_Store >> ~/.gitignore_global

Now tell git to use it for all repositories:

git config --global core.excludesfile ~/.gitignore_global

This page helped me answer your question.

How to check if a string contains an element from a list in Python

Use a generator together with any, which short-circuits on the first True:

if any(ext in url_string for ext in extensionsToCheck):
    print(url_string)

EDIT: I see this answer has been accepted by OP. Though my solution may be "good enough" solution to his particular problem, and is a good general way to check if any strings in a list are found in another string, keep in mind that this is all that this solution does. It does not care WHERE the string is found e.g. in the ending of the string. If this is important, as is often the case with urls, you should look to the answer of @Wladimir Palant, or you risk getting false positives.

How to Copy Text to Clip Board in Android?

For copy any text in Android:

            TextView text = findViewById(R.id.text_id);
            ImageView icons = findViewById(R.id.copy_icon);

            icons.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clipData = ClipData.newPlainText("text whatever you want", text.getText().toString());
                    clipboardManager.setPrimaryClip(clipData);

                    Toast.makeText(context, "Text Copied", Toast.LENGTH_SHORT).show();
                }
            });

Changing CSS Values with Javascript

You can get the "computed" styles of any element.

IE uses something called "currentStyle", Firefox (and I assume other "standard compliant" browsers) uses "defaultView.getComputedStyle".

You'll need to write a cross browser function to do this, or use a good Javascript framework like prototype or jQuery (search for "getStyle" in the prototype javascript file, and "curCss" in the jquery javascript file).

That said if you need the height or width you should probably use element.offsetHeight and element.offsetWidth.

The value returned is Null, so if I have Javascript that needs to know the width of something to do some logic (I increase the width by 1%, not to a specific value)

Mind, if you add an inline style to the element in question, it can act as the "default" value and will be readable by Javascript on page load, since it is the element's inline style property:

<div style="width:50%">....</div>

Checking if any elements in one list are in another

Your original approach can work with a list comprehension:

def listCompare():
  list1 = [1, 2, 3, 4, 5]
  list2 = [5, 6, 7, 8, 9]
  if [item for item in list1 if item in list2]:
    print("Number was found")
  else:
    print("Number not in list")

How to extract a substring using regex

you can use this i use while loop to store all matches substring in the array if you use

if (matcher.find()) { System.out.println(matcher.group(1)); }

you will get on matches substring so you can use this to get all matches substring

Matcher m = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+").matcher(text);
   // Matcher  mat = pattern.matcher(text);
    ArrayList<String>matchesEmail = new ArrayList<>();
        while (m.find()){
            String s = m.group();
            if(!matchesEmail.contains(s))
                matchesEmail.add(s);
        }

    Log.d(TAG, "emails: "+matchesEmail);

Setting focus on an HTML input box on page load

You could also use:

<body onload="focusOnInput()">
    <form name="passwordForm" action="verify.php" method="post">
        <input name="passwordInput" type="password" />
    </form>
</body>

And then in your JavaScript:

function focusOnInput() {
    document.forms["passwordForm"]["passwordInput"].focus();
}

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

Why does ++[[]][+[]]+[+[]] return the string "10"?

+[] evaluates to 0 [...] then summing (+ operation) it with anything converts array content to its string representation consisting of elements joined with comma.

Anything other like taking index of array (have grater priority than + operation) is ordinal and is nothing interesting.

CSS: How can I set image size relative to parent height?

If all your trying to do is fill the div this might help someone else, if aspect ratio is not important, is responsive.

.img-fill > img {
  min-height: 100%;
  min-width: 100%;  
}

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

I had similar problem against 2 different databases (DB2 and SQL), finally I solved it by using CAST in the source query from DB2. I also take advantage of using a query by adapting the source column to varchar and avoiding the useless blank spaces:

CAST(RTRIM(LTRIM(COLUMN_NAME)) AS VARCHAR(60) CCSID UNICODE 
   FOR SBCS DATA)  COLUMN_NAME

The important issue here is the CCSID conversion.

Git copy changes from one branch to another

git checkout BranchB
git merge BranchA
git push origin BranchB

This is all if you intend to not merge your changes back to master. Generally it is a good practice to merge all your changes back to master, and create new branches off of that.

Also, after the merge command, you will have some conflicts, which you will have to edit manually and fix.

Make sure you are in the branch where you want to copy all the changes to. git merge will take the branch you specify and merge it with the branch you are currently in.

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

As some suggested here, replacing utf8mb4 with utf8 will help you resolve the issue. IMHO, I used sed to find and replace them to avoid losing data. In addition, opening a large file into any graphical editor is potential pain. My MySQL data grows up 2 GB. The ultimate command is

sed 's/utf8mb4_unicode_520_ci/utf8_unicode_ci/g' original-mysql-data.sql > updated-mysql-data.sql
sed 's/utf8mb4/utf8/g' original-mysql-data.sql > updated-mysql-data.sql

Done!

Why does multiplication repeats the number several times?

In [58]: price = 1 *9
In [59]: price
Out[59]: 9

Load arrayList data into JTable

I created an arrayList from it and I somehow can't find a way to store this information into a JTable.

The DefaultTableModel doesn't support displaying custom Objects stored in an ArrayList. You need to create a custom TableModel.

You can check out the Bean Table Model. It is a reusable class that will use reflection to find all the data in your FootballClub class and display in a JTable.

Or, you can extend the Row Table Model found in the above link to make is easier to create your own custom TableModel by implementing a few methods. The JButtomTableModel.java source code give a complete example of how you can do this.

How can I find out a file's MIME type (Content-Type)?

file --mime works, but not --mime-type. at least for my RHEL 5.

Laravel Eloquent Sum of relation's column

I tried doing something similar, which took me a lot of time before I could figure out the collect() function. So you can have something this way:

collect($items)->sum('amount');

This will give you the sum total of all the items.

Formatting doubles for output in C#

I found this quick fix.

    double i = 10 * 0.69;
    System.Diagnostics.Debug.WriteLine(i);


    String s = String.Format("{0:F20}", i).Substring(0,20);
    System.Diagnostics.Debug.WriteLine(s + " " +s.Length );

How to center a component in Material-UI and make it responsive?

The @Nadun's version did not work for me, sizing wasn't working well. Removed the direction="column" or changing it to row, helps with building vertical login forms with responsive sizing.

<Grid
  container
  spacing={0}
  alignItems="center"
  justify="center"
  style={{ minHeight: "100vh" }}
>
  <Grid item xs={6}></Grid>
</Grid>;

How to initialize a private static const map in C++?

I often use this pattern and recommend you to use it as well:

class MyMap : public std::map<int, int>
{
public:
    MyMap()
    {
        //either
        insert(make_pair(1, 2));
        insert(make_pair(3, 4));
        insert(make_pair(5, 6));
        //or
        (*this)[1] = 2;
        (*this)[3] = 4;
        (*this)[5] = 6;
    }
} const static my_map;

Sure it is not very readable, but without other libs it is best we can do. Also there won't be any redundant operations like copying from one map to another like in your attempt.

This is even more useful inside of functions: Instead of:

void foo()
{
   static bool initComplete = false;
   static Map map;
   if (!initComplete)
   {
      initComplete = true;
      map= ...;
   }
}

Use the following:

void bar()
{
    struct MyMap : Map
    {
      MyMap()
      {
         ...
      }
    } static mymap;
}

Not only you don't need here to deal with boolean variable anymore, you won't have hidden global variable that is checked if initializer of static variable inside function was already called.

Use the auto keyword in C++ STL

If you want a code that is readable by all programmers (c++, java, and others) use the original old form instead of cryptographic new features

atp::ta::DataDrawArrayInfo* ddai;
for(size_t i = 0; i < m_dataDraw->m_dataDrawArrayInfoList.size(); i++) {
    ddai = m_dataDraw->m_dataDrawArrayInfoList[i];
    //...
}

How to extract epoch from LocalDate and LocalDateTime?

This is one way without using time a zone:

LocalDateTime now = LocalDateTime.now();
long epoch = (now.getLong(ChronoField.EPOCH_DAY) * 86400000) + now.getLong(ChronoField.MILLI_OF_DAY);

Oracle insert if not exists statement

insert into OPT (email, campaign_id) 
select '[email protected]',100
from dual
where not exists(select * 
                 from OPT 
                 where (email ='[email protected]' and campaign_id =100));

Change Timezone in Lumen or Laravel 5

You just have to edit de app.php file in config directory Just find next lines

/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/

'timezone' => 'UTC',

And.. chage it for:

'timezone' => 'Europe/Paris',

HTML image bottom alignment inside DIV container

Flexboxes can accomplish this by using align-items: flex-end; with display: flex; or display: inline-flex;

div#imageContainer {
    height: 160px;  
    align-items: flex-end;
    display: flex;

    /* This is the default value, so you only need to explicitly set it if it's already being set to something else elsewhere. */
    /*flex-direction: row;*/
}

JSFiddle example

CSS-Tricks has a good guide for flexboxes

Node.js – events js 72 throw er unhandled 'error' event

I always do the following whenever I get such error:

// remove node_modules/
rm -rf node_modules/
// install node_modules/ again
npm install // or, yarn

and then start the project

npm start //or, yarn start

It works fine after re-installing node_modules. But I don't know if it's good practice.

Proper way to concatenate variable strings

As simple as joining lists in python itself.

ansible -m debug -a msg="{{ '-'.join(('list', 'joined', 'together')) }}" localhost

localhost | SUCCESS => {
  "msg": "list-joined-together" }

Works the same way using variables:

ansible -m debug -a msg="{{ '-'.join((var1, var2, var3)) }}" localhost

PostgreSQL 'NOT IN' and subquery

When using NOT IN you should ensure that none of the values are NULL:

SELECT mac, creation_date 
FROM logs 
WHERE logs_type_id=11
AND mac NOT IN (
    SELECT mac
    FROM consols
    WHERE mac IS NOT NULL -- add this
)

Embed Youtube video inside an Android app

Pretty simple: Just put it inside a static method.

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(linkYouTube)));

How to construct a std::string from a std::vector<char>?

I think you can just do

std::string s( MyVector.begin(), MyVector.end() );

where MyVector is your std::vector.

No assembly found containing an OwinStartupAttribute Error

Add below code to your web.config file then run the project...

    <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
    </dependentAssembly>
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
    </dependentAssembly>
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
    </dependentAssembly>
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
    </dependentAssembly>
    </runtime>

Difference between JE/JNE and JZ/JNZ

  je : Jump if equal:

  399  3fb:   64 48 33 0c 25 28 00    xor    %fs:0x28,%rcx
  400  402:   00 00
  401  404:   74 05                   je     40b <sims_get_counter+0x51>

npm not working - "read ECONNRESET"

I had the same problem when trying to run npm on system emulated in Oracle VirtualBox. I resolved it by adding Google DNS address in Network Adapter properties.

Network Adapter properties > IPv4 properties > Preferred DNS address: 8.8.8.8.

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

Basically you have two ways to iterate over all elements:

1. Using recursion (the most common way I think):

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
        .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("document.xml"));
    doSomething(document.getDocumentElement());
}

public static void doSomething(Node node) {
    // do something with the current node instead of System.out
    System.out.println(node.getNodeName());

    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node currentNode = nodeList.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            //calls this method for all the children which is Element
            doSomething(currentNode);
        }
    }
}

2. Avoiding recursion using getElementsByTagName() method with * as parameter:

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
            .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("document.xml"));

    NodeList nodeList = document.getElementsByTagName("*");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // do something with the current element
            System.out.println(node.getNodeName());
        }
    }
}

I think these ways are both efficient.
Hope this helps.

TypeError: $(...).modal is not a function with bootstrap Modal

After linking up your jquery and bootstrap write your code just below the Script tags of jquery and bootstrap.

_x000D_
_x000D_
$(document).ready(function($) {_x000D_
  $("#div").on("click", "a", function(event) {_x000D_
    event.preventDefault();_x000D_
    jQuery.noConflict();_x000D_
    $('#myModal').modal('show');_x000D_
_x000D_
  });_x000D_
});
_x000D_
<!-- jQuery library -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
_x000D_
<!-- Latest compiled JavaScript -->_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
_x000D_
_x000D_
_x000D_

Can't build create-react-app project with custom PUBLIC_URL

As documented here create-react-app will only import environment variables beginning with REACT_APP_, so the PUBLIC_URL, I believe, as mentioned by @redbmk, comes from the homepage setting in the package.json file.

org.hibernate.MappingException: Could not determine type for: java.util.Set

Not saying your mapping is correct or wrong but I think hibernate wants a instance of the set where you declare the field.

@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
//@ElementCollection(targetClass=Role.class)
@Column(name = "ROLE_ID")
private Set<Role> roles = new HashSet<Role>();

HTML input - name vs. id

name is used for form submission in DOM (Document Object Model).

ID is used to unique name of html controls in DOM specially for Javascript & CSS

How to pass command line arguments to a rake task

I've found the answer from these two websites: Net Maniac and Aimred.

You need to have version > 0.8 of rake to use this technique

The normal rake task description is this:

desc 'Task Description'
task :task_name => [:depends_on_taskA, :depends_on_taskB] do
  #interesting things
end

To pass arguments, do three things:

  1. Add the argument names after the task name, separated by commas.
  2. Put the dependencies at the end using :needs => [...]
  3. Place |t, args| after the do. (t is the object for this task)

To access the arguments in the script, use args.arg_name

desc 'Takes arguments task'
task :task_name, :display_value, :display_times, :needs => [:depends_on_taskA, :depends_on_taskB] do |t, args|
  args.display_times.to_i.times do
    puts args.display_value
  end
end

To call this task from the command line, pass it the arguments in []s

rake task_name['Hello',4]

will output

Hello
Hello
Hello
Hello

and if you want to call this task from another task, and pass it arguments, use invoke

task :caller do
  puts 'In Caller'
  Rake::Task[:task_name].invoke('hi',2)
end

then the command

rake caller

will output

In Caller
hi
hi

I haven't found a way to pass arguments as part of a dependency, as the following code breaks:

task :caller => :task_name['hi',2]' do
   puts 'In Caller'
end

Pip freeze vs. pip list

To answer the second part of this question, the two packages shown in pip list but not pip freeze are setuptools (which is easy_install) and pip itself.

It looks like pip freeze just doesn't list packages that pip itself depends on. You may use the --all flag to show also those packages.

From the documentation:

--all

Do not skip these packages in the output: pip, setuptools, distribute, wheel

how to increase the limit for max.print in R

set the function options(max.print=10000) in top of your program. since you want intialize this before it works. It is working for me.

Running powershell script within python script, how to make python print the powershell output while it is running

  1. Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx

    Set-ExecutionPolicy RemoteSigned
    
  2. Run this python script on your powershell script helloworld.py:

    # -*- coding: iso-8859-1 -*-
    import subprocess, sys
    
    p = subprocess.Popen(["powershell.exe", 
                  "C:\\Users\\USER\\Desktop\\helloworld.ps1"], 
                  stdout=sys.stdout)
    p.communicate()
    

This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.

C:\Users\MacEwin\Desktop>python helloworld.py
Hello World

What Does This Mean in PHP -> or =>

=> is used in associative array key value assignment. Take a look at:

http://php.net/manual/en/language.types.array.php.

-> is used to access an object method or property. Example: $obj->method().

C# with MySQL INSERT parameters

You may use AddWithValue method like:

string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "INSERT INTO room(person,address) VALUES(@person, @address)";
comm.Parameters.AddWithValue("@person", "Myname");
comm.Parameters.AddWithValue("@address", "Myaddress");
comm.ExecuteNonQuery();
conn.Close();

OR

Try with ? instead of @, like:

string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "INSERT INTO room(person,address) VALUES(?person, ?address)";
comm.Parameters.Add("?person", "Myname");
comm.Parameters.Add("?address", "Myaddress");
comm.ExecuteNonQuery();
conn.Close();

Hope it helps...

Drag and drop elements from list into separate blocks

I wrote some test code to check JQueryUI drag/drop. The example shows how to drag an element from a container and drop it to another container.

Markup-

<div class="row">
    <div class="col-xs-3">
      <div class="panel panel-default">
        <div class="panel-heading">
          <h1 class="panel-title">Panel 1</h1>
        </div>
        <div id="container1" class="panel-body box-container">
          <div itemid="itm-1" class="btn btn-default box-item">Item 1</div>
          <div itemid="itm-2" class="btn btn-default box-item">Item 2</div>
          <div itemid="itm-3" class="btn btn-default box-item">Item 3</div>
          <div itemid="itm-4" class="btn btn-default box-item">Item 4</div>
          <div itemid="itm-5" class="btn btn-default box-item">Item 5</div>
        </div>
      </div>
    </div>
    <div class="col-xs-3">
      <div class="panel panel-default">
        <div class="panel-heading">
          <h1 class="panel-title">Panel 2</h1>
        </div>
        <div id="container2" class="panel-body box-container"></div>
      </div>
    </div>
  </div>

JQuery codes-

$(document).ready(function() {

$('.box-item').draggable({
    cursor: 'move',
    helper: "clone"
});

$("#container1").droppable({
  drop: function(event, ui) {
    var itemid = $(event.originalEvent.toElement).attr("itemid");
    $('.box-item').each(function() {
      if ($(this).attr("itemid") === itemid) {
        $(this).appendTo("#container1");
      }
    });
  }
});

$("#container2").droppable({
  drop: function(event, ui) {
    var itemid = $(event.originalEvent.toElement).attr("itemid");
    $('.box-item').each(function() {
      if ($(this).attr("itemid") === itemid) {
        $(this).appendTo("#container2");
      }
    });
  }
});

});

CSS-

.box-container {
    height: 200px;
}

.box-item {
    width: 100%;
    z-index: 1000
}

Check the plunker JQuery Drag Drop

Adjust icon size of Floating action button (fab)

Try to use app:maxImageSize="56dp" instead of the above answers after you update your support library to v28.0.0

How to restore to a different database in sql server?

It is actually a bit simpler than restoring to the same server. Basically, you just walk through the "Restore Database" options. Here is a tutorial for you:

http://www.techrepublic.com/blog/window-on-windows/how-do-i-restore-a-sql-server-database-to-a-new-server/454

Especially since this is a non-production restore, you can feel comfortable just trying it out without worrying about the details too much. Just put your SQL files where you want them on your new server and give it whatever name you want and you are good to go.

What is the difference between declarations, providers, and import in NgModule?

Adding a quick cheat sheet that may help after the long break with Angular:


DECLARATIONS

Example:

declarations: [AppComponent]

What can we inject here? Components, pipes, directives


IMPORTS

Example:

imports: [BrowserModule, AppRoutingModule]

What can we inject here? other modules


PROVIDERS

Example:

providers: [UserService]

What can we inject here? services


BOOTSTRAP

Example:

bootstrap: [AppComponent]

What can we inject here? the main component that will be generated by this module (top parent node for a component tree)


ENTRY COMPONENTS

Example:

entryComponents: [PopupComponent]

What can we inject here? dynamically generated components (for instance by using ViewContainerRef.createComponent())


EXPORT

Example:

export: [TextDirective, PopupComponent, BrowserModule]

What can we inject here? components, directives, modules or pipes that we would like to have access to them in another module (after importing this module)

PHP: Return all dates between two dates in an array

function getWeekdayDatesFrom($format, $start_date_epoch, $end_date_epoch, $range) {

    $dates_arr = array();

    if( ! $range) {
        $range = round(abs($start_date_epoch-$end_date_epoch)/86400) + 1;
    } else {
        $range = $range + 1; //end date inclusive
    }

    $current_date_epoch = $start_date_epoch;

    for($i = 1; $i <= $range; $i+1) {

        $d = date('N',  $current_date_epoch);

        if($d <= 5) { // not sat or sun
            $dates_arr[] = "'".date($format, $current_date_epoch)."'";
        }

        $next_day_epoch = strtotime('+'.$i.'day', $start_date_epoch);
        $i++;
        $current_date_epoch = $next_day_epoch;

    }

    return $dates_arr;
} 

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

I know this was for 6 months, however the answer shows in google for "adding months in python" if you are adding one month:

import calendar

date = datetime.date.today()    //Or your date

datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1])

this would count the days in the current month and add them to the current date, using 365/12 would ad 1/12 of a year can causes issues for short / long months if your iterating over the date.

Scala: write string to file in one statement

Here is a concise one-liner using reflect.io.file, this works with Scala 2.12:

reflect.io.File("filename").writeAll("hello world")

Alternatively, if you want to use the Java libraries you can do this hack:

Some(new PrintWriter("filename")).foreach{p => p.write("hello world"); p.close}

How do you sort a dictionary by value?

Given you have a dictionary you can sort them directly on values using below one liner:

var x = (from c in dict orderby c.Value.Order ascending select c).ToDictionary(c => c.Key, c=>c.Value);

How can I tell Moq to return a Task?

You only need to add .Returns(Task.FromResult(0)); after the Callback.

Example:

mock.Setup(arg => arg.DoSomethingAsync())
    .Callback(() => { <my code here> })
    .Returns(Task.FromResult(0));

Get domain name

I know this is old. I just wanted to dump this here for anyone that was looking for an answer to getting a domain name. This is in coordination with Peter's answer. There "is" a bug as stated by Rich. But, you can always make a simple workaround for that. The way I can tell if they are still on the domain or not is by pinging the domain name. If it responds, continue on with whatever it was that I needed the domain for. If it fails, I drop out and go into "offline" mode. Simple string method.

 string GetDomainName()
    {
        string _domain = IPGlobalProperties.GetIPGlobalProperties().DomainName;

        Ping ping = new Ping();

        try
        {
            PingReply reply = ping.Send(_domain);

            if (reply.Status == IPStatus.Success)
            {
                return _domain;
            }
            else
            {
                return reply.Status.ToString();
            }
        }
        catch (PingException pExp)
        {
            if (pExp.InnerException.ToString() == "No such host is known")
            {
                return "Network not detected!";
            }

            return "Ping Exception";
        }
    }

Syntax for an If statement using a boolean

You can change the value of a bool all you want. As for an if:

if randombool == True:

works, but you can also use:

if randombool:

If you want to test whether something is false you can use:

if randombool == False

but you can also use:

if not randombool:

How to force reloading php.ini file?

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

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

To restart the service:

Note: prepend sudo if not root

Using SysV Init scripts directly:

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

Using service wrapper script

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

Using Upstart (e.g. ubuntu):

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

Using systemd (newer servers):

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

Or whatever the equivalent is on your system.

The above commands taken directly from this server fault answer

How to place div side by side

You can use CSS grid to achieve this, this is the long-hand version for the purposes of illustration:

_x000D_
_x000D_
div.container {_x000D_
    display: grid;_x000D_
    grid-template-columns: 220px 20px auto;_x000D_
    grid-template-rows: auto;_x000D_
}_x000D_
_x000D_
div.left {_x000D_
    grid-column-start: 1;_x000D_
    grid-column-end: 2;_x000D_
    grid-row-start: row1-start_x000D_
    grid-row-end: 3;_x000D_
    background-color: Aqua;_x000D_
}_x000D_
_x000D_
div.right {_x000D_
    grid-column-start: 3;_x000D_
    grid-column-end: 4;_x000D_
    grid-row-start: 1;_x000D_
    grid-row-end; 1;_x000D_
    background-color: Silver;_x000D_
}_x000D_
_x000D_
div.below {_x000D_
    grid-column-start: 1;_x000D_
    grid-column-end: 4;_x000D_
    grid-row-start: 2;_x000D_
    grid-row-end; 2;_x000D_
}
_x000D_
<div class="container">_x000D_
    <div class="left">Left</div>_x000D_
    <div class="right">Right</div>_x000D_
    <div class="below">Below</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or the more traditional method using float and margin.

I have included a background colour in this example to help show where things are - and also what to do with content below the floated-area.

Don't put your styles inline in real life, extract them into a style sheet.

_x000D_
_x000D_
div.left {_x000D_
    width: 200px;_x000D_
    float: left;_x000D_
    background-color: Aqua;_x000D_
}_x000D_
_x000D_
div.right {_x000D_
    margin-left: 220px;_x000D_
    background-color: Silver;_x000D_
}_x000D_
_x000D_
div.clear {_x000D_
    clear: both;_x000D_
}
_x000D_
    <div class="left"> Left </div>_x000D_
    <div class="right"> Right </div>_x000D_
    <div class="clear">Below</div>
_x000D_
_x000D_
_x000D_

<div style="width: 200px; float: left; background-color: Aqua;"> Left </div>
<div style="margin-left: 220px; background-color: Silver;"> Right </div>
<div style="clear: both;">Below</div>

Writing a dictionary to a csv file with one line for every 'key: value'

Can you just do:

for key in mydict.keys():
    f.write(str(key) + ":" + str(mydict[key]) + ",");

So that you can have

key_1: value_1, key_2: value_2

Render Content Dynamically from an array map function in React Native

Don't forget to return the mapped array , like:

lapsList() {

    return this.state.laps.map((data) => {
      return (
        <View><Text>{data.time}</Text></View>
      )
    })

}

Reference for the map() method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Importing Maven project into Eclipse

Maven have a Eclipse plugin and Eclipse have a Maven plugin we are going to discus those things.when we using maven with those command line stuffs and etc when we are going through eclipse we don't want to that command line codes it have very much helpful, Maven and eclipse giving good integration ,they will work very well together thanks for that plugins

Step 1: Go to the maven project. Here my project is FirstApp.(Example my project is FirstApp)

There you can see one pom.xml file, now what we want is to generate an eclipse project using that pom.xml.

Step 2: Use mvn eclipse:eclipse command

Step 3: Verify the project

after execution of this command notice that two new files have been created

Note:- both these files are created for Eclipse. When you open those files you will notice a "M2_REPO" class variable is generate. You want to add that class path in eclipse, otherwise eclipse will show a error.

Step 4: Importing eclipse project

File -> Import -> General -> Existing Projects in Workspace -> Select root directory -> Done

More details here

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

It's not really a bug, just a difference in implantation by the browser vendors.

As a rule avoid browser sniffing. There is a nifty jQuery fix which is hinted at in the answers.

This is what works for me: $('html:not(:animated),body:not(:animated)').scrollTop()

Converting EditText to int? (Android)

In Kotlin, you can do this.

val editText1 = findViewById(R.id.editText)
val intNum = editText1.text.toString().toInt()

How do I get the path and name of the file that is currently executing?

This should work:

import os,sys
filename=os.path.basename(os.path.realpath(sys.argv[0]))
dirname=os.path.dirname(os.path.realpath(sys.argv[0]))

What is log4j's default log file dumping path

To redirect your logs output to a file, you need to use the FileAppender and need to define other file details in your log4j.properties/xml file. Here is a sample properties file for the same:

# Root logger option
log4j.rootLogger=INFO, file

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\loging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Follow this tutorial to learn more about log4j usage:

http://www.mkyong.com/logging/log4j-log4j-properties-examples/

How to obtain the location of cacerts of the default java installation?

Under Linux, to find the location of $JAVA_HOME:

readlink -f /usr/bin/java | sed "s:bin/java::"

the cacerts are under lib/security/cacerts:

$(readlink -f /usr/bin/java | sed "s:bin/java::")lib/security/cacerts

Under mac OS X , to find $JAVA_HOME run:

/usr/libexec/java_home

the cacerts are under Home/lib/security/cacerts:

$(/usr/libexec/java_home)/lib/security/cacerts

UPDATE (OS X with JDK)

above code was tested on computer without JDK installed. With JDK installed, as pR0Ps said, it's at

$(/usr/libexec/java_home)/jre/lib/security/cacerts

Which passwordchar shows a black dot (•) in a winforms textbox?

Instead of copy/paste a unicode character or setting it in the code-behind you could also change the properties of the TextBox. Simply set "UseSystemPasswordChar" to True and everytghing will be done for you by the Framework. Or in code-behind:

this.txtPassword.UseSystemPasswordChar = true;

Inheritance with base class constructor with parameters

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}

Table border left and bottom

Give a class .border-lb and give this CSS

.border-lb {border: 1px solid #ccc; border-width: 0 0 1px 1px;}

And the HTML

<table width="770">
  <tr>
    <td class="border-lb">picture (border only to the left and bottom ) </td>
    <td>text</td>
  </tr>
  <tr>
    <td>text</td>
    <td class="border-lb">picture (border only to the left and bottom) </td>
  </tr>
</table>

Screenshot

Fiddle: http://jsfiddle.net/FXMVL/

Python sys.argv lists and indexes

In a nutshell, sys.argv is a list of the words that appear in the command used to run the program. The first word (first element of the list) is the name of the program, and the rest of the elements of the list are any arguments provided. In most computer languages (including Python), lists are indexed from zero, meaning that the first element in the list (in this case, the program name) is sys.argv[0], and the second element (first argument, if there is one) is sys.argv[1], etc.

The test len(sys.argv) >= 2 simply checks wither the list has a length greater than or equal to 2, which will be the case if there was at least one argument provided to the program.

window.open target _self v window.location.href?

Hopefully someone else is saved by reading this.

We encountered an issue with webkit based browsers doing:

window.open("webpage.htm", "_self");

The browser would lockup and die if we had too many DOM nodes. When we switched our code to following the accepted answer of:

location.href = "webpage.html";

all was good. It took us awhile to figure out what was causing the issue, since it wasn't obvious what made our page periodically fail to load.

disable a hyperlink using jQuery

I know it's an old question but it seems unsolved still. Follows my solution...

Simply add this global handler:

$('a').click(function()
{
     return ($(this).attr('disabled')) ? false : true;
});

Here's a quick demo: http://jsbin.com/akihik/3

you can even add a bit of css to give a different style to all the links with the disabled attribute.

e.g

a[disabled]
{
    color: grey; 
}

Anyway it seems that the disabled attribute is not valid for a tags. If you prefer to follow the w3c specs you can easily adopt an html5 compliant data-disabled attribute. In this case you have to modify the previous snippet and use $(this).data('disabled').

Fastest way to list all primes below N

I tested some unutbu's functions, i computed it with hungred millions number

The winners are the functions that use numpy library,

Note: It would also interesting make a memory utilization test :)

Computation time result

Sample code

Complete code on my github repository

#!/usr/bin/env python

import lib
import timeit
import sys
import math
import datetime

import prettyplotlib as ppl
import numpy as np

import matplotlib.pyplot as plt
from prettyplotlib import brewer2mpl

primenumbers_gen = [
    'sieveOfEratosthenes',
    'ambi_sieve',
    'ambi_sieve_plain',
    'sundaram3',
    'sieve_wheel_30',
    'primesfrom3to',
    'primesfrom2to',
    'rwh_primes',
    'rwh_primes1',
    'rwh_primes2',
]

def human_format(num):
    # https://stackoverflow.com/questions/579310/formatting-long-numbers-as-strings-in-python?answertab=active#tab-top
    magnitude = 0
    while abs(num) >= 1000:
        magnitude += 1
        num /= 1000.0
    # add more suffixes if you need them
    return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])


if __name__=='__main__':

    # Vars
    n = 10000000 # number itereration generator
    nbcol = 5 # For decompose prime number generator
    nb_benchloop = 3 # Eliminate false positive value during the test (bench average time)
    datetimeformat = '%Y-%m-%d %H:%M:%S.%f'
    config = 'from __main__ import n; import lib'
    primenumbers_gen = {
        'sieveOfEratosthenes': {'color': 'b'},
        'ambi_sieve': {'color': 'b'},
        'ambi_sieve_plain': {'color': 'b'},
         'sundaram3': {'color': 'b'},
        'sieve_wheel_30': {'color': 'b'},
# # #        'primesfrom2to': {'color': 'b'},
        'primesfrom3to': {'color': 'b'},
        # 'rwh_primes': {'color': 'b'},
        # 'rwh_primes1': {'color': 'b'},
        'rwh_primes2': {'color': 'b'},
    }


    # Get n in command line
    if len(sys.argv)>1:
        n = int(sys.argv[1])

    step = int(math.ceil(n / float(nbcol)))
    nbs = np.array([i * step for i in range(1, int(nbcol) + 1)])
    set2 = brewer2mpl.get_map('Paired', 'qualitative', 12).mpl_colors

    print datetime.datetime.now().strftime(datetimeformat)
    print("Compute prime number to %(n)s" % locals())
    print("")

    results = dict()
    for pgen in primenumbers_gen:
        results[pgen] = dict()
        benchtimes = list()
        for n in nbs:
            t = timeit.Timer("lib.%(pgen)s(n)" % locals(), setup=config)
            execute_times = t.repeat(repeat=nb_benchloop,number=1)
            benchtime = np.mean(execute_times)
            benchtimes.append(benchtime)
        results[pgen] = {'benchtimes':np.array(benchtimes)}

fig, ax = plt.subplots(1)
plt.ylabel('Computation time (in second)')
plt.xlabel('Numbers computed')
i = 0
for pgen in primenumbers_gen:

    bench = results[pgen]['benchtimes']
    avgs = np.divide(bench,nbs)
    avg = np.average(bench, weights=nbs)

    # Compute linear regression
    A = np.vstack([nbs, np.ones(len(nbs))]).T
    a, b = np.linalg.lstsq(A, nbs*avgs)[0]

    # Plot
    i += 1
    #label="%(pgen)s" % locals()
    #ppl.plot(nbs, nbs*avgs, label=label, lw=1, linestyle='--', color=set2[i % 12])
    label="%(pgen)s avg" % locals()
    ppl.plot(nbs, a * nbs + b, label=label, lw=2, color=set2[i % 12])
print datetime.datetime.now().strftime(datetimeformat)

ppl.legend(ax, loc='upper left', ncol=4)

# Change x axis label
ax.get_xaxis().get_major_formatter().set_scientific(False)
fig.canvas.draw()
labels = [human_format(int(item.get_text())) for item in ax.get_xticklabels()]

ax.set_xticklabels(labels)
ax = plt.gca()

plt.show()

How to convert a boolean array to an int array

Most of the time you don't need conversion:

>>>array([True,True,False,False]) + array([1,2,3,4])
array([2, 3, 3, 4])

The right way to do it is:

yourArray.astype(int)

or

yourArray.astype(float)

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

Why not negate the padding added by container-fluid by marking left and right padding as 0?

<div class="container-fluid pl-0 pr-0">

even better way? no padding at all at the container level (cleaner)

<div class="container-fluid pl-0 pr-0">

Extracting hours from a DateTime (SQL Server 2005)

DATEPART(HOUR, [date]) returns the hour in military time ( 00 to 23 ) If you want 1AM, 3PM etc, you need to case it out:

SELECT Run_Time_Hour =
CASE DATEPART(HOUR, R.date_schedule)
    WHEN 0 THEN  '12AM'
    WHEN 1 THEN   '1AM'
    WHEN 2 THEN   '2AM'
    WHEN 3 THEN   '3AM'
    WHEN 4 THEN   '4AM'
    WHEN 5 THEN   '5AM'
    WHEN 6 THEN   '6AM'
    WHEN 7 THEN   '7AM'
    WHEN 8 THEN   '8AM'
    WHEN 9 THEN   '9AM'
    WHEN 10 THEN '10AM'
    WHEN 11 THEN '11AM'
    WHEN 12 THEN '12PM'
    ELSE CONVERT(varchar, DATEPART(HOUR, R.date_schedule)-12) + 'PM'
END
FROM
    dbo.ARCHIVE_RUN_SCHEDULE R

Generating statistics from Git repository

I tried http://gitstats.sourceforge.net/, starts are very interesting.

Once git clone git://repo.or.cz/gitstats.git is done, go to that folder and say gitstats <git repo location> <report output folder> (create a new folder for report as this generates lots of files)

Here is a quick list of stats from this:

  • activity
    • hour of the day
    • day of week
  • authors
    • List of Authors
    • Author of Month
    • Author of Year
  • files
    • File count by date
    • Extensions
  • lines
    • Lines of Code
  • tags

jQuery select box validation

Jquery Select Box Validation.You can Alert Message via alert or Put message in Div as per your requirements.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="message"></div>_x000D_
<form method="post">_x000D_
<select name="year"  id="year">_x000D_
    <option value="0">Year</option>_x000D_
    <option value="1">1919</option>_x000D_
    <option value="2">1920</option>_x000D_
    <option value="3">1921</option>_x000D_
    <option value="4">1922</option>_x000D_
</select>_x000D_
<button id="clickme">Click</button>_x000D_
</form>_x000D_
<script>_x000D_
$("#clickme").click(function(){_x000D_
_x000D_
if( $("#year option:selected").val()=='0'){_x000D_
_x000D_
alert("Please select one option at least");_x000D_
_x000D_
  $("#message").html("Select At least one option");_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
});_x000D_
_x000D_
</script>
_x000D_
_x000D_
_x000D_

AngularJS app.run() documentation?

Here's the calling order:

  1. app.config()
  2. app.run()
  3. directive's compile functions (if they are found in the dom)
  4. app.controller()
  5. directive's link functions (again, if found)

Here's a simple demo where you can watch each one executing (and experiment if you'd like).

From Angular's module docs:

Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.

One situation where run blocks are used is during authentications.

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

Python 3.3 and later now uses the 2010 compiler. To best way to solve the issue is to just install Visual C++ Express 2010 for free.

Now comes the harder part for 64 bit users and to be honest I just moved to 32 bit but 2010 express doesn't come with a 64 bit compiler (you get a new error, ValueError: ['path'] ) so you have to install Microsoft SDK 7.1 and follow the directions here to get the 64 bit compiler working with python: Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7

It may just be easier for you to use the 32 bit version for now. In addition to getting the compiler working, you can bypass the need to compile many modules by getting the binary wheel file from this locaiton http://www.lfd.uci.edu/~gohlke/pythonlibs/

Just download the .whl file you need, shift + right click the download folder and select "open command window here" and run

pip install module-name.whl 

I used that method on 64 bit 3.4.3 before I broke down and decided to just get a working compiler for pip compiles modules from source by default, which is why the binary wheel files work and having pip build from source doesn't.

People getting this (vcvarsall.bat) error on Python 2.7 can instead install "Microsoft Visual C++ Compiler for Python 2.7"

Flattening a shallow list in Python

What about:

from operator import add
reduce(add, map(lambda x: list(x.image_set.all()), [mi for mi in list_of_menuitems]))

But, Guido is recommending against performing too much in a single line of code since it reduces readability. There is minimal, if any, performance gain by performing what you want in a single line vs. multiple lines.

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3

Sometimes simplicity is the key to success. Search for while (i <= 10000) {} without increasing i in your code ;)

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below

git ls-files -z | xargs -0 rm
git checkout -- .

or one line

git ls-files -z | xargs -0 rm ; git checkout -- .

I use it all the time and haven't found any down sides yet!

For some further explanation, the -z appends a null character onto the end of each entry output by ls-files, and the -0 tells xargs to delimit the output it was receiving by those null characters.

Regex Email validation

I found nice document on MSDN for it.

How to: Verify that Strings Are in Valid Email Format http://msdn.microsoft.com/en-us/library/01escwtf.aspx (check out that this code also supports the use of non-ASCII characters for Internet domain names.)

There are 2 implementation, for .Net 2.0/3.0 and for .Net 3.5 and higher.
the 2.0/3.0 version is:

bool IsValidEmail(string strIn)
{
    // Return true if strIn is in valid e-mail format.
    return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); 
}

My tests over this method give:

Invalid: @majjf.com
Invalid: A@b@[email protected]
Invalid: Abc.example.com
Valid: [email protected]
Valid: [email protected]
Invalid: js*@proseware.com
Invalid: [email protected]
Valid: [email protected]
Valid: [email protected]
Invalid: ma@@jjf.com
Invalid: ma@jjf.
Invalid: [email protected]
Invalid: [email protected]
Invalid: ma_@jjf
Invalid: ma_@jjf.
Valid: [email protected]
Invalid: -------
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Invalid: [email protected]
Valid: j_9@[129.126.118.1]
Valid: [email protected]
Invalid: js#[email protected]
Invalid: [email protected]
Invalid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Invalid: [email protected]
Invalid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]

How to reset radiobuttons in jQuery so that none is checked

Finally after a lot of tests, I think the most convenient and efficient way to preset is:

var presetValue = "black";
$("input[name=correctAnswer]").filter("[value=" + presetValue + "]").prop("checked",true);
$("input[name=correctAnswer]").button( "refresh" );//JQuery UI only

The refresh is required with the JQueryUI object.

Retrieving the value is easy :

alert($('input[name=correctAnswer]:checked').val())

Tested with JQuery 1.6.1, JQuery UI 1.8.

QLabel: set color of text and background

The ONLY thing that worked for me was html.

And I found it to be the far easier to do than any of the programmatic approaches.

The following code changes the text color based on a parameter passed by a caller.

enum {msg_info, msg_notify, msg_alert};
:
:
void bits::sendMessage(QString& line, int level)
{
    QTextCursor cursor = ui->messages->textCursor();
    QString alertHtml  = "<font color=\"DeepPink\">";
    QString notifyHtml = "<font color=\"Lime\">";
    QString infoHtml   = "<font color=\"Aqua\">";
    QString endHtml    = "</font><br>";

    switch(level)
    {
        case msg_alert:  line = alertHtml % line; break;
        case msg_notify: line = notifyHtml % line; break;
        case msg_info:   line = infoHtml % line; break;
        default:         line = infoHtml % line; break;
    }

    line = line % endHtml;
    ui->messages->insertHtml(line);
    cursor.movePosition(QTextCursor::End);
    ui->messages->setTextCursor(cursor);
}

load jquery after the page is fully loaded

You can try using your function and using a timeout waiting until the jQuery object is loaded

Code:

document.onload=function(){
    var fileref=document.createElement('script');
    fileref.setAttribute("type","text/javascript");
    fileref.setAttribute("src", 'http://code.jquery.com/jquery-1.7.2.min.js');
    document.getElementsByTagName("head")[0].appendChild(fileref);
    waitForjQuery();
}

function waitForjQuery() {
    if (typeof jQuery != 'undefined') {
        // do some stuff
    } else {
        window.setTimeout(function () { waitForjQuery(); }, 100);
    }
}

How to check if a variable is an integer or a string?

Don't check. Go ahead and assume that it is the right input, and catch an exception if it isn't.

intresult = None
while intresult is None:
    input = raw_input()
    try: intresult = int(input)
    except ValueError: pass

Using textures in THREE.js

Andrea solution is absolutely right, I will just write another implementation based on the same idea. If you took a look at the THREE.ImageUtils.loadTexture() source you will find it uses the javascript Image object. The $(window).load event is fired after all Images are loaded ! so at that event we can render our scene with the textures already loaded...

  • CoffeeScript

    $(document).ready ->
    
        material = new THREE.MeshLambertMaterial(map: THREE.ImageUtils.loadTexture("crate.gif"))
    
        sphere   = new THREE.Mesh(new THREE.SphereGeometry(radius, segments, rings), material)
    
        $(window).load ->
            renderer.render scene, camera
    
  • JavaScript

    $(document).ready(function() {
    
        material = new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture("crate.gif") });
    
        sphere = new THREE.Mesh(new THREE.SphereGeometry(radius, segments, rings), material);
    
        $(window).load(function() {
            renderer.render(scene, camera);
        });
    });
    

Thanks...

Skip first entry in for loop in python?

Based on @SvenMarnach 's Answer, but bit simpler and without using deque

>>> def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    it = itertools.islice(it, at_start, None)
    it, it1 = itertools.tee(it)
    it1 = itertools.islice(it1, at_end, None)
    return (next(it) for _ in it1)

>>> list(skip(range(10), at_start=2, at_end=2))
[2, 3, 4, 5, 6, 7]
>>> list(skip(range(10), at_start=2, at_end=5))
[2, 3, 4]

Also Note, based on my timeit result, this is marginally faster than the deque solution

>>> iterable=xrange(1000)
>>> stmt1="""
def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    it = itertools.islice(it, at_start, None)
    it, it1 = itertools.tee(it)
    it1 = itertools.islice(it1, at_end, None)
    return (next(it) for _ in it1)
list(skip(iterable,2,2))
    """
>>> stmt2="""
def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    for x in itertools.islice(it, at_start):
        pass
    queue = collections.deque(itertools.islice(it, at_end))
    for x in it:
        queue.append(x)
        yield queue.popleft()
list(skip(iterable,2,2))
        """
>>> timeit.timeit(stmt = stmt1, setup='from __main__ import iterable, skip, itertools', number = 10000)
2.0313770640908047
>>> timeit.timeit(stmt = stmt2, setup='from __main__ import iterable, skip, itertools, collections', number = 10000)
2.9903135454296716

Populate dropdown select with array using jQuery

Since I cannot add this as a comment, I will leave it here for anyone who finds backticks to be easier to read. Its basically @Reigel answer but with backticks

var numbers = [1, 2, 3, 4, 5];
var option = ``;
for (var i=0;i<numbers.length;i++){
   option += `<option value=${numbers[i]}>${numbers[i]}</option>`;
}
$('#items').append(option);

Load data from txt with pandas

You can do as:

import pandas as pd
df = pd.read_csv('file_location\filename.txt', delimiter = "\t")

(like, df = pd.read_csv('F:\Desktop\ds\text.txt', delimiter = "\t")

How to check if memcache or memcached is installed for PHP?

Note that all of the class_exists, extensions_loaded, and function_exists only check the link between PHP and the memcache package.

To actually check whether memcache is installed you must either:

  • know the OS platform and use shell commands to check whether memcache package is installed
  • or test whether memcache connection can be established on the expected port

EDIT 2: OK, actually here's an easier complete solution:

if (class_exists('Memcache')) {
    $memcache = new Memcache;
    $isMemcacheAvailable = @$memcache->connect('localhost');
}
if ($isMemcacheAvailable) {
    //...
}

Outdated code below


EDIT: Actually you must force PHP to throw error on warnings first. Have a look at this SO question answer.

You can then test the connection via:

try {
    $memcache->connect('localhost');
} catch (Exception $e) {
    // well it's not here
}

How to call a Web Service Method?

The current way to do this is by using the "Add Service Reference" command. If you specify "TestUploaderWebService" as the service reference name, that will generate the type TestUploaderWebService.Service1. That class will have a method named GetFileListOnWebServer, which will return an array of strings (you can change that to be a list of strings if you like). You would use it like this:

string[] files = null;
TestUploaderWebService.Service1 proxy = null;
bool success = false;
try
{
    proxy = new TestUploaderWebService.Service1();
    files = proxy.GetFileListOnWebServer();
    proxy.Close();
    success = true;
}
finally
{
    if (!success)
    {
        proxy.Abort();
    }
}

P.S. Tell your instructor to look at "Microsoft: ASMX Web Services are a “Legacy Technology”", and ask why he's teaching out of date technology.

Difference between Interceptor and Filter in Spring MVC

Filter: - A filter as the name suggests is a Java class executed by the servlet container for each incoming HTTP request and for each http response. This way, is possible to manage HTTP incoming requests before them reach the resource, such as a JSP page, a servlet or a simple static page; in the same way is possible to manage HTTP outbound response after resource execution.

Interceptor: - Spring Interceptors are similar to Servlet Filters but they acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sophisticated behavior because can access to all Spring context.

How can I get the list of files in a directory using C or C++?

you can get all direct of files in your root directory by using std::experimental:: filesystem::directory_iterator(). Then, read the name of these pathfiles.

#include <iostream>
#include <filesystem>
#include <string>
#include <direct.h>
using namespace std;
namespace fs = std::experimental::filesystem;
void ShowListFile(string path)
{
for(auto &p: fs::directory_iterator(path))  /*get directory */
     cout<<p.path().filename()<<endl;   // get file name
}

int main() {

ShowListFile("C:/Users/dell/Pictures/Camera Roll/");
getchar();
return 0;
}

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

Where Sticky Notes are saved in Windows 10 1607

In windows 10 you can recover in this way, there is no .snt file

  1. Start Run
  2. Go to this %LocalAppData%\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe
  3. Copy this folder Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe
  4. Replace it with new Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe
  5. Check your sticky notes now, you will get all your data

TypeScript error: Type 'void' is not assignable to type 'boolean'

It means that the callback function you passed to this.dataStore.data.find should return a boolean and have 3 parameters, two of which can be optional:

  • value: Conversations
  • index: number
  • obj: Conversation[]

However, your callback function does not return anything (returns void). You should pass a callback function with the correct return value:

this.dataStore.data.find((element, index, obj) => {
    // ...

    return true; // or false
});

or:

this.dataStore.data.find(element => {
    // ...

    return true; // or false
});

Reason why it's this way: the function you pass to the find method is called a predicate. The predicate here defines a boolean outcome based on conditions defined in the function itself, so that the find method can determine which value to find.

In practice, this means that the predicate is called for each item in data, and the first item in data for which your predicate returns true is the value returned by find.

How to ssh from within a bash script?

What you need to do is to exchange the SSH keys for the user the script runs as. Have a look at this tutorial

After doing so, your scripts will run without the need for entering a password. But, for security's sake, you don't want to do this for root users!

How do I reset the setInterval timer?

Once you clear the interval using clearInterval you could setInterval once again. And to avoid repeating the callback externalize it as a separate function:

var ticker = function() {
    console.log('idle');
};

then:

var myTimer = window.setInterval(ticker, 4000);

then when you decide to restart:

window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);

How can you print a variable name in python?

Rather than ask for details to a specific solution, I recommend describing the problem you face; I think you'll get better answers. I say this since there's almost certainly a better way to do whatever it is you're trying to do. Accessing variable names in this way is not commonly needed to solve problems in any language.

That said, all of your variable names are already in dictionaries which are accessible through the built-in functions locals and globals. Use the correct one for the scope you are inspecting.

One of the few common idioms for inspecting these dictionaries is for easy string interpolation:

>>> first = 'John'
>>> last = 'Doe'
>>> print '%(first)s %(last)s' % globals()
John Doe

This sort of thing tends to be a bit more readable than the alternatives even though it requires inspecting variables by name.

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions