Programs & Examples On #Dom

Use this tag on questions regarding the interaction of other languages with XML/HTML via the document object model. Do not use it as shorthand for HTML, JavaScript, or SAX—use additional tags to denote both language and markup.

Getting HTML elements by their attribute names

In jQuery this is so:

$("span['property'=v:name]"); // for selecting your span element

Determine which element the mouse pointer is on top of in JavaScript

Mouseover events bubble, so you can put a single listener on the body and wait for them to bubble up, then grab the event.target or event.srcElement:

function getTarget(event) {
    var el = event.target || event.srcElement;
    return el.nodeType == 1? el : el.parentNode;
}

<body onmouseover="doSomething(getTarget(event));">

How do I create a link using javascript?

_x000D_
_x000D_
    <script>_x000D_
      _$ = document.querySelector  .bind(document) ;_x000D_
_x000D_
        var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs_x000D_
        var a   =  document.createElement( 'a' )_x000D_
        a.text  = "Download example" _x000D_
        a.href  = "//bit\.do/DeezerDL"_x000D_
_x000D_
        AppendLinkHere.appendChild( a )_x000D_
        _x000D_
_x000D_
     // a.title = 'Well well ... _x000D_
        a.setAttribute( 'title', _x000D_
                         'Well well that\'s a link'_x000D_
                      );_x000D_
    </script>
_x000D_
_x000D_
_x000D_

  1. The 'Anchor Object' has its own*(inherited)* properties for setting the link, its text. So just use them. .setAttribute is more general but you normally don't need it. a.title ="Blah" will do the same and is more clear! Well a situation that'll demand .setAttribute is this: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")

  2. Leave the protocol open. Instead of http://example.com/path consider to just use //example.com/path. Check if example.com can be accessed by http: as well as https: but 95 % of sites will work on both.

  3. OffTopic: That's not really relevant about creating links in JS but maybe good to know: Well sometimes like in the chromes dev-console you can use $("body") instead of document.querySelector("body") A _$ = document.querySelectorwill 'honor' your efforts with an Illegal invocation error the first time you use it. That's because the assignment just 'grabs' .querySelector (a ref to the class method). With .bind(... you'll also involve the context (here it's document) and you get an object method that'll work as you might expect it.

Best way to get child nodes

Just to add to the other answers, there are still noteworthy differences here, specifically when dealing with <svg> elements.

I have used both .childNodes and .children and have preferred working with the HTMLCollection delivered by the .children getter.

Today however, I ran into issues with IE/Edge failing when using .children on an <svg>. While .children is supported in IE on basic HTML elements, it isn't supported on document/document fragments, or SVG elements.

For me, I was able to simply grab the needed elements via .childNodes[n] because I don't have extraneous text nodes to worry about. You may be able to do the same, but as mentioned elsewhere above, don't forget that you may run into unexpected elements.

Hope this is helpful to someone scratching their head trying to figure out why .children works elsewhere in their js on modern IE and fails on document or SVG elements.

How can I select an element by name with jQuery?

Personally, what I've done in the past is give them a common class id and used that to select them. It may not be ideal as they have a class specified that may not exist, but it makes the selection a hell of a lot easier. Just make sure you're unique in your classnames.

i.e. for the example above I'd use your selection by class. Better still would be to change the class name from bold to 'tcol1', so you don't get any accidental inclusions into the jQuery results. If bold does actually refer to a CSS class, you can always specify both in the class property - i.e. 'class="tcol1 bold"'.

In summary, if you can't select by Name, either use a complicated jQuery selector and accept any related performance hit or use Class selectors.

You can always limit the jQuery scope by including the table name i.e. $('#tableID > .bold')

That should restrict jQuery from searching the "world".

Its could still be classed as a complicated selector, but it quickly constrains any searching to within the table with the ID of '#tableID', so keeps the processing to a minimum.

An alternative of this if you're looking for more than 1 element within #table1 would be to look this up separately and then pass it to jQuery as this limits the scope, but saves a bit of processing to look it up each time.

var tbl = $('#tableID');
var boldElements = $('.bold',tbl);
var rows = $('tr',tbl);
if (rows.length) {
   var row1 = rows[0]; 
   var firstRowCells = $('td',row1); 
}

What is the "hasClass" function with plain JavaScript?

What do you think about this approach?

<body class="thatClass anotherClass"> </body>

var bodyClasses = document.querySelector('body').className;
var myClass = new RegExp("thatClass");
var trueOrFalse = myClass.test( bodyClasses );

https://jsfiddle.net/5sv30bhe/

Get the selected option id with jQuery

$('#my_select option:selected').attr('id');

jQuery click function doesn't work after ajax call?

The click event doesn't exist at that point where the event is defined. You can use live or delegate the event.

$('.deletelanguage').live('click',function(){
    alert("success");
    $('#LangTable').append(' <br>------------<br> <a class="deletelanguage">Now my class is deletelanguage. click me to test it is not working.</a>');
});

What is the difference between children and childNodes in JavaScript?

Good answers so far, I want to only add that you could check the type of a node using nodeType:

yourElement.nodeType

This will give you an integer: (taken from here)

| Value |             Constant             |                          Description                          |  |
|-------|----------------------------------|---------------------------------------------------------------|--|
|    1  | Node.ELEMENT_NODE                | An Element node such as <p> or <div>.                         |  |
|    2  | Node.ATTRIBUTE_NODE              | An Attribute of an Element. The element attributes            |  |
|       |                                  | are no longer implementing the Node interface in              |  |
|       |                                  | DOM4 specification.                                           |  |
|    3  | Node.TEXT_NODE                   | The actual Text of Element or Attr.                           |  |
|    4  | Node.CDATA_SECTION_NODE          | A CDATASection.                                               |  |
|    5  | Node.ENTITY_REFERENCE_NODE       | An XML Entity Reference node. Removed in DOM4 specification.  |  |
|    6  | Node.ENTITY_NODE                 | An XML <!ENTITY ...> node. Removed in DOM4 specification.     |  |
|    7  | Node.PROCESSING_INSTRUCTION_NODE | A ProcessingInstruction of an XML document                    |  |
|       |                                  | such as <?xml-stylesheet ... ?> declaration.                  |  |
|    8  | Node.COMMENT_NODE                | A Comment node.                                               |  |
|    9  | Node.DOCUMENT_NODE               | A Document node.                                              |  |
|   10  | Node.DOCUMENT_TYPE_NODE          | A DocumentType node e.g. <!DOCTYPE html> for HTML5 documents. |  |
|   11  | Node.DOCUMENT_FRAGMENT_NODE      | A DocumentFragment node.                                      |  |
|   12  | Node.NOTATION_NODE               | An XML <!NOTATION ...> node. Removed in DOM4 specification.   |  |

Note that according to Mozilla:

The following constants have been deprecated and should not be used anymore: Node.ATTRIBUTE_NODE, Node.ENTITY_REFERENCE_NODE, Node.ENTITY_NODE, Node.NOTATION_NODE

Select all elements with a "data-xxx" attribute without using jQuery

While not as pretty as querySelectorAll (which has a litany of issues), here's a very flexible function that recurses the DOM and should work in most browsers (old and new). As long as the browser supports your condition (ie: data attributes), you should be able to retrieve the element.

To the curious: Don't bother testing this vs. QSA on jsPerf. Browsers like Opera 11 will cache the query and skew the results.

Code:

function recurseDOM(start, whitelist)
{
    /*
    *    @start:        Node    -    Specifies point of entry for recursion
    *    @whitelist:    Object  -    Specifies permitted nodeTypes to collect
    */

    var i = 0, 
    startIsNode = !!start && !!start.nodeType, 
    startHasChildNodes = !!start.childNodes && !!start.childNodes.length,
    nodes, node, nodeHasChildNodes;
    if(startIsNode && startHasChildNodes)
    {       
        nodes = start.childNodes;
        for(i;i<nodes.length;i++)
        {
            node = nodes[i];
            nodeHasChildNodes = !!node.childNodes && !!node.childNodes.length;
            if(!whitelist || whitelist[node.nodeType])
            {
                //condition here
                if(!!node.dataset && !!node.dataset.foo)
                {
                    //handle results here
                }
                if(nodeHasChildNodes)
                {
                    recurseDOM(node, whitelist);
                }
            }
            node = null;
            nodeHasChildNodes = null;
        }
    }
}

You can then initiate it with the following:

recurseDOM(document.body, {"1": 1}); for speed, or just recurseDOM(document.body);

Example with your specification: http://jsbin.com/unajot/1/edit

Example with differing specification: http://jsbin.com/unajot/2/edit

querySelector, wildcard element match?

I just wrote this short script; seems to work.

/**
 * Find all the elements with a tagName that matches.
 * @param {RegExp} regEx  regular expression to match against tagName
 * @returns {Array}       elements in the DOM that match
 */
function getAllTagMatches(regEx) {
  return Array.prototype.slice.call(document.querySelectorAll('*')).filter(function (el) { 
    return el.tagName.match(regEx);
  });
}
getAllTagMatches(/^di/i); // Returns an array of all elements that begin with "di", eg "div"

Delaying a jquery script until everything else has loaded

Multiple $(document).ready() will fire in order top down on the page. The last $(document).ready() will fire last on the page. Inside the last $(document).ready(), you can trigger a new custom event to fire after all the others..

Wrap your code in an event handler for the new custom event.

<html>
<head>
<script>
    $(document).on("my-event-afterLastDocumentReady", function () {
        // Fires LAST
    });
    $(document).ready(function() {
        // Fires FIRST
    });
    $(document).ready(function() {
        // Fires SECOND
    });
    $(document).ready(function() {
        // Fires THIRD
    });
</script>
<body>
... other code, scripts, etc....
</body>
</html>

<script>
    $(document).ready(function() {
        // Fires FOURTH
        // This event will fire after all the other $(document).ready() functions have completed.
        // Usefull when your script is at the top of the page, but you need it run last
        $(document).trigger("my-event-afterLastDocumentReady");
    });
</script>

Retrieving the text of the selected <option> in <select> element

If you use jQuery then you can write the following code:

$("#selectId option:selected").html();

Rotating a Div Element in jQuery

To rotate a DIV Make use of WebkitTransform / -moz-transform: rotate(Xdeg).

This will not work in IE. The Raphael library does work with IE and it does rotation. I believe it uses canvases

If you want to animate the rotation, you can use a recursive setTimeout()

You could probably even do part of a spin with jQuery's .animate()

Make sure that you consider the width of your element. If rotate an that has a larger width than its visible content, you'll get funny results. However you can narrow the widths of elements, and then rotate them.

Here is a simply jQuery snippet that rotates the elements in a jQuery object. Rotatation can be started and stopped:

$(function() {
    var $elie = $(selectorForElementsToRotate);
    rotate(0);
    function rotate(degree) {

          // For webkit browsers: e.g. Chrome
        $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
          // For Mozilla browser: e.g. Firefox
        $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});

          // Animate rotation with a recursive call
        setTimeout(function() { rotate(++degree); },5);
    }
});

jsFiddle example

Note:
Taking the degree and increasing it, will rotate the image clockwise. Decreasing the degree of rotation will rotate the image counter clockwise.

jQuery Force set src attribute for iframe

$(".excel").click(function () {
    var t = $(this).closest(".tblGrid").attr("id");
    window.frames["Iframe" + t].document.location.href = pagename + "?tbl=" + t;
});

this is what i use, no jquery needed for this. in this particular scenario for each table i have with an excel export icon this forces the iframe attached to that table to load the same page with a variable in the Query String that the page looks for, and if found response writes out a stream with an excel mimetype and includes the data for that table.

How to get coordinates of an svg element?

The element.getBoundingClientRect() method will return the proper coordinates of an element relative to the viewport regardless of whether the svg has been scaled and/or translated.

See this question and answer.

While getBBox() works for an untransformed space, if scale and translation have been applied to the layout then it will no longer be accurate. The getBoundingClientRect() function has worked well for me in a force layout project when pan and zoom are in effect, where I wanted to attach HTML Div elements as labels to the nodes instead of using SVG Text elements.

onKeyPress Vs. onKeyUp and onKeyDown

Check here for the archived link originally used in this answer.

From that link:

In theory, the onKeyDown and onKeyUp events represent keys being pressed or released, while the onKeyPress event represents a character being typed. The implementation of the theory is not same in all browsers.

Copy / Put text on the clipboard with FireFox, Safari and Chrome

http://www.rodsdot.com/ee/cross_browser_clipboard_copy_with_pop_over_message.asp works with Flash 10 and all Flash enabled browsers.

Also ZeroClipboard has been updated to avoid the bug mentioned about page scrolling causing the Flash movie to no longer be in the correct place.

Since that method "Requires" the user to click a button to copy this is a convenience to the user and nothing nefarious is occurring.

How to get the title of HTML page with JavaScript?

Use document.title:

_x000D_
_x000D_
console.log(document.title)
_x000D_
<title>Title test</title>
_x000D_
_x000D_
_x000D_

MDN Web Docs

How can I access iframe elements with Javascript?

If you have the HTML

<form name="formname" .... id="form-first">
    <iframe id="one" src="iframe2.html">
    </iframe>
</form>

and JavaScript

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

var inside = iframeRef( document.getElementById('one') )

inside is now a reference to the document, so you can do getElementsByTagName('textarea') and whatever you like, depending on what's inside the iframe src.

Uncaught TypeError: Cannot read property 'top' of undefined

I know this is extremely old, but I understand that this error type is a common mistake for beginners to make since most beginners will call their functions upon their header element being loaded. Seeing as this solution is not addressed at all in this thread, I'll add it. It is very likely that this javascript function was placed before the actual html was loaded. Remember, if you immediately call your javascript before the document is ready then elements requiring an element from the document might find an undefined value.

An invalid XML character (Unicode: 0xc) was found

public String stripNonValidXMLCharacters(String in) {
    StringBuffer out = new StringBuffer(); // Used to hold the output.
    char current; // Used to reference the current character.

    if (in == null || ("".equals(in))) return ""; // vacancy test.
    for (int i = 0; i < in.length(); i++) {
        current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen.
        if ((current == 0x9) ||
            (current == 0xA) ||
            (current == 0xD) ||
            ((current >= 0x20) && (current <= 0xD7FF)) ||
            ((current >= 0xE000) && (current <= 0xFFFD)) ||
            ((current >= 0x10000) && (current <= 0x10FFFF)))
            out.append(current);
    }
    return out.toString();
}    

What is the most efficient way to create HTML elements using jQuery?

I think you're using the best method, though you could optimize it to:

 $("<div/>");

addClass and removeClass in jQuery - not removing class

What happens is that your close button is placed inside your .clickable div, so the click event will be triggered in both elements.

The event bubbling will make the click event propagate from the child nodes to their parents. So your .close_button callback will be executed first, and when .clickable is reached, it will toggle the classes again. As this run very fast you can't notice the two events happened.

                    / \
--------------------| |-----------------
| .clickable        | |                |
|   ----------------| |-----------     |
|   | .close_button | |          |     |
|   ------------------------------     |
|             event bubbling           |
----------------------------------------

To prevent your event from reaching .clickable, you need to add the event parameter to your callback function and then call the stopPropagation method on it.

$(".close_button").click(function (e) { 
    $("#spot1").addClass("spot");
    $("#spot1").removeClass("grown");
    e.stopPropagation();
});

Fiddle: http://jsfiddle.net/u4GCk/1/

More info about event order in general: http://www.quirksmode.org/js/events_order.html (that's where I picked that pretty ASCII art =])

setAttribute('display','none') not working

It works for me

setAttribute('style', 'display:none');

How to make JavaScript execute after page load?

JavaScript

document.addEventListener('readystatechange', event => { 

    // When HTML/DOM elements are ready:
    if (event.target.readyState === "interactive") {   //does same as:  ..addEventListener("DOMContentLoaded"..
        alert("hi 1");
    }

    // When window loaded ( external resources are loaded too- `css`,`src`, etc...) 
    if (event.target.readyState === "complete") {
        alert("hi 2");
    }
});

same for jQuery:

$(document).ready(function() {   //same as: $(function() { 
     alert("hi 1");
});

$(window).load(function() {
     alert("hi 2");
});





NOTE: - Don't use the below markup ( because it overwrites other same-kind declarations ) :

document.onreadystatechange = ...

How can I be notified when an element is added to the page?

Check out this plugin that does exacly that - jquery.initialize

It works exacly like .each function, the difference is it takes selector you've entered and watch for new items added in future matching this selector and initialize them

Initialize looks like this

$(".some-element").initialize( function(){
    $(this).css("color", "blue");
});

But now if new element matching .some-element selector will appear on page, it will be instanty initialized.

The way new item is added is not important, you dont need to care about any callbacks etc.

So if you'd add new element like:

$("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color!

it will be instantly initialized.

Plugin is based on MutationObserver

Get child Node of another Node, given node name

Check if the Node is a Dom Element, cast, and call getElementsByTagName()

Node doc = docs.item(i);
if(doc instanceof Element) {
    Element docElement = (Element)doc;
    ...
    cell = doc.getElementsByTagName("aoo").item(0);
}

Include another HTML file in a HTML file

Using ES6 backticks ``: template literals!

_x000D_
_x000D_
let nick = "Castor", name = "Moon", nuts = 1_x000D_
_x000D_
more.innerHTML = `_x000D_
_x000D_
<h1>Hello ${nick} ${name}!</h1>_x000D_
_x000D_
You collected ${nuts} nuts so far!_x000D_
_x000D_
<hr>_x000D_
_x000D_
Double it and get ${nuts + nuts} nuts!!_x000D_
_x000D_
` 
_x000D_
<div id="more"></div>
_x000D_
_x000D_
_x000D_

This way we can include html without encoding quotes, include variables from the DOM, and so on.

It is a powerful templating engine, we can use separate js files and use events to load the content in place, or even separate everything in chunks and call on demand:

let inject = document.createElement('script');
inject.src= '//....com/template/panel45.js';
more.appendChild(inject);

https://caniuse.com/#feat=template-literals

Is it possible to run an .exe or .bat file on 'onclick' in HTML

You can do it on Internet explorer with OCX component and on chrome browser using a chrome extension chrome document in any case need additional settings on the client system!

Important part of chrome extension source:

var port = chrome.runtime.connectNative("your.app.id"); 
      port.onMessage.addListener(onNativeMessage); 
      port.onDisconnect.addListener(onDisconnected);
      port.postMessage("send some data to STDIO");

permission file:

{
      "name": "your.app.id",
      "description": "Name of your extension",
      "path": "myapp.exe",
      "type": "stdio",
      "allowed_origins": [
            "chrome-extension://IDOFYOUREXTENSION_lokldaeplkmh/"
      ]
}

and windows registry settings:

HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts\your.app.id
REG_EXPAND_SZ : c:\permissionsettings.json

Why does jQuery or a DOM method such as getElementById not find the element?

If script execution order is not the issue, another possible cause of the problem is that the element is not being selected properly:

  • getElementById requires the passed string to be the ID verbatim, and nothing else. If you prefix the passed string with a #, and the ID does not start with a #, nothing will be selected:

      <div id="foo"></div>
    
      // Error, selected element will be null:
      document.getElementById('#foo')
      // Fix:
      document.getElementById('foo')
    
  • Similarly, for getElementsByClassName, don't prefix the passed string with a .:

      <div class="bar"></div>
    
      // Error, selected element will be undefined:
      document.getElementsByClassName('.bar')[0]
      // Fix:
      document.getElementsByClassName('bar')[0]
    
  • With querySelector, querySelectorAll, and jQuery, to match an element with a particular class name, put a . directly before the class. Similarly, to match an element with a particular ID, put a # directly before the ID:

      <div class="baz"></div>
    
      // Error, selected element will be null:
      document.querySelector('baz')
      $('baz')
      // Fix:
      document.querySelector('.baz')
      $('.baz')
    

    The rules here are, in most cases, identical to those for CSS selectors, and can be seen in detail here.

  • To match an element which has two or more attributes (like two class names, or a class name and a data- attribute), put the selectors for each attribute next to each other in the selector string, without a space separating them (because a space indicates the descendant selector). For example, to select:

      <div class="foo bar"></div>
    

    use the query string .foo.bar. To select

      <div class="foo" data-bar="someData"></div>
    

    use the query string .foo[data-bar="someData"]. To select the <span> below:

      <div class="parent">
        <span data-username="bob"></span>
      </div>
    

    use div.parent > span[data-username="bob"].

  • Capitalization and spelling does matter for all of the above. If the capitalization is different, or the spelling is different, the element will not be selected:

      <div class="result"></div>
    
      // Error, selected element will be null:
      document.querySelector('.results')
      $('.Result')
      // Fix:
      document.querySelector('.result')
      $('.result')
    
  • You also need to make sure the methods have the proper capitalization and spelling. Use one of:

    $(selector)
    document.querySelector
    document.querySelectorAll
    document.getElementsByClassName
    document.getElementsByTagName
    document.getElementById
    

    Any other spelling or capitalization will not work. For example, document.getElementByClassName will throw an error.

  • Make sure you pass a string to these selector methods. If you pass something that isn't a string to querySelector, getElementById, etc, it almost certainly won't work.

  • If the HTML attributes on elements you want to select are surrounded by quotes, they must be plain straight quotes (either single or double); curly quotes like or will not work if you're trying to select by ID, class, or attribute.

Detect changes in the DOM

I have recently written a plugin that does exactly that - jquery.initialize

You use it the same way as .each function

$(".some-element").initialize( function(){
    $(this).css("color", "blue"); 
});

The difference from .each is - it takes your selector, in this case .some-element and wait for new elements with this selector in the future, if such element will be added, it will be initialized too.

In our case initialize function just change element color to blue. So if we'll add new element (no matter if with ajax or even F12 inspector or anything) like:

$("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color!

Plugin will init it instantly. Also plugin makes sure one element is initialized only once. So if you add element, then .detach() it from body and then add it again, it will not be initialized again.

$("<div/>").addClass('some-element').appendTo("body").detach()
    .appendTo(".some-container");
//initialized only once

Plugin is based on MutationObserver - it will work on IE9 and 10 with dependencies as detailed on the readme page.

Getting value of HTML Checkbox from onclick/onchange events

The short answer:

Use the click event, which won't fire until after the value has been updated, and fires when you want it to:

<label><input type='checkbox' onclick='handleClick(this);'>Checkbox</label>

function handleClick(cb) {
  display("Clicked, new value = " + cb.checked);
}

Live example | Source

The longer answer:

The change event handler isn't called until the checked state has been updated (live example | source), but because (as Tim Büthe points out in the comments) IE doesn't fire the change event until the checkbox loses focus, you don't get the notification proactively. Worse, with IE if you click a label for the checkbox (rather than the checkbox itself) to update it, you can get the impression that you're getting the old value (try it with IE here by clicking the label: live example | source). This is because if the checkbox has focus, clicking the label takes the focus away from it, firing the change event with the old value, and then the click happens setting the new value and setting focus back on the checkbox. Very confusing.

But you can avoid all of that unpleasantness if you use click instead.

I've used DOM0 handlers (onxyz attributes) because that's what you asked about, but for the record, I would generally recommend hooking up handlers in code (DOM2's addEventListener, or attachEvent in older versions of IE) rather than using onxyz attributes. That lets you attach multiple handlers to the same element and lets you avoid making all of your handlers global functions.


An earlier version of this answer used this code for handleClick:

function handleClick(cb) {
  setTimeout(function() {
    display("Clicked, new value = " + cb.checked);
  }, 0);
}

The goal seemed to be to allow the click to complete before looking at the value. As far as I'm aware, there's no reason to do that, and I have no idea why I did. The value is changed before the click handler is called. In fact, the spec is quite clear about that. The version without setTimeout works perfectly well in every browser I've tried (even IE6). I can only assume I was thinking about some other platform where the change isn't done until after the event. In any case, no reason to do that with HTML checkboxes.

Javascript querySelector vs. getElementById

The functions getElementById and getElementsByClassName are very specific, while querySelector and querySelectorAll are more elaborate. My guess is that they will actually have a worse performance.

Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".

change html text from link with jquery

The method you are looking for is jQuery's .text() and you can used it in the following fashion:

$('#a_tbnotesverbergen').text('text here');

AngularJS: How to run additional code after AngularJS has rendered a template?

I have found the simplest (cheap and cheerful) solution is simply add an empty span with ng-show = "someFunctionThatAlwaysReturnsZeroOrNothing()" to the end of the last element rendered. This function will be run when to check if the span element should be displayed. Execute any other code in this function.

I realize this is not the most elegant way to do things, however, it works for me...

I had a similar situation, though slightly reversed where I needed to remove a loading indicator when an animation began, on mobile devices angular was initializing much faster than the animation to be displayed, and using an ng-cloak was insufficient as the loading indicator was removed well before any real data was displayed. In this case I just added the my return 0 function to the first rendered element, and in that function flipped the var that hides the loading indicator. (of course I added an ng-hide to the loading indicator triggered by this function.

How can I check if a scrollbar is visible?

Here's my improvement: added parseInt. for some weird reason it didn't work without it.

// usage: jQuery('#my_div1').hasVerticalScrollBar();
// Credit: http://stackoverflow.com/questions/4814398/how-can-i-check-if-a-scrollbar-is-visible
(function($) {
    $.fn.hasVerticalScrollBar = function() {
        return this.get(0) ? parseInt( this.get(0).scrollHeight ) > parseInt( this.innerHeight() ) : false;
    };
})(jQuery);

Does document.body.innerHTML = "" clear the web page?

document.body.innerHTML = ''; does clear the body, yeah. But it clears the innerHTML as it is at the moment the code is ran. As you run the code before the images and the script are actually in the body, it tries to clear the body, but there's nothing to clear.

If you want to clear the body, you have to run the code after the body has been filled with content. You can do this by either placing the <script> block as the last child of body, so everything is loaded before the code is ran, or you have to use some way to listen to the dom:loaded event.

jQuery - Trigger event when an element is removed from the DOM

Only jQuery is required (No jQuery UI needed)

(I have extracted this extension from the jQuery UI framework)

Works with: empty() and html() and remove()

$.cleanData = ( function( orig ) {
    return function( elems ) {
        var events, elem, i;
        for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {
            try {

                // Only trigger remove when necessary to save time
                events = $._data( elem, "events" );
                if ( events && events.remove ) {
                    $( elem ).triggerHandler( "remove" );
                }

            // Http://bugs.jquery.com/ticket/8235
            } catch ( e ) {}
        }
        orig( elems );
    };
} )( $.cleanData );

With this solution you can also unbind the event handler.

$("YourElemSelector").off("remove");

Try it! - Example

_x000D_
_x000D_
$.cleanData = (function(orig) {_x000D_
  return function(elems) {_x000D_
    var events, elem, i;_x000D_
    for (i = 0;_x000D_
      (elem = elems[i]) != null; i++) {_x000D_
      try {_x000D_
_x000D_
        // Only trigger remove when necessary to save time_x000D_
        events = $._data(elem, "events");_x000D_
        if (events && events.remove) {_x000D_
          $(elem).triggerHandler("remove");_x000D_
        }_x000D_
_x000D_
        // Http://bugs.jquery.com/ticket/8235_x000D_
      } catch (e) {}_x000D_
    }_x000D_
    orig(elems);_x000D_
  };_x000D_
})($.cleanData);_x000D_
_x000D_
_x000D_
$("#DivToBeRemoved").on("remove", function() {_x000D_
  console.log("div was removed event fired");_x000D_
});_x000D_
_x000D_
$("p").on("remove", function() {_x000D_
  console.log("p was removed event fired");_x000D_
});_x000D_
_x000D_
$("span").on("remove", function() {_x000D_
  console.log("span was removed event fired");_x000D_
});_x000D_
_x000D_
// $("span").off("remove");_x000D_
_x000D_
$("#DivToBeRemoved").on("click", function() {_x000D_
  console.log("Div was clicked");_x000D_
});_x000D_
_x000D_
function RemoveDiv() {_x000D_
  //       $("#DivToBeRemoved").parent().html("");    _x000D_
  $("#DivToBeRemoved").remove();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h3>OnRemove event handler attached to elements `div`, `p` and `span`.</h3>_x000D_
<div class="container">_x000D_
  <br>_x000D_
  <button onclick="RemoveDiv();">Click here to remove div below</button>_x000D_
  <div id="DivToBeRemoved">_x000D_
    DIV TO BE REMOVED _x000D_
    contains 1 p element _x000D_
    which in turn contains a span element_x000D_
    <p>i am p (within div)_x000D_
      <br><br><span>i am span (within div)</span></p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Additional Demo - jsBin

How to get a DOM Element from a JQuery Selector

Edit: seems I was wrong in assuming you could not get the element. As others have posted here, you can get it with:

$('#element').get(0);

I have verified this actually returns the DOM element that was matched.

Getting DOM elements by classname

If you wish to get the innerhtml of the class without the zend you could use this:

$dom = new DomDocument();
$dom->load($filePath);
$classname = 'main-article';
$finder = new DomXPath($dom);
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
$tmp_dom = new DOMDocument(); 
foreach ($nodes as $node) 
    {
    $tmp_dom->appendChild($tmp_dom->importNode($node,true));
    }
$innerHTML.=trim($tmp_dom->saveHTML()); 
echo $innerHTML;

How can I add a class to a DOM element in JavaScript?

<script>
    document.getElementById('add-Box').addEventListener('click', function (event) {
        let itemParent = document.getElementById('box-Parent');
        let newItem = document.createElement('li');
        newItem.className = 'box';
        itemParent.appendChild(newItem);
    })
</script>

Check if an image is loaded (no errors) with jQuery

This is how I got it to work cross browser using a combination of the methods above (I also needed to insert images dynamically into the dom):

$('#domTarget').html('<img src="" />');

var url = '/some/image/path.png';

$('#domTarget img').load(function(){}).attr('src', url).error(function() {
    if ( isIE ) {
       var thisImg = this;
       setTimeout(function() {
          if ( ! thisImg.complete ) {
             $(thisImg).attr('src', '/web/css/img/picture-broken-url.png');
          }
       },250);
    } else {
       $(this).attr('src', '/web/css/img/picture-broken-url.png');
    }
});

Note: You will need to supply a valid boolean state for the isIE variable.

How to use "not" in xpath?

you can use not(expression) function

or

expression != true()

Get child node index

you can use the previousSibling property to iterate back through the siblings until you get back null and count how many siblings you've encountered:

var i = 0;
while( (child = child.previousSibling) != null ) 
  i++;
//at the end i will contain the index.

Please note that in languages like Java, there is a getPreviousSibling() function, however in JS this has become a property -- previousSibling.

jQuery events .load(), .ready(), .unload()

window load will wait for all resources to be loaded.

document ready waits for the document to be initialized.

unload well, waits till the document is being unloaded.

the order is: document ready, window load, ... ... ... ... window unload.

always use document ready unless you need to wait for your images to load.

shorthand for document ready:

$(function(){
    // yay!
});

Event when window.location.href changes

There is a default onhashchange event that you can use.

Documented HERE

And can be used like this:

function locationHashChanged( e ) {
    console.log( location.hash );
    console.log( e.oldURL, e.newURL );
    if ( location.hash === "#pageX" ) {
        pageX();
    }
}

window.onhashchange = locationHashChanged;

If the browser doesn't support oldURL and newURL you can bind it like this:

//let this snippet run before your hashChange event binding code
if( !window.HashChangeEvent )( function() {
    let lastURL = document.URL;
    window.addEventListener( "hashchange", function( event ) {
        Object.defineProperty( event, "oldURL", { enumerable: true, configurable: true, value: lastURL } );
        Object.defineProperty( event, "newURL", { enumerable: true, configurable: true, value: document.URL } );
        lastURL = document.URL;
    } );
} () );

How do I programmatically set the value of a select box element using JavaScript?

Should be something along these lines:

function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
  if (dl.options[i].value == inVal){
    el=i;
    break;
  }
}
dl.selectedIndex = el;
}

Normalization in DOM parsing with java - how does it work?

The rest of the sentence is:

where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.

This basically means that the following XML element

<foo>hello 
wor
ld</foo>

could be represented like this in a denormalized node:

Element foo
    Text node: ""
    Text node: "Hello "
    Text node: "wor"
    Text node: "ld"

When normalized, the node will look like this

Element foo
    Text node: "Hello world"

And the same goes for attributes: <foo bar="Hello world"/>, comments, etc.

jQuery find events handlers registered with an object

I've combined both solutions from @jps to one function:

jQuery.fn.getEvents = function() {
    if (typeof(jQuery._data) === 'function') {
        return jQuery._data(this.get(0), 'events') || {};
    }

    // jQuery version < 1.7.?
    if (typeof(this.data) === 'function') {
        return this.data('events') || {};
    }

    return {};
};

But beware, this function can only return events that were set using jQuery itself.

Dynamically set value of a file input

I had similar problem, then I tried writing this from JavaScript and it works! : referenceToYourInputFile.value = "" ;

Difference between window.location.href, window.location.replace and window.location.assign

These do the same thing:

window.location.assign(url);
window.location = url;
window.location.href = url;

They simply navigate to the new URL. The replace method on the other hand navigates to the URL without adding a new record to the history.

So, what you have read in those many forums is not correct. The assign method does add a new record to the history.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/location

How to get the new value of an HTML input after a keypress has modified it?

To give a modern approach to this question. This works well, including Ctrl+v. GlobalEventHandlers.oninput.

var onChange = function(evt) {
  console.info(this.value);
  // or
  console.info(evt.target.value);
};
var input = document.getElementById('some-id');
input.addEventListener('input', onChange, false);

For loop for HTMLCollection elements

Alternative to Array.from is to use Array.prototype.forEach.call

forEach: Array.prototype.forEach.call(htmlCollection, i => { console.log(i) });

map: Array.prototype.map.call(htmlCollection, i => { console.log(i) });

ect...

How to find a parent with a known class in jQuery?

You can use parents() to get all parents with the given selector.

Description: Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.

But parent() will get just the first parent of the element.

Description: Get the parent of each element in the current set of matched elements, optionally filtered by a selector.

jQuery parent() vs. parents()

And there is .parentsUntil() which I think will be the best.

Description: Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector.

How to fill in form field, and submit, using javascript?

You can try something like this:

    <script type="text/javascript">
        function simulateLogin(userName)
        {
            var userNameField = document.getElementById("username");
            userNameField.value = userName;
            var goButton = document.getElementById("go");
            goButton.click();
        }

        simulateLogin("testUser");
</script>

Javascript: 'window' is not defined

It is from an external js file and it is the only file linked to the page.

OK.

When I double click this file I get the following error

Sounds like you're double-clicking/running a .js file, which will attempt to run the script outside the browser, like a command line script. And that would explain this error:

Windows Script Host Error: 'window' is not defined Code: 800A1391

... not an error you'll see in a browser. And of course, the browser is what supplies the window object.

ADDENDUM: As a course of action, I'd suggest opening the relevant HTML file and taking a peek at the console. If you don't see anything there, it's likely your window.onload definition is simply being hit after the browser fires the window.onload event.

Remove all child elements of a DOM node in JavaScript

In response to DanMan, Maarten and Matt. Cloning a node, to set the text is indeed a viable way in my results.

// @param {node} node
// @return {node} empty node
function removeAllChildrenFromNode (node) {
  var shell;
  // do not copy the contents
  shell = node.cloneNode(false);

  if (node.parentNode) {
    node.parentNode.replaceChild(shell, node);
  }

  return shell;
}

// use as such
var myNode = document.getElementById('foo');
myNode = removeAllChildrenFromNode( myNode );

Also this works for nodes not in the dom which return null when trying to access the parentNode. In addition, if you need to be safe a node is empty before adding content this is really helpful. Consider the use case underneath.

// @param {node} node
// @param {string|html} content
// @return {node} node with content only
function refreshContent (node, content) {
  var shell;
  // do not copy the contents
  shell = node.cloneNode(false);

  // use innerHTML or you preffered method
  // depending on what you need
  shell.innerHTML( content );

  if (node.parentNode) {
    node.parentNode.replaceChild(shell, node);
  }

  return shell;
}

// use as such
var myNode = document.getElementById('foo');
myNode = refreshContent( myNode );

I find this method very useful when replacing a string inside an element, if you are not sure what the node will contain, instead of worrying how to clean up the mess, start out fresh.

Can scripts be inserted with innerHTML?

Use $(parent).html(code) instead of parent.innerHTML = code.

The following also fixes scripts that use document.write and scripts loaded via src attribute. Unfortunately even this doesn't work with Google AdSense scripts.

var oldDocumentWrite = document.write;
var oldDocumentWriteln = document.writeln;
try {
    document.write = function(code) {
        $(parent).append(code);
    }
    document.writeln = function(code) {
        document.write(code + "<br/>");
    }
    $(parent).html(html); 
} finally {
    $(window).load(function() {
        document.write = oldDocumentWrite
        document.writeln = oldDocumentWriteln
    })
}

Source

Setting focus to iframe contents

Try listening for events in the parent document and passing the event to a handler in the iframe document.

How can I remove a child node in HTML using JavaScript?

You should be able to use the .RemoveNode method of the node or the .RemoveChild method of the parent node.

What is DOM element?

Document object model.
The DOM is the way Javascript sees its containing pages' data. It is an object that includes how the HTML/XHTML/XML is formatted, as well as the browser state.

A DOM element is something like a DIV, HTML, BODY element on a page. You can add classes to all of these using CSS, or interact with them using JS.

How to show Page Loading div until the page has finished loading?

Default the contents to display:none and then have an event handler that sets it to display:block or similar after it's fully loaded. Then have a div that's set to display:block with "Loading" in it, and set it to display:none in the same event handler as before.

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

for (int i = 0; i < nodeList.getLength(); i++)

change to

for (int i = 0, len = nodeList.getLength(); i < len; i++)

to be more efficient.

The second way of javanna answer may be the best as it tends to use a flatter, predictable memory model.

How to convert String to DOM Document object in java?

you can try

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><node1></node1></root>"));

Document doc = db.parse(is);

refer this http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm

Finding element's position relative to the document

You can use element.getBoundingClientRect() to retrieve element position relative to the viewport.

Then use document.documentElement.scrollTop to calculate the viewport offset.

The sum of the two will give the element position relative to the document:

element.getBoundingClientRect().top + document.documentElement.scrollTop

How to insert an element after another element in JavaScript without using a library?

You can actually a method called after() in newer version of Chrome, Firefox and Opera. The downside of this method is that Internet Explorer doesn't support it yet.

Example:

// You could create a simple node
var node = document.createElement('p')

// And then get the node where you want to append the created node after
var existingNode = document.getElementById('id_of_the_element')

// Finally you can append the created node to the exisitingNode
existingNode.after(node)

A simple HTML Code to test that is:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
     <p id='up'>Up</p>_x000D_
    <p id="down">Down</p>_x000D_
  <button id="switchBtn" onclick="switch_place()">Switch place</button>_x000D_
  <script>_x000D_
    function switch_place(){_x000D_
      var downElement = document.getElementById("down")_x000D_
      var upElement = document.getElementById("up")_x000D_
      downElement.after(upElement);_x000D_
      document.getElementById('switchBtn').innerHTML = "Switched!"_x000D_
    }_x000D_
  </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

As expected, it moves the up element after the down element

Adding an onclick event to a table row

I was trying to select a table row, so that it can be easily copied to the clipboard and then pasted in Excel. Below is a small adaptation of your solution.

References:

<!DOCTYPE html>
<html>
<body>

<div>
    <table id="tableId" border=1>
      <tbody>
        <tr><td>Item <b>A1</b></td><td>Item <b>B1</b></td></tr>
        <tr><td>Item <b>A2</b></td><td>Item <b>B2</b></td></tr>
        <tr><td>Item <b>A3</b></td><td>Item <b>B3</b></td></tr>
      </tbody>
    </table>
</div>

<script>
function addRowHandlers() {
    var table = document.getElementById("tableId");
    var rows = table.getElementsByTagName("tr");
    for (i = 0; i < rows.length; i++) {
        var currentRow = table.rows[i];
        var createClickHandler = 
            function(row) 
            {
                return function() { 
                                        var cell = row.getElementsByTagName("td")[0];
                                        var id = cell.innerHTML;

                                        var cell1 = row.getElementsByTagName("td")[1];
                                        var id2 = cell1.innerHTML;
                                        // alert(id + " - " + id2);
                                        window.prompt("Copy to clipboard: Ctrl+C, Enter", "<table><tr><td>" + id + "</td><td>" + id2 + "</td></tr></table>")
                                 };
            };

        currentRow.onclick = createClickHandler(currentRow);
    }
}
window.onload = addRowHandlers();
</script>
</body>
</html> 

Get elements by attribute when querySelectorAll is not available without using libraries?

That works too:

document.querySelector([attribute="value"]);

So:

document.querySelector([data-foo="bar"]);

How do I get the value of text input field using JavaScript?

Also you can, call by tags names, like this: form_name.input_name.value; So you will have the specific value of determined input in a specific form.

Getting or changing CSS class property with Javascript using DOM style

I think this is not the best way, but in my cases other methods did not work.

stylesheet = document.styleSheets[0]
stylesheet.insertRule(".have-border { border: 1px solid black;}", 0);

Example from https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript

How to add DOM element script to head section?

This is an old question, and I know its asking specifically about adding a script tag into the head, however based on the OPs explanation they actually just intend to execute some JS code which has been obtained via some other JS function.

This is much simpler than adding a script tag into the page.

Simply:

eval(decoded);

Eval will execute a string of JS in-line, without any need to add it to the DOM at all.

I don't think there's ever really a need to add an in-line script tag to the DOM after page load.

More info here: http://www.w3schools.com/jsref/jsref_eval.asp

Getting XML Node text value with Java DOM

If you are open to vtd-xml, which excels at both performance and memory efficiency, below is the code to do what you are looking for...in both XPath and manual navigation... the overall code is much concise and easier to understand ...

import com.ximpleware.*;
public class queryText {
    public static void main(String[] s) throws VTDException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", true))
            return;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        // first manually navigate
        if(vn.toElement(VTDNav.FC,"tag")){
            int i= vn.getText();
            if (i!=-1){
                System.out.println("text ===>"+vn.toString(i));
            }
            if (vn.toElement(VTDNav.NS,"tag")){
                i=vn.getText();
                System.out.println("text ===>"+vn.toString(i));
            }
        }

        // second version use XPath
        ap.selectXPath("/add/tag/text()");
        int i=0;
        while((i=ap.evalXPath())!= -1){
            System.out.println("text node ====>"+vn.toString(i));
        }
    }
}

How do I programmatically click on an element in JavaScript?

For firefox links appear to be "special". The only way I was able to get this working was to use the createEvent described here on MDN and call the initMouseEvent function. Even that didn't work completely, I had to manually tell the browser to open a link...

var theEvent = document.createEvent("MouseEvent");
theEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
var element = document.getElementById('link');
element.dispatchEvent(theEvent);

while (element)
{
    if (element.tagName == "A" && element.href != "")
    {
        if (element.target == "_blank") { window.open(element.href, element.target); }
        else { document.location = element.href; }
        element = null;
    }
    else
    {
        element = element.parentElement;
    }
}

Focus Input Box On Load

There are two parts to your question.

1) How to focus an input on page load?

You can just add the autofocus attribute to the input.

<input id="myinputbox" type="text" autofocus>

However, this might not be supported in all browsers, so we can use javascript.

window.onload = function() {
  var input = document.getElementById("myinputbox").focus();
}

2) How to place cursor at the end of the input text?

Here's a non-jQuery solution with some borrowed code from another SO answer.

function placeCursorAtEnd() {
  if (this.setSelectionRange) {
    // Double the length because Opera is inconsistent about 
    // whether a carriage return is one character or two.
    var len = this.value.length * 2;
    this.setSelectionRange(len, len);
  } else {
    // This might work for browsers without setSelectionRange support.
    this.value = this.value;
  }

  if (this.nodeName === "TEXTAREA") {
    // This will scroll a textarea to the bottom if needed
    this.scrollTop = 999999;
  }
};

window.onload = function() {
  var input = document.getElementById("myinputbox");

  if (obj.addEventListener) {
    obj.addEventListener("focus", placeCursorAtEnd, false);
  } else if (obj.attachEvent) {
    obj.attachEvent('onfocus', placeCursorAtEnd);
  }

  input.focus();
}

Here's an example of how I would accomplish this with jQuery.

<input type="text" autofocus>

<script>
$(function() {
  $("[autofocus]").on("focus", function() {
    if (this.setSelectionRange) {
      var len = this.value.length * 2;
      this.setSelectionRange(len, len);
    } else {
      this.value = this.value;
    }
    this.scrollTop = 999999;
  }).focus();
});
</script>

What is the difference between properties and attributes in HTML?

The answers already explain how attributes and properties are handled differently, but I really would like to point out how totally insane this is. Even if it is to some extent the spec.

It is crazy, to have some of the attributes (e.g. id, class, foo, bar) to retain only one kind of value in the DOM, while some attributes (e.g. checked, selected) to retain two values; that is, the value "when it was loaded" and the value of the "dynamic state". (Isn't the DOM supposed to be to represent the state of the document to its full extent?)

It is absolutely essential, that two input fields, e.g. a text and a checkbox behave the very same way. If the text input field does not retain a separate "when it was loaded" value and the "current, dynamic" value, why does the checkbox? If the checkbox does have two values for the checked attribute, why does it not have two for its class and id attributes? If you expect to change the value of a text *input* field, and you expect the DOM (i.e. the "serialized representation") to change, and reflect this change, why on earth would you not expect the same from an input field of type checkbox on the checked attribute?

The differentiation, of "it is a boolean attribute" just does not make any sense to me, or is, at least not a sufficient reason for this.

setting the id attribute of an input element dynamically in IE: alternative for setAttribute method

The documentation says:

When you need to set attributes that are also mapped to a JavaScript dot-property (such as href, style, src or event-handlers), favour that mapping instead.

So, just change id, value assignment and you should be done.

How can I check if an element exists in the visible DOM?

A simple solution with jQuery:

$('body').find(yourElement)[0] != null

How to check in Javascript if one element is contained within another

You can use the contains method

var result = parent.contains(child);

or you can try to use compareDocumentPosition()

var result = nodeA.compareDocumentPosition(nodeB);

The last one is more powerful: it return a bitmask as result.

How can I change an element's class with JavaScript?

You can use node.className like so:

document.getElementById('foo').className = 'bar';

This should work in IE5.5 and up according to PPK.

How to Implement DOM Data Binding in JavaScript

Late to the party, especially since I've written 2 libs related months/years ago, I'll mention them later, but still looks relevant to me. To make it really short spoiler, the technologies of my choice are:

  • Proxy for observation of model
  • MutationObserver for the tracking changes of DOM (for binding reasons, not value changes)
  • value changes (view to model flow) are handled via regular addEventListener handlers

IMHO, in addition to the OP, it is important that data binding implementation will:

  • handle different app lifecycle cases (HTML first, then JS, JS first then HTML, dynamic attributes change etc)
  • allow deep binding of model, so that one may bind user.address.block
  • arrays as a model should be supported correctly (shift, splice and alike)
  • handle ShadowDOM
  • attempt to be as easy for technology replacement as possible, thus any templating sub-languages are a non-future-changes-friendly approach since it's too heavily coupled with framework

Taking all those into consideration, in my opinion makes it impossible to just throw few dozens of JS lines. I've tried to do it as a pattern rather than lib - didn't work for me.

Next, having Object.observe is removed, and yet given that observation of model is crucial part - this whole part MUST be concern-separated to another lib. Now to the point of principals of how I took this problem - exactly as OP asked:

Model (JS part)

My take for model observation is Proxy, it is the only sane way to make it work, IMHO. Fully featured observer deserves it's own library, so I've developed object-observer library for that sole purpose.

The model/s should be registered via some dedicated API, that's the point where POJOs turn into Observables, can't see any shortcut here. The DOM elements which are considered to be a bound views (see below), are updated with the values of the model/s at first and then upon each data change.

Views (HTML part)

IMHO, the cleanest way to express the binding, is via attributes. Many did this before and many will do after, so no news here, this is just a right way to do that. In my case I've gone with the following syntax: <span data-tie="modelKey:path.to.data => targerProperty"></span>, but this is less important. What is important to me, no complex scripting syntax in the HTML - this is wrong, again, IMHO.

All the elements designated to be a bound views shall be collected at first. It looks inevitable to me from a performance side to manage some internal mapping between the models and the views, seems a right case where memory + some management should be sacrificed to save runtime lookups and updates.

The views are updated at first from the model, if available and upon later model changes, as we said. More yet, the whole DOM should be observed by means of MutationObserver in order to react (bind/unbind) on the dynamically added/remove/changed elements. Furthermore, all this, should be replicated into the ShadowDOM (open one, of course) in order to not leave unbound black holes.

The list of specifics may go further indeed, but those are in my opinion the main principals that would made data binding implemented with a good balance of feature completeness from one and sane simplicity from the other side.

And thus, in addition to the object-observer mentioned above, I've written indeed also data-tier library, that implements data binding along the above mentioned concepts.

How to get the HTML for a DOM element in javascript

old question but for newcomers that come around :

document.querySelector('div').outerHTML

Get selected text from a drop-down list (select box) using jQuery

Try this:

$("#myselect :selected").text();

For an ASP.NET dropdown you can use the following selector:

$("[id*='MyDropDownId'] :selected")

How do I toggle an element's class in pure JavaScript?

This one works in earlier versions of IE also.

_x000D_
_x000D_
function toogleClass(ele, class1) {_x000D_
  var classes = ele.className;_x000D_
  var regex = new RegExp('\\b' + class1 + '\\b');_x000D_
  var hasOne = classes.match(regex);_x000D_
  class1 = class1.replace(/\s+/g, '');_x000D_
  if (hasOne)_x000D_
    ele.className = classes.replace(regex, '');_x000D_
  else_x000D_
    ele.className = classes + class1;_x000D_
}
_x000D_
.red {_x000D_
  background-color: red_x000D_
}_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  margin-bottom: 10px;_x000D_
  border: 1px solid black;_x000D_
}
_x000D_
<div class="does red redAnother " onclick="toogleClass(this, 'red')"></div>_x000D_
_x000D_
<div class="does collapse navbar-collapse " onclick="toogleClass(this, 'red')"></div>
_x000D_
_x000D_
_x000D_

Appending HTML string to the DOM

Use insertAdjacentHTML if it's available, otherwise use some sort of fallback. insertAdjacentHTML is supported in all current browsers.

div.insertAdjacentHTML( 'beforeend', str );

Live demo: http://jsfiddle.net/euQ5n/

How do I select text nodes with jQuery?

if you want to strip all tags, then try this

function:

String.prototype.stripTags=function(){
var rtag=/<.*?[^>]>/g;
return this.replace(rtag,'');
}

usage:

var newText=$('selector').html().stripTags();

Can I position an element fixed relative to parent?

This solution works for me! Reference to the original detailed answer: https://stackoverflow.com/a/11833892/5385623

css:

.level1 {
    position: relative;
}


.level2 {
    position: absolute;
}


.level3 {
    position: fixed;
    /* Do not set top / left! */
}

html:

<div class='level1'>
    <div class='level2'>
        <div class='level3'>
            Content
        </div>
    </div>
</div>

Get an element by index in jQuery

You can use jQuery's .eq() method to get the element with a certain index.

$('ul li').eq(index).css({'background-color':'#343434'});

Is it possible to use jQuery to read meta tags

I just tried this, and this could be a jQuery version-specific error, but

$("meta[property=twitter:image]").attr("content");

resulted in the following syntax error for me:

Error: Syntax error, unrecognized expression: meta[property=twitter:image]

Apparently it doesn't like the colon. I was able to fix it by using double and single quotes like this:

$("meta[property='twitter:image']").attr("content");

(jQuery version 1.8.3 -- sorry, I would have made this a comment to @Danilo, but it won't let me comment yet)

How do you check if a JavaScript Object is a DOM Object?

In Firefox, you can use the instanceof Node. That Node is defined in DOM1.

But that is not that easy in IE.

  1. "instanceof ActiveXObject" only can tell that it is a native object.
  2. "typeof document.body.appendChild=='object'" tell that it may be DOM object, but also can be something else have same function.

You can only ensure it is DOM element by using DOM function and catch if any exception. However, it may have side effect (e.g. change object internal state/performance/memory leak)

Simple way to get element by id within a div tag?

Sample Html code   
 <div id="temp">
        F1 <input type="text" value="111"/><br/>
        F2 <input type="text" value="222"/><br/>
        F3 <input type="text" value="333"/><br/>
        Type <select>
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
        </select>
        <input type="button" value="Go" onclick="getVal()">
    </div>

Javascript

    function  getVal()
    {
        var test = document.getElementById("temp").getElementsByTagName("input");
        alert("Number of Input Elements "+test.length);
        for(var i=0;i<test.length;i++)
        {
          if(test[i].type=="text")
          {
            alert(test[i].value);
          }
       }
      test = document.getElementById("temp").getElementsByTagName("select");
      alert("Select box  "+test[0].options[test[0].selectedIndex].text);
    }

By providing different tag names we can get all the values from the div.

JavaScript DOM remove element

In most browsers, there's a slightly more succinct way of removing an element from the DOM than calling .removeChild(element) on its parent, which is to just call element.remove(). In due course, this will probably become the standard and idiomatic way of removing an element from the DOM.

The .remove() method was added to the DOM Living Standard in 2011 (commit), and has since been implemented by Chrome, Firefox, Safari, Opera, and Edge. It was not supported in any version of Internet Explorer.

If you want to support older browsers, you'll need to shim it. This turns out to be a little irritating, both because nobody seems to have made a all-purpose DOM shim that contains these methods, and because we're not just adding the method to a single prototype; it's a method of ChildNode, which is just an interface defined by the spec and isn't accessible to JavaScript, so we can't add anything to its prototype. So we need to find all the prototypes that inherit from ChildNode and are actually defined in the browser, and add .remove to them.

Here's the shim I came up with, which I've confirmed works in IE 8.

(function () {
    var typesToPatch = ['DocumentType', 'Element', 'CharacterData'],
        remove = function () {
            // The check here seems pointless, since we're not adding this
            // method to the prototypes of any any elements that CAN be the
            // root of the DOM. However, it's required by spec (see point 1 of
            // https://dom.spec.whatwg.org/#dom-childnode-remove) and would
            // theoretically make a difference if somebody .apply()ed this
            // method to the DOM's root node, so let's roll with it.
            if (this.parentNode != null) {
                this.parentNode.removeChild(this);
            }
        };

    for (var i=0; i<typesToPatch.length; i++) {
        var type = typesToPatch[i];
        if (window[type] && !window[type].prototype.remove) {
            window[type].prototype.remove = remove;
        }
    }
})();

This won't work in IE 7 or lower, since extending DOM prototypes isn't possible before IE 8. I figure, though, that on the verge of 2015 most people needn't care about such things.

Once you've included them shim, you'll be able to remove a DOM element element from the DOM by simply calling

element.remove();

Changing CSS Values with Javascript

Gathering the code in the answers, I wrote this function that seems running well on my FF 25.

function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
  /* returns the value of the element style of the rule in the stylesheet
  *  If no value is given, reads the value
  *  If value is given, the value is changed and returned
  *  If '' (empty string) is given, erases the value.
  *  The browser will apply the default one
  *
  * string stylesheet: part of the .css name to be recognized, e.g. 'default'
  * string selectorText: css selector, e.g. '#myId', '.myClass', 'thead td'
  * string style: camelCase element style, e.g. 'fontSize'
  * string value optionnal : the new value
  */
  var CCSstyle = undefined, rules;
  for(var m in document.styleSheets){
    if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
     rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
     for(var n in rules){
       if(rules[n].selectorText == selectorText){
         CCSstyle = rules[n].style;
         break;
       }
     }
     break;
    }
  }
  if(value == undefined)
    return CCSstyle[style]
  else
    return CCSstyle[style] = value
}

This is a way to put values in the css that will be used in JS even if not understood by the browser. e.g. maxHeight for a tbody in a scrolled table.

Call :

CCSStylesheetRuleStyle('default', "#mydiv", "height");

CCSStylesheetRuleStyle('default', "#mydiv", "color", "#EEE");

Angular2, what is the correct way to disable an anchor element?

For [routerLink] you can use:

Adding this CSS should do what you want:

a.disabled {
   pointer-events: none;
   cursor: not-allowed; 
}

This should fix the issue mentioned by @MichelLiu in the comments:

<a href="#" [class.disabled]="isDisabled(link)"
    (keydown.enter)="!isDisabled(link)">{{ link.name }}</a>

Another approach

<a [routerLink]="['Other']" *ngIf="!isDisabled(link)">{{ link.name }}</a>
<a  *ngIf="isDisabled(link)">{{ link.name }}</a>  

Plunker example

How may I sort a list alphabetically using jQuery?

HTML

<ul id="list">
    <li>alpha</li>
    <li>gamma</li>
    <li>beta</li>
</ul>

JavaScript

function sort(ul) {
    var ul = document.getElementById(ul)
    var liArr = ul.children
    var arr = new Array()
    for (var i = 0; i < liArr.length; i++) {
        arr.push(liArr[i].textContent)
    }
    arr.sort()
    arr.forEach(function(content, index) {
        liArr[index].textContent = content
    })
}

sort("list")

JSFiddle Demo https://jsfiddle.net/97oo61nw/

Here we are push all values of li elements inside ul with specific id (which we provided as function argument) to array arr and sort it using sort() method which is sorted alphabetical by default. After array arr is sorted we are loop this array using forEach() method and just replace text content of all li elements with sorted content

How to replace DOM element in place using Javascript?

I had a similar issue and found this thread. Replace didn't work for me, and going by the parent was difficult for my situation. Inner Html replaced the children, which wasn't what I wanted either. Using outerHTML got the job done. Hope this helps someone else!

currEl = <div>hello</div>
newElem = <span>Goodbye</span>
currEl.outerHTML = newElem
# currEl = <span>Goodbye</span>

Getting the document object of an iframe

Try the following

var doc=document.getElementById("frame").contentDocument;

// Earlier versions of IE or IE8+ where !DOCTYPE is not specified
var doc=document.getElementById("frame").contentWindow.document;

Note: AndyE pointed out that contentWindow is supported by all major browsers so this may be the best way to go.

Note2: In this sample you won't be able to access the document via any means. The reason is you can't access the document of an iframe with a different origin because it violates the "Same Origin" security policy

How do you set the document title in React?

As others have mentioned, you can use document.title = 'My new title' and React Helmet to update the page title. Both of these solutions will still render the initial 'React App' title before scripts are loaded.

If you are using create-react-app the initial document title is set in the <title> tag /public/index.html file.

You can edit this directly or use a placeholder which will be filled from environmental variables:

/.env:

REACT_APP_SITE_TITLE='My Title!'
SOME_OTHER_VARS=...

If for some reason I wanted a different title in my development environment -

/.env.development:

REACT_APP_SITE_TITLE='**DEVELOPMENT** My TITLE! **DEVELOPMENT**'
SOME_OTHER_VARS=...

/public/index.html:

<!DOCTYPE html>
<html lang="en">
    <head>
         ...
         <title>%REACT_APP_SITE_TITLE%</title>
         ...
     </head>
     <body>
         ...
     </body>
</html>

This approach also means that I can read the site title environmental variable from my application using the global process.env object, which is nice:

console.log(process.env.REACT_APP_SITE_TITLE_URL);
// My Title!

See: Adding Custom Environment Variables

DOM element to corresponding vue.js component

If you're starting with a DOM element, check for a __vue__ property on that element. Any Vue View Models (components, VMs created by v-repeat usage) will have this property.

You can use the "Inspect Element" feature in your browsers developer console (at least in Firefox and Chrome) to view the DOM properties.

Hope that helps!

Jackson Vs. Gson

Jackson and Gson are the most complete Java JSON packages regarding actual data binding support; many other packages only provide primitive Map/List (or equivalent tree model) binding. Both have complete support for generic types, as well, as enough configurability for many common use cases.

Since I am more familiar with Jackson, here are some aspects where I think Jackson has more complete support than Gson (apologies if I miss a Gson feature):

  • Extensive annotation support; including full inheritance, and advanced "mix-in" annotations (associate annotations with a class for cases where you can not directly add them)
  • Streaming (incremental) reading, writing, for ultra-high performance (or memory-limited) use cases; can mix with data binding (bind sub-trees) -- EDIT: latest versions of Gson also include streaming reader
  • Tree model (DOM-like access); can convert between various models (tree <-> java object <-> stream)
  • Can use any constructors (or static factory methods), not just default constructor
  • Field and getter/setter access (earlier gson versions only used fields, this may have changed)
  • Out-of-box JAX-RS support
  • Interoperability: can also use JAXB annotations, has support/work-arounds for common packages (joda, ibatis, cglib), JVM languages (groovy, clojure, scala)
  • Ability to force static (declared) type handling for output
  • Support for deserializing polymorphic types (Jackson 1.5) -- can serialize AND deserialize things like List correctly (with additional type information)
  • Integrated support for binary content (base64 to/from JSON Strings)

See whether an item appears more than once in a database column

How about:

select salesid from AXDelNotesNoTracking group by salesid having count(*) > 1;

Python: Find a substring in a string and returning the index of the substring

There's a builtin method find on string objects.

s = "Happy Birthday"
s2 = "py"

print(s.find(s2))

Python is a "batteries included language" there's code written to do most of what you want already (whatever you want).. unless this is homework :)

find returns -1 if the string cannot be found.

Radio button validation in javascript

Full validation example with javascript:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Radio button: full validation example with javascript</title>
        <script>
            function send() {
                var genders = document.getElementsByName("gender");
                if (genders[0].checked == true) {
                    alert("Your gender is male");
                } else if (genders[1].checked == true) {
                    alert("Your gender is female");
                } else {
                    // no checked
                    var msg = '<span style="color:red;">You must select your gender!</span><br /><br />';
                    document.getElementById('msg').innerHTML = msg;
                    return false;
                }
                return true;
            }

            function reset_msg() {
                document.getElementById('msg').innerHTML = '';
            }
        </script>
    </head>
    <body>
        <form action="" method="POST">
            <label>Gender:</label>
            <br />
            <input type="radio" name="gender" value="m" onclick="reset_msg();" />Male
            <br />
            <input type="radio" name="gender" value="f" onclick="reset_msg();" />Female
            <br />
            <div id="msg"></div>
            <input type="submit" value="send>>" onclick="return send();" />
        </form>
    </body>
</html>

Regards,

Fernando

Difference between two dates in Python

Use - to get the difference between two datetime objects and take the days member.

from datetime import datetime

def days_between(d1, d2):
    d1 = datetime.strptime(d1, "%Y-%m-%d")
    d2 = datetime.strptime(d2, "%Y-%m-%d")
    return abs((d2 - d1).days)

How to calculate the angle between a line and the horizontal axis?

I have found a solution in Python that is working well !

from math import atan2,degrees

def GetAngleOfLineBetweenTwoPoints(p1, p2):
    return degrees(atan2(p2 - p1, 1))

print GetAngleOfLineBetweenTwoPoints(1,3)

Dynamic variable names in Bash

for varname=$prefix_suffix format, just use:

varname=${prefix}_suffix

How do I do a Date comparison in Javascript?

JavaScript's dates can be compared using the same comparison operators the rest of the data types use: >, <, <=, >=, ==, !=, ===, !==.

If you have two dates A and B, then A < B if A is further back into the past than B.

But it sounds like what you're having trouble with is turning a string into a date. You do that by simply passing the string as an argument for a new Date:

var someDate = new Date("12/03/2008");

or, if the string you want is the value of a form field, as it seems it might be:

var someDate = new Date(document.form1.Textbox2.value);

Should that string not be something that JavaScript recognizes as a date, you will still get a Date object, but it will be "invalid". Any comparison with another date will return false. When converted to a string it will become "Invalid Date". Its getTime() function will return NaN, and calling isNaN() on the date itself will return true; that's the easy way to check if a string is a valid date.

How to get request URI without context path?

request.getRequestURI().substring(request.getContextPath().length())

Aggregate a dataframe on a given column and display another column

First, you split the data using split:

split(z,z$Group)

Than, for each chunk, select the row with max Score:

lapply(split(z,z$Group),function(chunk) chunk[which.max(chunk$Score),])

Finally reduce back to a data.frame do.calling rbind:

do.call(rbind,lapply(split(z,z$Group),function(chunk) chunk[which.max(chunk$Score),]))

Result:

  Group Score Info
1     1     3    c
2     2     4    d

One line, no magic spells, fast, result has good names =)

Capitalize the first letter of string in AngularJs

if you want capitalize each word from string (in progress -> In Progress), you can use array like this.

.filter('capitalize', function() {
    return function(input) {
        return (!!input) ? input.split(' ').map(function(wrd){return wrd.charAt(0).toUpperCase() + wrd.substr(1).toLowerCase();}).join(' ') : '';
    }
});

default value for struct member in C

If you only use this structure for once, i.e. create a global/static variable, you can remove typedef, and initialized this variable instantly:

struct {
    int id;
    char *name;
} employee = {
    .id = 0,
    .name = "none"
};

Then, you can use employee in your code after that.

How can I view the shared preferences file using Android Studio?

From Android Studio , start Android Device Monitor, go to File Explorer, and browse "/data/data/< name of your package >/shared_prefs/". You will find the XML there... and also you can copy it for inspection.

If you have a non-rooted device it's not possible to do that directly from Android Studio. However, you can access the file with adb shell as long as your application is the debug version.

adb shell
run-as your.app.id
chmod 777 shared_prefs/your.app.id_preferences.xml
exit # return to default user
cp /data/data/your.app.id/shared_prefs/your.app.id_preferences.xml /sdcard

After that you can pull the file from /sdcard directory with adb.

Encode html entities in javascript

If you want to avoid encode html entities more than once

function encodeHTML(str){
    return str.replace(/([\u00A0-\u9999<>&])(.|$)/g, function(full, char, next) {
      if(char !== '&' || next !== '#'){
        if(/[\u00A0-\u9999<>&]/.test(next))
          next = '&#' + next.charCodeAt(0) + ';';

        return '&#' + char.charCodeAt(0) + ';' + next;
      }

      return full;
    });
}

function decodeHTML(str){
    return str.replace(/&#([0-9]+);/g, function(full, int) {
        return String.fromCharCode(parseInt(int));
    });
}

# Example

var text = "<a>Content &#169; <#>&<&#># </a>";

text = encodeHTML(text);
console.log("Encode 1 times: " + text);

// &#60;a&#62;Content &#169; &#60;#&#62;&#38;&#60;&#38;#&#62;# &#60;/a&#62;

text = encodeHTML(text);
console.log("Encode 2 times: " + text);

// &#60;a&#62;Content &#169; &#60;#&#62;&#38;&#60;&#38;#&#62;# &#60;/a&#62;

text = decodeHTML(text);
console.log("Decoded: " + text);

// <a>Content © <#>&<&#># </a>

Click through div to underlying elements

  1. Hide overlaying the element
  2. Determine cursor coordinates
  3. Get element on those coordinates
  4. Trigger click on element
  5. Show overlaying element again
$('#elementontop').click(e => {
    $('#elementontop').hide();
    $(document.elementFromPoint(e.clientX, e.clientY)).trigger("click");
    $('#elementontop').show();
});

HTTP get with headers using RestTemplate

The RestTemplate getForObject() method does not support setting headers. The solution is to use the exchange() method.

So instead of restTemplate.getForObject(url, String.class, param) (which has no headers), use

HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...

HttpEntity entity = new HttpEntity(headers);

ResponseEntity<String> response = restTemplate.exchange(
    url, HttpMethod.GET, entity, String.class, param);

Finally, use response.getBody() to get your result.

This question is similar to this question.

JAVA Unsupported major.minor version 51.0

The Java runtime you try to execute your program with is an earlier version than Java 7 which was the target you compile your program for.

For Ubuntu use

apt-get install openjdk-7-jdk

to get Java 7 as default. You may have to uninstall openjdk-6 first.

How do I convert a factor into date format?

Take a look at the formats in ?strptime

R> foo <-  factor("1/15/2006 0:00:00")
R> foo <- as.Date(foo, format = "%m/%d/%Y %H:%M:%S")                                           
R> foo                                                                                       
 [1] "2006-01-15"                                                                             
R> class(foo)                                                                                
 [1] "Date"  

Note that this will work even if foo starts out as a character. It will also work if using other date formats (as.POSIXlt, as.POSIXct).

Is there a way to take the first 1000 rows of a Spark Dataframe?

The method you are looking for is .limit.

Returns a new Dataset by taking the first n rows. The difference between this function and head is that head returns an array while limit returns a new Dataset.

Example usage:

df.limit(1000)

How to check if a file exists in Ansible?

This can be achieved with the stat module to skip the task when file exists.

- hosts: servers
  tasks:
  - name: Ansible check file exists.
    stat:
      path: /etc/issue
    register: p
  - debug:
      msg: "File exists..."
    when: p.stat.exists
  - debug:
      msg: "File not found"
    when: p.stat.exists == False

'No JUnit tests found' in Eclipse

junit4 require that test classname should be use Test as suffix.

Why Does OAuth v2 Have Both Access and Refresh Tokens?

This answer has been put together by the help of two senior devs (John Brayton and David Jennes).

The main reason to use a refresh token is to reduce the attack surface.

Let's suppose there is no refresh key and let’s go through this example:

A building has 80 doors. All doors are opened with the same key. The key changes every 30 minutes. At the end of the 30 minutes I have to give the old key to the keymaker and get a new key.

If I’m the hacker and get your key, then at the end of the 30 minutes, I’ll courier that to the keymaker and get a new key. I’ll be able to continuously open all doors regardless of the key changing.

Question: During the 30 minutes, how many hacking opportunities did I have against the key? I had 80 hacking opportunities, each time you used the key (think of this as making a network request and passing the access token to identify yourself). So that’s 80X attack surface.

Now let’s go through the same example but this time let’s assume there’s a refresh key.

A building has 80 doors. All doors are opened with the same key. The key changes every 30 minutes. To get a new key, I can’t pass the old access token. I must only pass the refresh key.

If I’m the hacker and get your key, I can use it for 30 minutes, but at the end of the 30 minutes sending it to the keymaker has no value. If I do, then the keymaker would just say "This token is expired. You need to refresh the token." To be able to extend my hack I would have to hack the courier to the keymaker. The courier has a distinct key (think of this as a refresh token).

Question: During the 30 minutes, how many hacking opportunities did I have against the refresh key? 80? No. I only had 1 hacking opportunity. During the time the courier communicates with the keymaker. So that’s 1X attack surface. I did have 80 hacking opportunities against the key, but they are no good after 30 minutes.


A server would verify an access token based on credentials and signing of (typically) a JWT.

An access token leaking is bad, but once it expires it is no longer useful to an attacker. A refresh token leaking is far worse, but presumably it is less likely. (I think there is room to question whether the likelihood of a refresh token leaking is much lower than that of an access token leaking, but that’s the idea.)

Point is that the access token is added to every request you make, whereas a refresh token is only used during the refresh flow So less chance of a MITM seeing the token

Frequency helps an attacker. Heartbleed-like potential security flaws in SSL, potential security flaws in the client, and potential security flaws in the server all make leaking possible.

In addition, if the authorization server is separate from the application server processing other client requests then that application server will never see refresh tokens. It will only see access tokens that will not live for much longer.

Compartmentalization is good for security.

Last but not least see this awesome answer


What refresh token is NOT about?

The ability to update/revoke access level through refresh tokens is a byproduct of choosing to use refresh tokens, otherwise a standalone access token could be revoked or have its access level modified when it expires and users gets a new token

implements Closeable or implements AutoCloseable

Here is the small example

public class TryWithResource {

    public static void main(String[] args) {
        try (TestMe r = new TestMe()) {
            r.generalTest();
        } catch(Exception e) {
            System.out.println("From Exception Block");
        } finally {
            System.out.println("From Final Block");
        }
    }
}



public class TestMe implements AutoCloseable {

    @Override
    public void close() throws Exception {
        System.out.println(" From Close -  AutoCloseable  ");
    }

    public void generalTest() {
        System.out.println(" GeneralTest ");
    }
}

Here is the output:

GeneralTest 
From Close -  AutoCloseable  
From Final Block

anaconda - path environment variable in windows

it turns out I was mistaken.

Solution is: in anaconda (as well as in other implementations), set the path environment variable to the directory where 'python.exe' is installed.

As a default, the python.exe file in anaconda is in:

c:\.....\anaconda

after you do that, obviously, the python command works, in my case, yielding the following.

python
Python 3.4.3 |Anaconda 2.2.0. (64|bit)|(default, Nov 7 2015), etc, etc

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

UML diagram shapes missing on Visio 2013

I had the same problem with Visio 2016. I have the standard license. I think it is very strange that you can select a "UML Sequence" template when you search for it but it then opens a blank canvas without shapes. So you don't see anything and can't select the shapes under the "More Shapes" window on the side.

So I searched the shapes in the installation directory of Visio. I found in the directory C:\Program Files\Microsoft Office\Office16\Visio Content\1033 a couple of Sequence diagram templates (ie: BASIC_UMLSEQUENCE_M.VSTX). They are using the stencil USEQME_M.vssx. I found that out by right clicking the shapes in the left window and select "Save as". I saved them in "My Documents" under "My Shapes" just like custom shapes. I can than use them in any new document that I want.

Note the capital M or U in the name of the template or stencil for US Units or Metric Units. I'm from the Netherlands so I'm using the M version.

A not really friendly way to get the shapes. But it works.

How can I enter latitude and longitude in Google Maps?

First is latitude, second longitude. Different than many constructors in mapbox.

Here are examples of formats that work:

  • Degrees, minutes, and seconds (DMS): 41°24'12.2"N 2°10'26.5"E
  • Degrees and decimal minutes (DMM): 41 24.2028, 2 10.4418
  • Decimal degrees (DD): 41.40338, 2.17403

Tips for formatting your coordinates

  • Use the degree symbol instead of “d”.
  • Use periods as decimals, not commas.
    • Incorrect: 41,40338, 2,17403.
    • Correct: 41.40338, 2.17403.
  • List your latitude coordinates before longitude coordinates.
  • Check that the first number in your latitude coordinate is between -90 and 90 and the first number in your longitude coordinate is between -180 and 180.

https://support.google.com/maps/answer/18539

How to delete a selected DataGridViewRow and update a connected database table?

I have written the following code, please take a look:

foreach (DataGridViewRow row in dataGridView1.SelectedRows)
    if (!row.IsNewRow) dataGridView1.Rows.Remove(row);

using the Index of the selected row still could work; see if the code below will do the trick:

int selectedCount = dataGridView1.SelectedRows.Count;           
while (selectedCount > 0)
{
    if (!dataGridView1.SelectedRows[0].IsNewRow)
        dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
    selectedCount--;
}

I hope this helps, regards.

Property [title] does not exist on this collection instance

A person might get this while working with factory functions, so I can confirm this is valid syntax:

$user = factory(User::class, 1)->create()->first();

You might see the collection instance error if you do something like:

$user = factory(User::class, 1)->create()->id;

so change it to:

$user = factory(User::class, 1)->create()->first()->id;

How to get the bluetooth devices as a list?

Find list of Nearby Bluetooth Devices:

Find Screenshot for the same.

enter image description here

MainActivity.java:

public class MainActivity extends ActionBarActivity {

    private ListView listView;
    private ArrayList<String> mDeviceList = new ArrayList<String>();
    private BluetoothAdapter mBluetoothAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.listView);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mBluetoothAdapter.startDiscovery();

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);

    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mDeviceList.add(device.getName() + "\n" + device.getAddress());
                Log.i("BT", device.getName() + "\n" + device.getAddress());
                listView.setAdapter(new ArrayAdapter<String>(context,
                        android.R.layout.simple_list_item_1, mDeviceList));
            }
        }
    };

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.bluetoothdemo.MainActivity" >

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"/>

</RelativeLayout>

Manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bluetoothdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Note:

Please make sure that you ask Location permission to your user and turn GPS On.

Reason: From Android 6.0 you need Location permission for Bluetooth Discovery.

More reference:

  1. https://developer.android.com/guide/topics/connectivity/bluetooth
  2. https://getlief.zendesk.com/hc/en-us/articles/360007600233-Why-does-Android-require-Location-Permissions-for-Bluetooth-

Done

How can I get a web site's favicon?

It's a good practice to minimize the number of requests each page needs. So if you need several icons, yandex can do a sprite of favicons in one query. Here is an example http://favicon.yandex.net/favicon/google.com/stackoverflow.com/yandex.net/

Xcode - Warning: Implicit declaration of function is invalid in C99

should call the function properly; like- Fibonacci:input

SSIS Connection not found in package

I had the same problem.

I use project level connection managers and my packages run correctly in SSDT but when I deployed them and execute them through a job with sql server agent, I get "Connection not found" errors.

So I deploy the project and then the problem was solved, when you use project level connection managers but just deploy a single package from that project, and you call package through sql server agent, it could not recognize your connection managers so you should determine package level connection managers or you should first deploy your project.

Font size of TextView in Android application changes on changing font size from native settings

Also note that if the textSize is set in code, calling textView.setTextSize(X) interprets the number (X) as SP. Use setTextSize(TypedValue.COMPLEX_UNIT_DIP, X) to set values in dp.

Using SVG as background image

You have set a fixed width and height in your svg tag. This is probably the root of your problem. Try not removing those and set the width and height (if needed) using CSS instead.

Array.sort() doesn't sort numbers correctly

I've tried different numbers, and it always acts as if the 0s aren't there and sorts the numbers correctly otherwise. Anyone know why?

You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

array.sort([compareFunction])

Parameters

compareFunction

Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

In the ECMAscript specification (the normative reference for the generic Javascript), ECMA-262, 3rd ed., section 15.4.4.11, the default sort order is lexicographical, although they don't come out and say it, instead giving the steps for a conceptual sort function that calls the given compare function if necessary, otherwise comparing the arguments when converted to strings:

13. If the argument comparefn is undefined, go to step 16.
14. Call comparefn with arguments x and y.
15. Return Result(14).
16. Call ToString(x).
17. Call ToString(y).
18. If Result(16) < Result(17), return -1.
19. If Result(16) > Result(17), return 1.
20. Return +0.

Check if table exists

You can use the available meta data:

  DatabaseMetaData meta = con.getMetaData();
  ResultSet res = meta.getTables(null, null, "My_Table_Name", 
     new String[] {"TABLE"});
  while (res.next()) {
     System.out.println(
        "   "+res.getString("TABLE_CAT") 
       + ", "+res.getString("TABLE_SCHEM")
       + ", "+res.getString("TABLE_NAME")
       + ", "+res.getString("TABLE_TYPE")
       + ", "+res.getString("REMARKS")); 
  }

See here for more details. Note also the caveats in the JavaDoc.

httpd-xampp.conf: How to allow access to an external IP besides localhost?

In windows all you have to do is to go to windows search Allow an app through Windows Firewall.click on Allow another app select Apache and mark public and private both . Open cmd by pressing windows button+r write cmd than in cmd write ipconfig find out your ip . than open up your browser write down your ip http://172.16..x and you will be on the xampp startup page.if you want to access your local site simply put / infront of your ip e.g http://192.168.1.x/yousite. Now you are able to access your website in private network computers .

i hope this will resolve your problem

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

Hide Button After Click (With Existing Form on Page)

This is my solution. I Hide and then confirm check

onclick="return ConfirmSubmit(this);" />

function ConfirmSubmit(sender)
    {
        sender.disabled = true;
        var displayValue = sender.style.
        sender.style.display = 'none'

        if (confirm('Seguro que desea entregar los paquetes?')) {
            sender.disabled = false
            return true;
        }

        sender.disabled = false;
        sender.style.display = displayValue;
        return false;
    }

Collection was modified; enumeration operation may not execute

I've seen many options for this but to me this one was the best.

ListItemCollection collection = new ListItemCollection();
        foreach (ListItem item in ListBox1.Items)
        {
            if (item.Selected)
                collection.Add(item);
        }

Then simply loop through the collection.

Be aware that a ListItemCollection can contain duplicates. By default there is nothing preventing duplicates being added to the collection. To avoid duplicates you can do this:

ListItemCollection collection = new ListItemCollection();
            foreach (ListItem item in ListBox1.Items)
            {
                if (item.Selected && !collection.Contains(item))
                    collection.Add(item);
            }

Full examples of using pySerial package

import serial
ser = serial.Serial(0)  # open first serial port
print ser.portstr       # check which port was really used
ser.write("hello")      # write a string
ser.close()             # close port

use https://pythonhosted.org/pyserial/ for more examples

Bad Gateway 502 error with Apache mod_proxy and Tomcat

Sample from apache conf:

#Default value is 2 minutes
**Timeout 600**
ProxyRequests off
ProxyPass /app balancer://MyApp stickysession=JSESSIONID lbmethod=bytraffic nofailover=On
ProxyPassReverse /app balancer://MyApp
ProxyTimeout 600
<Proxy balancer://MyApp>
    BalancerMember http://node1:8080/ route=node1 retry=1 max=25 timeout=600
    .........
</Proxy>

How to increment a variable on a for loop in jinja template?

You could use loop.index:

{% for i in p %}
  {{ loop.index }}
{% endfor %}

Check the template designer documentation.

In more recent versions, due to scoping rules, the following would not work:

{% set count = 1 %}
{% for i in p %}
  {{ count }}
  {% set count = count + 1 %}
{% endfor %}

Android emulator: could not get wglGetExtensionsStringARB error

I faced the similar problem. In my case I had created the new virtual device and had enabled the snapshot. I just unchecked the checkbox Go to AVD Manager -> Select the device -> click Edit and uncheck the Enabled checkbox. I hope this works.

Emulate/Simulate iOS in Linux

The only solution I can think of is to install VMWare or any other VT then install OSX on a VM.

It works pretty good for testing.

Android Google Maps API V2 Zoom to Current Location

youmap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentlocation, 16));

16 is the zoom level

Insert null/empty value in sql datetime column by default

if there is no value inserted, the default value should be null,empty

In the table definition, make this datetime column allows null, be not defining NOT NULL:

...
DateTimeColumn DateTime,
...

I HAVE ALLOWED NULL VARIABLES THOUGH.

Then , just insert NULL in this column:

INSERT INTO Table(name, datetimeColumn, ...)
VALUES('foo bar', NULL, ..);

Or, you can make use of the DEFAULT constaints:

...
DateTimeColumn DateTime DEFAULT NULL,
...

Then you can ignore it completely in the INSERT statement and it will be inserted withe the NULL value:

INSERT INTO Table(name, ...)
VALUES('foo bar', ..);

Cannot convert lambda expression to type 'string' because it is not a delegate type

I think you are missing using System.Linq; from this system class.

and also add using System.Data.Entity; to the code

Nginx: Job for nginx.service failed because the control process exited

I had the same problem when I used Vesta, which uses nginx with apache. The problem was that after applying all updates Apache started listening to 443 for https. The solution was just to comment out the 443 stuff in ports.conf. This is because nginx also uses this port.

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

To pass a pointer to an int it should be void Fun(int* pointer).

Passing a reference to an int would look like this...

void Fun(int& ref) {
   ref = 10;
}

int main() {
   int test = 5;
   cout << test << endl;  // prints 5

   Fun(test);
   cout << test << endl;  // prints 10 because Fun modified the value

   return 1;
}

Angular2 QuickStart npm start is not working correctly

Installing the packages globally is one way to do it, but this restricts you to using the same version across all projects in which they are used.

Instead, you can prefix your npm scripts with ./node_modules/.bin. In your case, the package.json would look like this:

{
  "name": "reservationsystem",
  "version": "0.0.1",
  "scripts": {
    "tsc": "./node_modules/.bin/tsc",
    "tsc:w": "npm run tsc -w",
    "lite": "./node_modules/.bin/lite-server",
    "start": "./node_modules/.bin/concurrent \"npm run tsc:w\" \"npm run lite\" "
  },
  "dependencies": {
    "a2-in-memory-web-api": "~0.1.0",
    "angular2": "2.0.0-beta.3",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.0",
    "systemjs": "0.19.17",
    "zone.js": "0.5.11"
  },
  "devDependencies": {
    "concurrently": "^1.0.0",
    "lite-server": "^2.0.1",
    "typescript": "^1.7.5"
  }
}

I think npm is supposed to supply the ./node_modules/.bin in front of each "script" command that's in that directory by default, which is why the original package.json looked the way it did. I am not sure if that feature is in every release of npm, or if there's some config setting you're supposed to specify. It'd be worth looking into!

How do I create a basic UIButton programmatically?

For Swift 2.2 (with the with the new "selector" declaration).

let btn = UIButton(type: UIButtonType.System) as UIButton
btn.frame = CGRectMake(0, 0, 100, 20) // set any frame you want
btn.setTitle("MyAction", forState: UIControlState.Normal)
btn.addTarget(self, action: #selector(MyClass.myAction(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btn)


func myAction(sender:UIButton!){
  // Some action 
}

Android XML Percent Symbol

To allow the app using formatted strings from resources you should correct your xml. So, for example

<string name="app_name">Your App name, ver.%d</string>

should be replaced with

<string name="app_name">Your App name, ver.%1$d</string>

You can see this for details.

Show and hide divs at a specific time interval using jQuery

here is a jQuery plugin I came up with:

$.fn.cycle = function(timeout){
    var $all_elem = $(this)

    show_cycle_elem = function(index){
        if(index == $all_elem.length) return; //you can make it start-over, if you want
        $all_elem.hide().eq(index).fadeIn()
        setTimeout(function(){show_cycle_elem(++index)}, timeout);
    }
    show_cycle_elem(0);
}

You need to have a common classname for all the divs you wan to cycle, use it like this:

$("div.cycleme").cycle(5000)

Default keystore file does not exist?

You must be providing the wrong path to the debug.keystore file.

Follow these steps to get the correct path and complete your command:

  1. In eclipse, click the Window menu -> Preferences -> Expand Android -> Build
  2. In the right panel, look for: Default debug keystore:
  3. Select the entire box next to the label specified in Step 2

And finally, use the path you just copied from Step 3 to construct your command:

For example, in my case, it would be:

C:\Program Files\Java\jre7\bin>keytool -list -v -keystore "C:\Users\Siddharth Lele.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

UPDATED:

If you had already followed the steps mentioned above, the only other solution is to delete the debug.keystore and let Eclipse recreate it for you.

Step 1: Go to the path where your keystore is stored. In your case, C:\Users\Suresh\.android\debug.keystore

Step 2: Close and restart Eclipse.

Step 3 (Optional): You may need to clean your project before the debug.keystore is created again.

Source: http://www.coderanch.com/t/440920/Security/KeyTool-genkeypair-exception-Keystore-file

You can refer to this for the part about deleting your debug.keystore file: "Debug certificate expired" error in Eclipse Android plugins

Working copy locked error in tortoise svn while committing

  1. Right click on folder.
  2. TortoiseSVN->Check for modifications.
  3. Click on the Check repository button.
  4. Break lock on all files returned.

How to check the version before installing a package using apt-get?

Also, the apt-show-versions package (installed separately) parses dpkg information about what is installed and tells you if packages are up to date.

Example..

$ sudo apt-show-versions --regex chrome
google-chrome-stable/stable upgradeable from 32.0.1700.102-1 to 35.0.1916.114-1
xserver-xorg-video-openchrome/quantal-security uptodate 1:0.3.1-0ubuntu1.12.10.1
$

What is the role of the package-lock.json?

package-lock.json: It contains the exact version details that is currently installed for your Application.

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

In short, yes, the order is preserved. In long:

In general the following definitions will always apply to objects like lists:

A list is a collection of elements that can contain duplicate elements and has a defined order that generally does not change unless explicitly made to do so. stacks and queues are both types of lists that provide specific (often limited) behavior for adding and removing elements (stacks being LIFO, queues being FIFO). Lists are practical representations of, well, lists of things. A string can be thought of as a list of characters, as the order is important ("abc" != "bca") and duplicates in the content of the string are certainly permitted ("aaa" can exist and != "a").

A set is a collection of elements that cannot contain duplicates and has a non-definite order that may or may not change over time. Sets do not represent lists of things so much as they describe the extent of a certain selection of things. The internal structure of set, how its elements are stored relative to each other, is usually not meant to convey useful information. In some implementations, sets are always internally sorted; in others the ordering is simply undefined (usually depending on a hash function).

Collection is a generic term referring to any object used to store a (usually variable) number of other objects. Both lists and sets are a type of collection. Tuples and Arrays are normally not considered to be collections. Some languages consider maps (containers that describe associations between different objects) to be a type of collection as well.

This naming scheme holds true for all programming languages that I know of, including Python, C++, Java, C#, and Lisp (in which lists not keeping their order would be particularly catastrophic). If anyone knows of any where this is not the case, please just say so and I'll edit my answer. Note that specific implementations may use other names for these objects, such as vector in C++ and flex in ALGOL 68 (both lists; flex is technically just a re-sizable array).

If there is any confusion left in your case due to the specifics of how the + sign works here, just know that order is important for lists and unless there is very good reason to believe otherwise you can pretty much always safely assume that list operations preserve order. In this case, the + sign behaves much like it does for strings (which are really just lists of characters anyway): it takes the content of a list and places it behind the content of another.

If we have

list1 = [0, 1, 2, 3, 4]
list2 = [5, 6, 7, 8, 9]

Then

list1 + list2

Is the same as

[0, 1, 2, 3, 4] + [5, 6, 7, 8, 9]

Which evaluates to

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Much like

"abdcde" + "fghijk"

Produces

"abdcdefghijk"

How to display a date as iso 8601 format with PHP

The problem many times occurs with the milliseconds and final microseconds that many times are in 4 or 8 finals. To convert the DATE to ISO 8601 "date(DATE_ISO8601)" these are one of the solutions that works for me:

// In this form it leaves the date as it is without taking the current date as a reference
$dt = new DateTime();
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-14T13:35:55.191Z

// In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z');
return-> 2020-05-14T13:35:55.191Z

// Various examples:
$date_in = '2020-05-25 22:12 03.056';
$dt = new DateTime($date_in);
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-25T22:12:03.056Z

//In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z',strtotime($date_in));
// return-> 2020-05-25T14:22:05.188Z

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

removing JAVA_HOME and JAVA_JRE from environment variable is resolved the issue.

Adding event listeners to dynamically added elements using jQuery

You are dynamically generating those elements so any listener applied on page load wont be available. I have edited your fiddle with the correct solution. Basically jQuery holds the event for later binding by attaching it to the parent Element and propagating it downward to the correct dynamically created element.

$('#musics').on('change', '#want',function(e) {
    $(this).closest('.from-group').val(($('#want').is(':checked')) ? "yes" : "no");
    var ans=$(this).val();
    console.log(($('#want').is(':checked')));
});

http://jsfiddle.net/swoogie/1rkhn7ek/39/

How do I check if a Socket is currently connected in Java?

Assuming you have some level of control over the protocol, I'm a big fan of sending heartbeats to verify that a connection is active. It's proven to be the most fail proof method and will often give you the quickest notification when a connection has been broken.

TCP keepalives will work, but what if the remote host is suddenly powered off? TCP can take a long time to timeout. On the other hand, if you have logic in your app that expects a heartbeat reply every x seconds, the first time you don't get them you know the connection no longer works, either by a network or a server issue on the remote side.

See Do I need to heartbeat to keep a TCP connection open? for more discussion.

Should I write script in the body or the head of the html?

W3Schools have a nice article on this subject.

Scripts in <head>

Scripts to be executed when they are called, or when an event is triggered, are placed in functions.

Put your functions in the head section, this way they are all in one place, and they do not interfere with page content.

Scripts in <body>

If you don't want your script to be placed inside a function, or if your script should write page content, it should be placed in the body section.

How to tackle daylight savings using TimeZone in Java

This is the problem to start with:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));

The 3-letter abbreviations should be wholeheartedly avoided in favour of TZDB zone IDs. EST is Eastern Standard Time - and Standard time never observes DST; it's not really a full time zone name. It's the name used for part of a time zone. (Unfortunately I haven't come across a good term for this "half time zone" concept.)

You want a full time zone name. For example, America/New_York is in the Eastern time zone:

TimeZone zone = TimeZone.getTimeZone("America/New_York");
DateFormat format = DateFormat.getDateTimeInstance();
format.setTimeZone(zone);

System.out.println(format.format(new Date()));

How do you create a remote Git branch?

I've solved this by adding this into my bash ~/.profile:

function gitb() { git checkout -b $1 && git push --set-upstream origin $1; }

Then to start up a new local + remote branch, I write:

gitb feature/mynewbranch

This creates the branch and does the first push, not just to setup tracking (so that later git pull and git push work without extra arguments), but actually confirming that the target repo doesn't already have such branch in it.

How to vertically center content with variable height within a div?

This seems to be the best solution I’ve found to this problem, as long as your browser supports the ::before pseudo element: CSS-Tricks: Centering in the Unknown.

It doesn’t require any extra markup and seems to work extremely well. I couldn’t use the display: table method because table elements don’t obey the max-height property.

_x000D_
_x000D_
.block {_x000D_
  height: 300px;_x000D_
  text-align: center;_x000D_
  background: #c0c0c0;_x000D_
  border: #a0a0a0 solid 1px;_x000D_
  margin: 20px;_x000D_
}_x000D_
_x000D_
.block::before {_x000D_
  content: '';_x000D_
  display: inline-block;_x000D_
  height: 100%; _x000D_
  vertical-align: middle;_x000D_
  margin-right: -0.25em; /* Adjusts for spacing */_x000D_
_x000D_
  /* For visualization _x000D_
  background: #808080; width: 5px;_x000D_
  */_x000D_
}_x000D_
_x000D_
.centered {_x000D_
  display: inline-block;_x000D_
  vertical-align: middle;_x000D_
  width: 300px;_x000D_
  padding: 10px 15px;_x000D_
  border: #a0a0a0 solid 1px;_x000D_
  background: #f5f5f5;_x000D_
}
_x000D_
<div class="block">_x000D_
    <div class="centered">_x000D_
        <h1>Some text</h1>_x000D_
        <p>But he stole up to us again, and suddenly clapping his hand on my_x000D_
           shoulder, said&mdash;"Did ye see anything looking like men going_x000D_
           towards that ship a while ago?"</p>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

What is ADT? (Abstract Data Type)

ADT is a data type in which collection of data and operation works on that data . It focuses on more the concept than implementation.. It's up to you which language you use to make it visible on the earth Example: Stack is an ADT while the Array is not Stack is ADT because we can implement it by many languages, Python c c++ java and many more , while Array is built in data type

Already defined in .obj - no double inclusions

This is one of the method to overcome this issue.

  • Just put the prototype in the header files and include the header files in the .cpp files as shown below.

client.cpp

#ifndef SOCKET_CLIENT_CLASS
#define SOCKET_CLIENT_CLASS
#ifndef BOOST_ASIO_HPP
#include <boost/asio.hpp>
#endif

class SocketClient // Or whatever the name is... {

// ...

    bool read(int, char*); // Or whatever the name is...

//  ... };

#endif

client.h

bool SocketClient::read(int, char*)
{
    // Implementation  goes here...
}

main.cpp

#include <iostream>
#include <string>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include "client.h"
//              ^^ Notice this!

main.h

int main()

Receive JSON POST with PHP

$data = file_get_contents('php://input');
echo $data;

This worked for me.

Set selected radio from radio group with a value

$("input[name='mygroup'][value='5']").attr("checked", true);

How to run Maven from another directory (without cd to project dir)?

For me, works this way: mvn -f /path/to/pom.xml [goals]

What's the difference between a method and a function?

A method is on an object.
A function is independent of an object.

For Java and C#, there are only methods.
For C, there are only functions.

For C++ and Python it would depend on whether or not you're in a class.

This declaration has no storage class or type specifier in C++

This is a mistake:

m.check(side);

That code has to go inside a function. Your class definition can only contain declarations and functions.

Classes don't "run", they provide a blueprint for how to make an object.

The line Message m; means that an Orderbook will contain Message called m, if you later create an Orderbook.

Local package.json exists, but node_modules missing

This issue can also raise when you change your system password but not the same updated on your .npmrc file that exist on path C:\Users\user_name, so update your password there too.

please check on it and run npm install first and then npm start.

Modifying a file inside a jar

Check out TrueZip.

It does exactly what you want (to edit files inline inside a jar file), through a virtual file system API. It also supports nested archives (jar inside a jar) as well.

How to find all the tables in MySQL with specific column names in them?

Use this one line query, replace desired_column_name by your column name.

SELECT TABLE_NAME FROM information_schema.columns WHERE column_name = 'desired_column_name';

Difference between mkdir() and mkdirs() in java for java.io.File

mkdirs() also creates parent directories in the path this File represents.

javadocs for mkdirs():

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

javadocs for mkdir():

Creates the directory named by this abstract pathname.

Example:

File  f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());

will yield false for the first [and no dir will be created], and true for the second, and you will have created non_existing_dir/someDir

Creating a pandas DataFrame from columns of other DataFrames with similar indexes

Well, I'm not sure that merge would be the way to go. Personally I would build a new data frame by creating an index of the dates and then constructing the columns using list comprehensions. Possibly not the most pythonic way, but it seems to work for me!

import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.random.randn(5,3), index=pd.date_range('01/02/2014',periods=5,freq='D'), columns=['a','b','c'] )
df2 = pd.DataFrame(np.random.randn(8,3), index=pd.date_range('01/01/2014',periods=8,freq='D'), columns=['a','b','c'] )

# Create an index list from the set of dates in both data frames
Index = list(set(list(df1.index) + list(df2.index)))
Index.sort()

df3 = pd.DataFrame({'df1': [df1.loc[Date, 'c'] if Date in df1.index else np.nan for Date in Index],\
                'df2': [df2.loc[Date, 'c'] if Date in df2.index else np.nan for Date in Index],},\
                index = Index)

df3

HTTP Content-Type Header and JSON

Content-Type: application/json is just the content header. The content header is just information about the type of returned data, ex::JSON,image(png,jpg,etc..),html.

Keep in mind, that JSON in JavaScript is an array or object. If you want to see all the data, use console.log instead of alert:

alert(response.text); // Will alert "[object Object]" string
console.log(response.text); // Will log all data objects

If you want to alert the original JSON content as a string, then add single quotation marks ('):

echo "'" . json_encode(array('text' => 'omrele')) . "'";
// alert(response.text) will alert {"text":"omrele"}

Do not use double quotes. It will confuse JavaScript, because JSON uses double quotes on each value and key:

echo '<script>var returndata=';
echo '"' . json_encode(array('text' => 'omrele')) . '"';
echo ';</script>';

// It will return the wrong JavaScript code:
<script>var returndata="{"text":"omrele"}";</script>

How to reset the bootstrap modal when it gets closed and open it fresh again?

also, you can clone your modal before open ;)

$('#myModal')
    .clone()
    .modal()
    .on('hidden.bs.modal', function(e) {
        $(this).remove();
    });

When is a language considered a scripting language?

Scripting languages are programming languages where the programs are typically delivered to end users in a readable textual form and where there is a program that can apparently execute that program directly. (The program may well compile the script internally; that's not relevant here because it is not visible to the user.)

It's relatively common for scripting languages to be able to support an interactive session where users can just type in their program and have it execute immediately. This is because this is a trivial extension of the essential requirement from the first paragraph; the main extra requirement is the addition of a mechanism to figure out when a typed-in statement is complete so that it can be sent to the execution engine.

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

In case you do need to define dataSource(), for example when you have multiple data sources, you can use:

@Autowired Environment env;

@Primary
@Bean
public DataSource customDataSource() {

    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("custom.datasource.driver-class-name"));
    dataSource.setUrl(env.getProperty("custom.datasource.url"));
    dataSource.setUsername(env.getProperty("custom.datasource.username"));
    dataSource.setPassword(env.getProperty("custom.datasource.password"));

    return dataSource;

}

By setting up the dataSource yourself (instead of using DataSourceBuilder), it fixed my problem which you also had.

The always knowledgeable Baeldung has a tutorial which explains in depth.

Python 2,3 Convert Integer to "bytes" Cleanly

In Python 3.x, you can convert an integer value (including large ones, which the other answers don't allow for) into a series of bytes like this:

import math

x = 0x1234
number_of_bytes = int(math.ceil(x.bit_length() / 8))

x_bytes = x.to_bytes(number_of_bytes, byteorder='big')

x_int = int.from_bytes(x_bytes, byteorder='big')
x == x_int

Can I use an HTML input type "date" to collect only a year?

There is input type month in HTML5 which allows to select month and year. Month selector works with autocomplete.

Check the example in JSFiddle.

<!DOCTYPE html>
<html>
<body>
    <header>
        <h1>Select a month below</h1>
    </header>
    Month example
    <input type="month" />
</body>
</html>

Set a button background image iPhone programmatically

In one line we can set image with this code

[buttonName setBackgroundImage:[UIImage imageNamed:@"imageName"] forState:UIControlStateNormal];

How do I match any character across multiple lines in a regular expression?

Use RegexOptions.Singleline, it changes the meaning of . to include newlines

Regex.Replace(content, searchText, replaceText, RegexOptions.Singleline);

How can I get the count of line in a file in an efficient way?

Quick and dirty, but it does the job:

import java.io.*;

public class Counter {

    public final static void main(String[] args) throws IOException {
        if (args.length > 0) {
            File file = new File(args[0]);
            System.out.println(countLines(file));
        }
    }

    public final static int countLines(File file) throws IOException {
        ProcessBuilder builder = new ProcessBuilder("wc", "-l", file.getAbsolutePath());
        Process process = builder.start();
        InputStream in = process.getInputStream();
        LineNumberReader reader = new LineNumberReader(new InputStreamReader(in));
        String line = reader.readLine();
        if (line != null) {
            return Integer.parseInt(line.trim().split(" ")[0]);
        } else {
            return -1;
        }
    }

}

Format LocalDateTime with Timezone in Java8

LocalDateTime is a date-time without a time-zone. You specified the time zone offset format symbol in the format, however, LocalDateTime doesn't have such information. That's why the error occured.

If you want time-zone information, you should use ZonedDateTime.

DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
ZonedDateTime.now().format(FORMATTER);
=> "20140829 14:12:22.122000 +09"

How to check the value given is a positive or negative integer?

For checking positive integer:

var isPositiveInteger = function(n) {
        return ($.isNumeric(n)) && (Math.floor(n) == n) && (n > 0); 
}

Convert a bitmap into a byte array

I believe you may simply do:

ImageConverter converter = new ImageConverter();
var bytes = (byte[])converter.ConvertTo(img, typeof(byte[]));

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

At grub screen goto boot in recovery.

As booting hold ESC

It should take you into a gui menu. Open command and fix selinux.

Also I suggest run the clean broken packages

Check if boolean is true?

i personally would prefer

if(true == foo)
{
}

there is no chance for the ==/= mistype and i find it more expressive in terms of foo's type. But it is a very subjective question.

Add a tooltip to a div

I have developed three type fade effects :

_x000D_
_x000D_
/* setup tooltips */_x000D_
    .tooltip {_x000D_
      position: relative;_x000D_
    }_x000D_
    .tooltip:before,_x000D_
    .tooltip:after {_x000D_
      display: block;_x000D_
      opacity: 0;_x000D_
      pointer-events: none;_x000D_
      position: absolute;_x000D_
    }_x000D_
    .tooltip:after {_x000D_
     border-right: 6px solid transparent;_x000D_
     border-bottom: 6px solid rgba(0,0,0,.75); _x000D_
      border-left: 6px solid transparent;_x000D_
      content: '';_x000D_
      height: 0;_x000D_
        top: 20px;_x000D_
        left: 20px;_x000D_
      width: 0;_x000D_
    }_x000D_
    .tooltip:before {_x000D_
      background: rgba(0,0,0,.75);_x000D_
      border-radius: 2px;_x000D_
      color: #fff;_x000D_
      content: attr(data-title);_x000D_
      font-size: 14px;_x000D_
      padding: 6px 10px;_x000D_
        top: 26px;_x000D_
      white-space: nowrap;_x000D_
    }_x000D_
_x000D_
    /* the animations */_x000D_
    /* fade */_x000D_
    .tooltip.fade:after,_x000D_
    .tooltip.fade:before {_x000D_
      transform: translate3d(0,-10px,0);_x000D_
      transition: all .15s ease-in-out;_x000D_
    }_x000D_
    .tooltip.fade:hover:after,_x000D_
    .tooltip.fade:hover:before {_x000D_
      opacity: 1;_x000D_
      transform: translate3d(0,0,0);_x000D_
    }_x000D_
_x000D_
    /* expand */_x000D_
    .tooltip.expand:before {_x000D_
      transform: scale3d(.2,.2,1);_x000D_
      transition: all .2s ease-in-out;_x000D_
    }_x000D_
    .tooltip.expand:after {_x000D_
      transform: translate3d(0,6px,0);_x000D_
      transition: all .1s ease-in-out;_x000D_
    }_x000D_
    .tooltip.expand:hover:before,_x000D_
    .tooltip.expand:hover:after {_x000D_
      opacity: 1;_x000D_
      transform: scale3d(1,1,1);_x000D_
    }_x000D_
    .tooltip.expand:hover:after {_x000D_
      transition: all .2s .1s ease-in-out;_x000D_
    }_x000D_
_x000D_
    /* swing */_x000D_
    .tooltip.swing:before,_x000D_
    .tooltip.swing:after {_x000D_
      transform: translate3d(0,30px,0) rotate3d(0,0,1,60deg);_x000D_
      transform-origin: 0 0;_x000D_
      transition: transform .15s ease-in-out, opacity .2s;_x000D_
    }_x000D_
    .tooltip.swing:after {_x000D_
      transform: translate3d(0,60px,0);_x000D_
      transition: transform .15s ease-in-out, opacity .2s;_x000D_
    }_x000D_
    .tooltip.swing:hover:before,_x000D_
    .tooltip.swing:hover:after {_x000D_
      opacity: 1;_x000D_
      transform: translate3d(0,0,0) rotate3d(1,1,1,0deg);_x000D_
    }_x000D_
_x000D_
    /* basic styling: has nothing to do with tooltips: */_x000D_
    h1 {_x000D_
      padding-left: 50px;_x000D_
    }_x000D_
    ul {_x000D_
      margin-bottom: 40px;_x000D_
    }_x000D_
    li {_x000D_
      cursor: pointer; _x000D_
      display: inline-block; _x000D_
      padding: 0 10px;_x000D_
    }
_x000D_
 <h1>FADE</h1>_x000D_
_x000D_
      <div class="tooltip fade" data-title="Hypertext Markup Language">_x000D_
      <label>Name</label>_x000D_
      <input type="text"/>_x000D_
      </div>_x000D_
      _x000D_
_x000D_
    <h1>EXPAND</h1>_x000D_
_x000D_
      <div class="tooltip expand" data-title="Hypertext Markup Language">_x000D_
      <label>Name</label>_x000D_
      <input type="text"/>_x000D_
      </div>_x000D_
      _x000D_
_x000D_
    <h1>SWING</h1>_x000D_
_x000D_
      <div class="tooltip swing" data-title="Hypertext Markup Language"> _x000D_
      <label>Name</label>_x000D_
      <input type="text"/>_x000D_
      </div>_x000D_
     
_x000D_
_x000D_
_x000D_

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

Refer to here

write query with named parameter, use simple ListPreparedStatementSetter with all parameters in sequence. Just add below snippet to convert the query in traditional form based to available parameters,

ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);

List<Integer> parameters = new ArrayList<Integer>();
for (A a : paramBeans)
    parameters.add(a.getId());

MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("placeholder1", parameters);
// create SQL with ?'s
String sql = NamedParameterUtils.substituteNamedParameters(parsedSql, parameterSource);     
return sql;

Declare multiple module.exports in Node.js

You can use this approach too

module.exports.func1 = ...
module.exports.func2 = ...

or

exports.func1 = ...
exports.func2 = ...

Hash string in c#

using System.Security.Cryptography;

public static byte[] GetHash(string inputString)
{
    using (HashAlgorithm algorithm = SHA256.Create())
        return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
}

public static string GetHashString(string inputString)
{
    StringBuilder sb = new StringBuilder();
    foreach (byte b in GetHash(inputString))
        sb.Append(b.ToString("X2"));

    return sb.ToString();
}

Additional Notes

  • Since MD5 and SHA1 are obsolete and insecure algorithms, this solution uses SHA256. Alternatively, you can use BCrypt or Scrypt as pointed out in comments.
  • Also, consider "salting" your hashes and use proven cryptographic algorithms, as pointed out in comments.

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

Long story short, it probably doesn't matter. Use whichever you think looks nicest.

Longer answer, using Oracle's Java 7 JDK specifically, since this isn't defined at the JLS:

String.valueOf or Character.toString work the same way, so use whichever you feel looks nicer. In fact, Character.toString simply calls String.valueOf (source).

So the question is, should you use one of those or String.substring. Here again it doesn't matter much. String.substring uses the original string's char[] and so allocates one object fewer than String.valueOf. This also prevents the original string from being GC'ed until the one-character string is available for GC (which can be a memory leak), but in your example, they'll both be available for GC after each iteration, so that doesn't matter. The allocation you save also doesn't matter -- a char[1] is cheap to allocate, and short-lived objects (as the one-char string will be) are cheap to GC, too.

If you have a large enough data set that the three are even measurable, substring will probably give a slight edge. Like, really slight. But that "if... measurable" contains the real key to this answer: why don't you just try all three and measure which one is fastest?

angularjs - ng-repeat: access key and value from JSON array object

You've got an array of objects, so you'll need to use ng-repeat twice, like:

<ul ng-repeat="item in items">
  <li ng-repeat="(key, val) in item">
    {{key}}: {{val}}
  </li>
</ul>

Example: http://jsfiddle.net/Vwsej/

Edit:

Note that properties order in objects are not guaranteed.

<table>
    <tr>
        <th ng-repeat="(key, val) in items[0]">{{key}}</th>
    </tr>
    <tr ng-repeat="item in items">
        <td ng-repeat="(key, val) in item">{{val}}</td>
    </tr>
</table>

Example: http://jsfiddle.net/Vwsej/2/

Checking if a string can be converted to float in Python

We can use regex as: import re if re.match('[0-9]*.?[0-9]+', <your_string>): print("Its a float/int") else: print("Its something alien") let me explain the regex in english,

  • * -> 0 or more occurence
  • + -> 1 or more occurence
  • ? -> 0/1 occurence

now, lets convert

  • '[0-9]* -> let there be 0 or more occurence of digits in between 0-9
  • \.? -> followed by a 0 or one '.'(if you need to check if it can be int/float else we can also use instead of ?, use {1})
  • [0-9]+ -> followed by 0 or more occurence of digits in between 0-9

Insert new column into table in sqlite?

SQLite has limited ALTER TABLE support that you can use to add a column to the end of a table or to change the name of a table.

If you want to make more complex changes in the structure of a table, you will have to recreate the table. You can save existing data to a temporary table, drop the old table, create the new table, then copy the data back in from the temporary table.

For example, suppose you have a table named "t1" with columns names "a" and "c" and that you want to insert column "b" from this table. The following steps illustrate how this could be done:

BEGIN TRANSACTION;
CREATE TEMPORARY TABLE t1_backup(a,c);
INSERT INTO t1_backup SELECT a,c FROM t1;
DROP TABLE t1;
CREATE TABLE t1(a,b, c);
INSERT INTO t1 SELECT a,c FROM t1_backup;
DROP TABLE t1_backup;
COMMIT;

Now you are ready to insert your new data like so:

UPDATE t1 SET b='blah' WHERE a='key'

How to Set Focus on JTextField?

if is there only one Top-Level Container then last lines in GUI constructor would be for example

.
.
.
myFrame.setVisible(true);
EventQueue.invokeLater(new Runnable() {

   @Override
     public void run() {
         myComponent.grabFocus();
         myComponent.requestFocus();//or inWindow
     }
});

Simplest way to profile a PHP script

If subtracting microtimes gives you negative results, try using the function with the argument true (microtime(true)). With true, the function returns a float instead of a string (as it does if it is called without arguments).

Clear text from textarea with selenium

driver.find_element_by_xpath("path").send_keys(Keys.CONTROL + u'\ue003') worked great with FireFox

  • u'\ue003' is a BACK_SPACE for those like me - never remembering it)

How to initialize a vector of vectors on a struct?

Like this:

#include <vector>

// ...

std::vector<std::vector<int>> A(dimension, std::vector<int>(dimension));

(Pre-C++11 you need to leave whitespace between the angled brackets.)

UIView background color in Swift

self.view.backgroundColor = UIColor.redColor()

In Swift 3:

self.view.backgroundColor = UIColor.red

Array of an unknown length in C#

Use List<> to build up an 'array' of unknown length.

Use List<>.ToArray() to return a real array, and not a List.

var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
var array = list.ToArray();

Phone Number Validation MVC

Or you can use JQuery - just add your input field to the class "phone" and put this in your script section:

$(".phone").keyup(function () {
        $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));

There is no error message but you can see that the phone number is not correctly formatted until you have entered all ten digits.

Generics/templates in python?

After coming up with some good thoughts on making generic types in python, I started looking for others who had the same idea, but I couldn't find any. So, here it is. I tried this out and it works well. It allows us to parameterize our types in python.

class List( type ):

    def __new__(type_ref, member_type):

        class List(list):

            def append(self, member):
                if not isinstance(member, member_type):
                    raise TypeError('Attempted to append a "{0}" to a "{1}" which only takes a "{2}"'.format(
                        type(member).__name__,
                        type(self).__name__,
                        member_type.__name__ 
                    ))

                    list.append(self, member)

        return List 

You can now derive types from this generic type.

class TestMember:
        pass

class TestList(List(TestMember)):

    def __init__(self):
        super().__init__()


test_list = TestList()
test_list.append(TestMember())
test_list.append('test') # This line will raise an exception

This solution is simplistic, and it does have it's limitations. Each time you create a generic type, it will create a new type. Thus, multiple classes inheriting List( str ) as a parent would be inheriting from two separate classes. To overcome this, you need to create a dict to store the various forms of the inner class and return the previous created inner class, rather than creating a new one. This would prevent duplicate types with the same parameters from being created. If interested, a more elegant solution can be made with decorators and/or metaclasses.

Javascript objects: get parent

There is a more 'smooth' solution for this :)

var Foo = function(){
  this.par = 3;

  this.sub = new(function(t){ //using virtual function to create sub object and pass parent object via 't'
    this.p = t;
    this.subFunction = function(){
      alert(this.p.par);
    }
  })(this);
}

var myObj = new Foo();
myObj.sub.subFunction() // will popup 3;

myObj.par = 5;
myObj.sub.subFunction() // will popup 5;

How to efficiently calculate a running standard deviation?

You could look at the Wikipedia article on Standard Deviation, in particular the section about Rapid calculation methods.

There's also an article I found that uses Python, you should be able to use the code in it without much change: Subliminal Messages - Running Standard Deviations.

Delete all the queues from RabbitMQ?

Here is a way to do it with PowerShell. the URL may need to be updated

$cred = Get-Credential
 iwr -ContentType 'application/json' -Method Get -Credential $cred   'http://localhost:15672/api/queues' | % { 
    ConvertFrom-Json  $_.Content } | % { $_ } | ? { $_.messages -gt 0} | % {
    iwr  -method DELETE -Credential $cred  -uri  $("http://localhost:15672/api/queues/{0}/{1}" -f  [System.Web.HttpUtility]::UrlEncode($_.vhost),  $_.name)
 }

How can I change property names when serializing with Json.net?

There is still another way to do it, which is using a particular NamingStrategy, which can be applied to a class or a property by decorating them with [JSonObject] or [JsonProperty].

There are predefined naming strategies like CamelCaseNamingStrategy, but you can implement your own ones.

The implementation of different naming strategies can be found here: https://github.com/JamesNK/Newtonsoft.Json/tree/master/Src/Newtonsoft.Json/Serialization

What is the difference between JAX-RS and JAX-WS?

Can JAX-RS do Asynchronous Request like JAX-WS?

1) I don't know if the JAX-RS API includes a specific mechanism for asynchronous requests, but this answer could still change based on the client implementation you use.

Can JAX-RS access a web service that is not running on the Java platform, and vice versa?

2) I can't think of any reason it wouldn't be able to.

What does it mean by "REST is particularly useful for limited-profile devices, such as PDAs and mobile phones"?

3) REST based architectures typically will use a lightweight data format, like JSON, to send data back and forth. This is in contrast to JAX-WS which uses XML. I don't see XML by itself so significantly heavier than JSON (which some people may argue), but with JAX-WS it's how much XML is used that ends up making REST with JSON the lighter option.

What does it mean by "JAX-RS do not require XML messages or WSDL service–API definitions?

4) As stated in 3, REST architectures often use JSON to send and receive data. JAX-WS uses XML. It's not that JSON is so significantly smaller than XML by itself. It's mostly that JAX-WS specification includes lots overhead in how it communicates.

On the point about WSDL and API definitions, REST will more frequently use the URI structure and HTTP commands to define the API rather than message types, as is done in the JAX-WS. This means that you don't need to publish a WSDL document so that other users of your service can know how to talk to your service. With REST you will still need to provide some documentation to other users about how the REST service is organized and what data and HTTP commands need to be sent.

Is it possible to use if...else... statement in React render function?

Try going with Switch case or ternary operator

render(){
    return (
        <div>
            <Element1/>
            <Element2/>
            // updated code works here
            {(() => {
                        switch (this.props.hasImage) {
                            case (this.props.hasImage):
                                return <MyImage />;
                            default:
                                return (
                                   <OtherElement/>; 
                                );
                        }
                    })()}
        </div>
    )
}

This worked for me and should work for you else. Try Ternary Operator

How can I set a UITableView to grouped style

swift 4

if you don't want use storyboard, this might be help.

you can add table view and set properties in a closure:

lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)

        tableView.backgroundColor = UIColor(named: Palette.secondaryLight.rawValue)
        tableView.rowHeight = 68
        tableView.separatorStyle = .none
        tableView.translatesAutoresizingMaskIntoConstraints = false
        return tableView
    }()

then add in subview and set constraints.

Fatal error: Class 'ZipArchive' not found in

For CentOS based server use

yum install php-pecl-zip.x86_64

Enable it by running: echo "extension=zip.so" >> /etc/php.d/zip.ini

How can you make a custom keyboard in Android?

Well Suragch gave the best answer so far but he skipped certain minor stuff that was important to getting the app compiled.

I hope to make a better answer than Suragch by improving on his answer. I will add all the missing elements he didnt put.

I compiled my apk using the android app , APK Builder 1.1.0. So let's begin.

To build an Android app we need couple files and folders that are organized in a certain format and capitalized accordingly.

res layout -> xml files depicting how app will look on phone. Similar to how html shapes how web page looks on browser. Allowing your app to fit on screens accordingly.

values -> constant data such as colors.xml, strings.xml, styles.xml. These files must be properly spelt.

drawable -> pics{jpeg, png,...}; Name them anything.

mipmap -> more pics. used for app icon?

xml -> more xml files.

src -> acts like JavaScript in html. layout files will initiate the starting view and your java file will dynamically control the tag elements and trigger events. Events can also be activated directly in the layout.xml just like in html.

AndroidManifest.xml -> This file registers what your app is about. Application name, Type of program, permissions needed, etc. This seems to make Android rather safe. Programs literally cannot do what they didnt ask for in the Manifest.

Now there are 4 types of Android programs, an activity, a service, a content provider, and a broadcast reciever. Our keyboard will be a service, which allows it to run in the background. It will not appear in the list of apps to launch; but it can be uninstalled.

To compile your app, involves gradle, and apk signing. You can research that one or use APK Builder for android. It is super easy.

Now that we understand Android development, let us create the files and folders.

  1. Create the files and folders as I discussed above. My directory wil look as follows:

    • NumPad
      • AndroidManifest.xml
      • src
        • Saragch
          • num_pad
            • MyInputMethodService.java
      • res
        • drawable
          • Suragch_NumPad_icon.png
        • layout
          • key_preview.xml
          • keyboard_view.xml
        • xml
          • method.xml
          • number_pad.xml
        • values
          • colors.xml
          • strings.xml
          • styles.xml

Remember if you are using an ide such as Android Studio it may have a project file.

  1. Write files.

A: NumPad/res/layout/key_preview.xml

<?xml version="1.0" encoding="utf-8"?>
   <TextView
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:gravity="center"
      android:background="@android:color/white"
      android:textColor="@android:color/black"
      android:textSize="30sp">
</TextView>

B: NumPad/res/layout/keyboard_view.xml

<?xml version="1.0" encoding="utf-8"?>
<android.inputmethodservice.KeyboardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:keyPreviewLayout="@layout/key_preview"
    android:layout_alignParentBottom="true">

</android.inputmethodservice.KeyboardView>

C: NumPad/res/xml/method.xml

<?xml version="1.0" encoding="utf-8"?>
<input-method  xmlns:android="http://schemas.android.com/apk/res/android">
    <subtype  android:imeSubtypeMode="keyboard"/>
</input-method>

D: Numpad/res/xml/number_pad.xml

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="20%p"
    android:horizontalGap="5dp"
    android:verticalGap="5dp"
    android:keyHeight="60dp">

    <Row>
        <Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left"/>
        <Key android:codes="50" android:keyLabel="2"/>
        <Key android:codes="51" android:keyLabel="3"/>
        <Key android:codes="52" android:keyLabel="4"/>
        <Key android:codes="53" android:keyLabel="5" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="54" android:keyLabel="6" android:keyEdgeFlags="left"/>
        <Key android:codes="55" android:keyLabel="7"/>
        <Key android:codes="56" android:keyLabel="8"/>
        <Key android:codes="57" android:keyLabel="9"/>
        <Key android:codes="48" android:keyLabel="0" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="-5"
             android:keyLabel="DELETE"
             android:keyWidth="40%p"
             android:keyEdgeFlags="left"
             android:isRepeatable="true"/>
        <Key android:codes="10"
             android:keyLabel="ENTER"
             android:keyWidth="60%p"
             android:keyEdgeFlags="right"/>
    </Row>

</Keyboard>

Of course this can be easily edited to your liking. You can even use images instead lf words for the label.

Suragch didnt demonstrate the files in the values folder and assumed we had access to Android Studio; which automatically creates them. Good thing I have APK Builder.

E: NumPad/res/values/colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>

F: NumPad/res/values/strings.xml

<resources>
    <string name="app_name">Suragch NumPad</string>
</resources>

G: NumPad/res/values/styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="android:Theme.Material.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

</resources>

H: Numpad/AndroidManifest.xml

This is the file that was really up for contension. Here I felt I would never compile my program. sob. sob. If you check Suracgh's answer you see he leaves the first set of fields empty, and adds the activity tag in this file. As I said there are four types of Android programs. An activity is a regular app with a launcher icon. This numpad is not an activity! Further he didnt implement any activity.

My friends do not include the activity tag. Your program will compile, and when you try to launch it will crash! As for xmlns:android and uses-sdk; I cant help you there. Just try my settings if they work.

As you can see there is a service tag, which register it as a service. Also service.android:name must be name of public class extending service in our java file. It MUST be capitalized accordingly. Also package is the name of the package we declared in java file.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="Saragch.num_pad">

    <uses-sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="27" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/Suragch_NumPad_icon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <service
            android:name=".MyInputMethodService"
            android:label="Keyboard Display Name"
            android:permission="android.permission.BIND_INPUT_METHOD">

            <intent-filter>
                <action android:name="android.view.InputMethod"/>
            </intent-filter>

            <meta-data
                android:name="android.view.im"
                android:resource="@xml/method"/>

        </service>

    </application>
</manifest>

I: NumPad/src/Saragch/num_pad/MyInputMethodService.java

Note: I think java is an alternative to src.

This was another problem file but not as contentious as the manifest file. As I know Java good enough to know what is what, what is not. I barely know xml and how it ties in with Android development!

The problem here was he didnt import anything! I mean, he gave us a "complete" file which uses names that couldnt be resolved! InputMethodService, Keyboard, etc. That is bad practice Mr. Suragch. Thanks for helping me out but how did you expect the code to compile if the names cant be resolved?

Following is the correctly edited version. I just happened to pounce upon couple hints to drove me to the right place to learn what exactly to import.

package Saragch.num_pad;

import android.inputmethodservice.InputMethodService;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.Keyboard;

import android.text.TextUtils;
import android.view.inputmethod.InputConnection;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


public class MyInputMethodService extends InputMethodService implements KeyboardView.OnKeyboardActionListener 
{
    @Override
    public View onCreateInputView() 
    {
     // get the KeyboardView and add our Keyboard layout to it
     KeyboardView keyboardView = (KeyboardView)getLayoutInflater().inflate(R.layout.keyboard_view, null);
     Keyboard keyboard = new Keyboard(this, R.xml.number_pad);
     keyboardView.setKeyboard(keyboard);
     keyboardView.setOnKeyboardActionListener(this);
     return keyboardView;
    }

    @Override
    public void onKey(int primaryCode, int[] keyCodes) 
    {

        InputConnection ic = getCurrentInputConnection();

        if (ic == null) return;

        switch (primaryCode)
        {
         case Keyboard.KEYCODE_DELETE:
            CharSequence selectedText = ic.getSelectedText(0);

            if (TextUtils.isEmpty(selectedText)) 
            {
             // no selection, so delete previous character
             ic.deleteSurroundingText(1, 0);
            }

            else 
            {
             // delete the selection
             ic.commitText("", 1);
            }

            ic.deleteSurroundingText(1, 0);
            break;

         default:
            char code = (char) primaryCode;
            ic.commitText(String.valueOf(code), 1);
        }
    }

    @Override
    public void onPress(int primaryCode) { }

    @Override
    public void onRelease(int primaryCode) { }

    @Override
    public void onText(CharSequence text) { }

    @Override
    public void swipeLeft() { }

    @Override
    public void swipeRight() { }

    @Override
    public void swipeDown() { }

    @Override
    public void swipeUp() { }
}
  1. Compile and sign your project.

    This is where I am clueless as a newby Android developer. I would like to learn it manually, as I believe real programmers can compile manually.

I think gradle is one of the tools for compiling and packaging to apk. apk seems to be like a jar file or a rar for zip file. There are then two types of signing. debug key which is not alllowed on play store and private key.

Well lets give Mr. Saragch a hand. And thank you for watching my video. Like, subscribe.

How do I print a datetime in the local timezone?

I use this function datetime_to_local_timezone(), which seems overly convoluted but I found no simpler version of a function that converts a datetime instance to the local time zone, as configured in the operating system, with the UTC offset that was in effect at that time:

import time, datetime

def datetime_to_local_timezone(dt):
    epoch = dt.timestamp() # Get POSIX timestamp of the specified datetime.
    st_time = time.localtime(epoch) #  Get struct_time for the timestamp. This will be created using the system's locale and it's time zone information.
    tz = datetime.timezone(datetime.timedelta(seconds = st_time.tm_gmtoff)) # Create a timezone object with the computed offset in the struct_time.

    return dt.astimezone(tz) # Move the datetime instance to the new time zone.

utc = datetime.timezone(datetime.timedelta())
dt1 = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, utc) # DST was in effect
dt2 = datetime.datetime(2009, 1, 10, 18, 44, 59, 193982, utc) # DST was not in effect

print(dt1)
print(datetime_to_local_timezone(dt1))

print(dt2)
print(datetime_to_local_timezone(dt2))

This example prints four dates. For two moments in time, one in January and one in July 2009, each, it prints the timestamp once in UTC and once in the local time zone. Here, where CET (UTC+01:00) is used in the winter and CEST (UTC+02:00) is used in the summer, it prints the following:

2009-07-10 18:44:59.193982+00:00
2009-07-10 20:44:59.193982+02:00

2009-01-10 18:44:59.193982+00:00
2009-01-10 19:44:59.193982+01:00

Are 2 dimensional Lists possible in c#?

another work around which i have used was...

List<int []> itemIDs = new List<int[]>();

itemIDs.Add( new int[2] { 101, 202 } );

The library i'm working on has a very formal class structure and i didn't wan't extra stuff in there effectively for the privilege of recording two 'related' ints.

Relies on the programmer entering only a 2 item array but as it's not a common item i think it works.

Python Remove last 3 characters of a string

I try to avoid regular expressions, but this appears to work:

string = re.sub("\s","",(string.lower()))[:-3]

How to: Install Plugin in Android Studio

File-> Settings->Under IDE Settings click on Plugins. Now in right side window Click on Browse repositories and there you can find the plugins. Select which one you want and click on install

Rails 4: how to use $(document).ready() with turbo-links

Here's what I do... CoffeeScript:

ready = ->

  ...your coffeescript goes here...

$(document).ready(ready)
$(document).on('page:load', ready)

last line listens for page load which is what turbo links will trigger.

Edit...adding Javascript version (per request):

var ready;
ready = function() {

  ...your javascript goes here...

};

$(document).ready(ready);
$(document).on('page:load', ready);

Edit 2...For Rails 5 (Turbolinks 5) page:load becomes turbolinks:load and will be even fired on initial load. So we can just do the following:

$(document).on('turbolinks:load', function() {

  ...your javascript goes here...

});

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

IIS7: A process serving application pool 'YYYYY' suffered a fatal communication error with the Windows Process Activation Service

Make sure that each Application Pool in IIS, under Advanced Settings has Enable 32 bit Applications set to True

IIS screenshot

How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

In Visual Studio 2015 Update3 I have this feature.

Just by highlighting properties and then press Ctrl + . and then press Generate Constructor.

For example, if you've highlighted two properties it will suggest you to create a constructor with two parameters and if you've selected three it will suggest one with three parameters and so on.

It also works with Visual Studio 2017 and 2019.

Auto generate shortcut visualisation

HttpWebRequest-The remote server returned an error: (400) Bad Request

Are you sure you should be using POST not PUT?

POST is usually used with application/x-www-urlencoded formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data. Not always, but usually, that is the right thing to do..

Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.

CSS Input field text color of inputted text

If you want the placeholder text to be red you need to target it specifically in CSS.

Write:

input::placeholder{
  color: #f00;
}

I can't understand why this JAXB IllegalAnnotationException is thrown

I can't understand why this JAXB IllegalAnnotationException is thrown

I also was getting the ### counts of IllegalAnnotationExceptions exception and it seemed to be due to an improper dependency hierarchy in my Spring wiring.

I figured it out by putting a breakpoint in the JAXB code when it does the throw. For me this was at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(). Then I dumped the list variable which gives something like:

[org.mortbay.jetty.Handler is an interface, and JAXB can't handle interfaces.
this problem is related to the following location:
    at org.mortbay.jetty.Handler
    at public org.mortbay.jetty.Handler[] org.mortbay.jetty.handler.HandlerCollection.getHandlers()
    at org.mortbay.jetty.handler.HandlerCollection
    at org.mortbay.jetty.handler.ContextHandlerCollection
    at com.mprew.ec2.commons.server.LocalContextHandlerCollection
    at private com.mprew.ec2.commons.server.LocalContextHandlerCollection com.mprew.ec2.commons.services.jaxws_asm.SetLocalContextHandlerCollection.arg0
    at com.mprew.ec2.commons.services.jaxws_asm.SetLocalContextHandlerCollection,
org.mortbay.jetty.Handler does not have a no-arg default constructor.]
....

The does not have a no-arg default constructor seemed to me to be misleading. Maybe I wasn't understanding what the exception was saying. But it did indicate that there was a problem with my LocalContextHandlerCollection. I removed a dependency loop and the error cleared.

Hopefully this will be helpful to others.

Scatter plot and Color mapping in Python

Subplot Colorbar

For subplots with scatter, you can trick a colorbar onto your axes by building the "mappable" with the help of a secondary figure and then adding it to your original plot.

As a continuation of the above example:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')


# Build your secondary mirror axes:
fig2, (ax3, ax4) = plt.subplots(1, 2)

# Build maps that parallel the color-coded data
# NOTE 1: imshow requires a 2-D array as input
# NOTE 2: You must use the same cmap tag as above for it match
map1 = ax3.imshow(np.stack([t, t]),cmap='viridis')
map2 = ax4.imshow(np.stack([t, t]),cmap='viridis_r')

# Add your maps onto your original figure/axes
fig.colorbar(map1, ax=ax1)
fig.colorbar(map2, ax=ax2)
plt.show()

Scatter subplots with COLORBAR

Note that you will also output a secondary figure that you can ignore.

using href links inside <option> tag

Try this Code

<select name="forma" onchange="location = this.options[this.selectedIndex].value;">
 <option value="Home.php">Home</option>
 <option value="Contact.php">Contact</option>
 <option value="Sitemap.php">Sitemap</option>
</select>

symfony 2 No route found for "GET /"

Using symfony 2.3 with php 5.5 and using the built in server with

app/console server:run

which should output something like:

Server running on http://127.0.0.1:8000
Quit the server with CONTROL-C.

then go to http://127.0.0.1:8000/app_dev.php/app/example

this should give you the default, which you can also find the default route by viewing src/AppBundle/Controller/DefaultController.php

How can I enable auto complete support in Notepad++?

It is very easy:

  1. Find the XML file with unity keywords
  2. Copy only lines with "< KeyWord name="......" / > "
  3. Go to C:\Program Files\Notepad++\plugins\APIs and find cs.xml for example
  4. Paste what you copied in 1., but be careful: Don't delete any line of it cs.xml
  5. Save the file and enjoy autocompleting :)

How to force Chrome's script debugger to reload javascript?

While you are developing your script, try disabling the Chrome cache.

When you reload the page, the JavaScript should now get refreshed.


Chrome circa 2011

Open settings Disable the cache


Chrome circa 2018

Open settings Disable the cache

You can also access it on the network tab:

Network tab

How to run Gulp tasks sequentially one after the other

I was searching for this answer for a while. Now I got it in the official gulp documentation.

If you want to perform a gulp task when the last one is complete, you have to return a stream:

_x000D_
_x000D_
gulp.task('wiredep', ['dev-jade'], function () {_x000D_
    var stream = gulp.src(paths.output + '*.html')_x000D_
        .pipe($.wiredep())_x000D_
        .pipe(gulp.dest(paths.output));_x000D_
_x000D_
    return stream; // execute next task when this is completed_x000D_
});_x000D_
_x000D_
// First will execute and complete wiredep task_x000D_
gulp.task('prod-jade', ['wiredep'], function() {_x000D_
    gulp.src(paths.output + '**/*.html')_x000D_
        .pipe($.minifyHtml())_x000D_
        .pipe(gulp.dest(paths.output));_x000D_
});
_x000D_
_x000D_
_x000D_

RE error: illegal byte sequence on Mac OS X

My workaround had been using gnu sed. Worked fine for my purposes.

T-SQL Substring - Last 3 Characters

You can use either way:

SELECT RIGHT(RTRIM(columnName), 3)

OR

SELECT SUBSTRING(columnName, LEN(columnName)-2, 3)

How to load all the images from one of my folder into my web page, using Jquery/Javascript

You can't do this automatically. Your JS can't see the files in the same directory as it.

Easiest is probably to give a list of those image names to your JavaScript.

Otherwise, you might be able to fetch a directory listing from the web server using JS and parse it to get the list of images.

Failed to import new Gradle project: failed to find Build Tools revision *.0.0

I had the API 17 installed but that was not enough. What I really need installed is the "Android SDK Build-Tools 17".

You can locate your "Android SDK Build-Tools X" inside the first child, named "Tools", in the "Android SDK Manager".

What techniques can be used to define a class in JavaScript, and what are their trade-offs?

The simple way is:

function Foo(a) {
  var that=this;

  function privateMethod() { .. }

  // public methods
  that.add = function(b) {
    return a + b;
  };
  that.avg = function(b) {
    return that.add(b) / 2; // calling another public method
  };
}

var x = new Foo(10);
alert(x.add(2)); // 12
alert(x.avg(20)); // 15

The reason for that is that this can be bound to something else if you give a method as an event handler, so you save the value during instantiation and use it later.

Edit: it's definitely not the best way, just a simple way. I'm waiting for good answers too!

How do I find all of the symlinks in a directory tree?

To see just the symlinks themselves, you can use

find -L /path/to/dir/ -xtype l 

while if you want to see also which files they target, just append an ls

find -L /path/to/dir/ -xtype l -exec ls -al {} \;

How to solve "Fatal error: Class 'MySQLi' not found"?

Sounds like you just need to install MySQLi.

If you think you've done that and still have a problem, please post your operating system and anything else that might help diagnose it further.

how to make label visible/invisible?

You can set display attribute as none to hide a label.

<label id="excel-data-div" style="display: none;"></label>

Angularjs checkbox checked by default on load and disables Select list when checked

Do it in the controller

_x000D_
_x000D_
$timeout(function(){
$scope.checked = true;
}, 1);
_x000D_
_x000D_
_x000D_

then remove ng-checked.

Show data on mouseover of circle

This concise example demonstrates common way how to create custom tooltip in d3.

_x000D_
_x000D_
var w = 500;_x000D_
var h = 150;_x000D_
_x000D_
var dataset = [5, 10, 15, 20, 25];_x000D_
_x000D_
// firstly we create div element that we can use as_x000D_
// tooltip container, it have absolute position and_x000D_
// visibility: hidden by default_x000D_
_x000D_
var tooltip = d3.select("body")_x000D_
  .append("div")_x000D_
  .attr('class', 'tooltip');_x000D_
_x000D_
var svg = d3.select("body")_x000D_
  .append("svg")_x000D_
  .attr("width", w)_x000D_
  .attr("height", h);_x000D_
_x000D_
// here we add some circles on the page_x000D_
_x000D_
var circles = svg.selectAll("circle")_x000D_
  .data(dataset)_x000D_
  .enter()_x000D_
  .append("circle");_x000D_
_x000D_
circles.attr("cx", function(d, i) {_x000D_
    return (i * 50) + 25;_x000D_
  })_x000D_
  .attr("cy", h / 2)_x000D_
  .attr("r", function(d) {_x000D_
    return d;_x000D_
  })_x000D_
  _x000D_
  // we define "mouseover" handler, here we change tooltip_x000D_
  // visibility to "visible" and add appropriate test_x000D_
  _x000D_
  .on("mouseover", function(d) {_x000D_
    return tooltip.style("visibility", "visible").text('radius = ' + d);_x000D_
  })_x000D_
  _x000D_
  // we move tooltip during of "mousemove"_x000D_
  _x000D_
  .on("mousemove", function() {_x000D_
    return tooltip.style("top", (event.pageY - 30) + "px")_x000D_
      .style("left", event.pageX + "px");_x000D_
  })_x000D_
  _x000D_
  // we hide our tooltip on "mouseout"_x000D_
  _x000D_
  .on("mouseout", function() {_x000D_
    return tooltip.style("visibility", "hidden");_x000D_
  });
_x000D_
.tooltip {_x000D_
    position: absolute;_x000D_
    z-index: 10;_x000D_
    visibility: hidden;_x000D_
    background-color: lightblue;_x000D_
    text-align: center;_x000D_
    padding: 4px;_x000D_
    border-radius: 4px;_x000D_
    font-weight: bold;_x000D_
    color: orange;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
_x000D_
_x000D_
_x000D_

How to embed a PDF viewer in a page?

You could consider using PDFObject by Philip Hutchison.

Alternatively, if you're looking for a non-Javascript solution, you could use markup like this:

<object data="myfile.pdf" type="application/pdf" width="100%" height="100%">
  <p>Alternative text - include a link <a href="myfile.pdf">to the PDF!</a></p>
</object>

How to set JAVA_HOME in Linux for all users

Probably a good idea to source whatever profile you edit to save having to use a fresh login.

either: source /etc/ or . /etc/

Where is whatever profile you edited.

How to set some xlim and ylim in Seaborn lmplot facetgrid

The lmplot function returns a FacetGrid instance. This object has a method called set, to which you can pass key=value pairs and they will be set on each Axes object in the grid.

Secondly, you can set only one side of an Axes limit in matplotlib by passing None for the value you want to remain as the default.

Putting these together, we have:

g = sns.lmplot('X', 'Y', df, col='Z', sharex=False, sharey=False)
g.set(ylim=(0, None))

enter image description here

Hibernate: flush() and commit()

flush(); Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory. It will update or insert into your tables in the running transaction, but it may not commit those changes.

You need to flush in batch processing otherwise it may give OutOfMemoryException.

Commit(); Commit will make the database commit. When you have a persisted object and you change a value on it, it becomes dirty and hibernate needs to flush these changes to your persistence layer. So, you should commit but it also ends the unit of work (transaction.commit()).

How to add an object to an array

Expanding Gabi Purcaru's answer to include an answer to number 2.

a = new Array();
b = new Object();
a[0] = b;

var c = a[0]; // c is now the object we inserted into a...

Creating a zero-filled pandas data frame

It's best to do this with numpy in my opinion

import numpy as np
import pandas as pd
d = pd.DataFrame(np.zeros((N_rows, N_cols)))

Correct way to initialize HashMap and can HashMap hold different value types?

It really depends on what kind of type safety you need. The non-generic way of doing it is best done as:

 Map x = new HashMap();

Note that x is typed as a Map. this makes it much easier to change implementations (to a TreeMap or a LinkedHashMap) in the future.

You can use generics to ensure a certain level of type safety:

Map<String, Object> x = new HashMap<String, Object>();

In Java 7 and later you can do

Map<String, Object> x = new HashMap<>();

The above, while more verbose, avoids compiler warnings. In this case the content of the HashMap can be any Object, so that can be Integer, int[], etc. which is what you are doing.

If you are still using Java 6, Guava Libraries (although it is easy enough to do yourself) has a method called newHashMap() which avoids the need to duplicate the generic typing information when you do a new. It infers the type from the variable declaration (this is a Java feature not available on constructors prior to Java 7).

By the way, when you add an int or other primitive, Java is autoboxing it. That means that the code is equivalent to:

 x.put("one", Integer.valueOf(1));

You can certainly put a HashMap as a value in another HashMap, but I think there are issues if you do it recursively (that is put the HashMap as a value in itself).

How to extract .war files in java? ZIP vs JAR

For mac users: in terminal command :

unzip yourWARfileName.war

Is it possible to open developer tools console in Chrome on Android phone?

When you don't have a PC on hand, you could use Eruda, which is devtools for mobile browsers https://github.com/liriliri/eruda
It is provided as embeddable javascript and also a bookmarklet (pasting bookmarklet in chrome removes the javascript: prefix, so you have to type it yourself)

Check if year is leap year in javascript

The function checks if February has 29 days. If it does, then we have a leap year.

ES5

function isLeap(year) {
  return new Date(year, 1, 29).getDate() === 29;
}

ES6

const isLeap = year => new Date(year, 1, 29).getDate() === 29;

Result

isLeap(1004) // true
isLeap(1001) // false

A child container failed during start java.util.concurrent.ExecutionException

Your webapp has servletcontainer specific libraries like servlet-api.jar file in its /WEB-INF/lib. This is not right.

Remove them all.

The /WEB-INF/lib should contain only the libraries specific to the webapp, not to the servletcontainer. The servletcontainer (like Tomcat) is the one who should already provide the servletcontainer specific libraries.

If you supply libraries from an arbitrary servletcontainer of a different make/version, you'll run into this kind of problems because your webapp wouldn't be able to run on a servletcontainer of a different make/version than where those libraries are originated from.

How to solve: In Eclipse Right click on the project in eclipse Properties -> Java Build Path -> Add library -> Server Runtime Library -> Apache Tomcat

Im Maven Project:-

add follwing line in pom.xml file

<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${default.javax.servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${default.javax.servlet.jsp.version}</version>
            <scope>provided</scope>
        </dependency>

jQuery how to find an element based on a data-attribute value?

$("ul").find("li[data-slide='" + current + "']");

I hope this may work better

thanks

A fast way to delete all rows of a datatable at once

If you are really concerned about speed and not worried about the data you can do a Truncate. But this is assuming your DataTable is on a database and not just a memory object.

TRUNCATE TABLE tablename

The difference is this removes all rows without logging the row deletes making the transaction faster.

What is a Maven artifact?

Q. What is Artifact in maven?
ANS: ARTIFACT is a JAR,(WAR or EAR), but it could be also something else. Each artifact has,

  • a group ID (like com.your.package),
  • an artifact ID (just a name), and
  • a version string.
    The three together uniquely identify the artifact.

Q.Why does Maven need them?
Ans: Maven is used to make them available for our applications.

How to trigger SIGUSR1 and SIGUSR2?

terminal 1

dd if=/dev/sda of=debian.img

terminal 2

killall -SIGUSR1 dd

go back to terminal 1

34292201+0 records in
34292200+0 records out
17557606400 bytes (18 GB) copied, 1034.7 s, 17.0 MB/s

Omitting the second expression when using the if-else shorthand

Probably shortest (based on OR operator and its precedence)

x-2||dosomething()

_x000D_
_x000D_
let x=1, y=2;_x000D_
let dosomething = s=>console.log(s); _x000D_
_x000D_
x-2||dosomething('x do something');_x000D_
y-2||dosomething('y do something');
_x000D_
_x000D_
_x000D_

Create Hyperlink in Slack

I am not sure if this is still bothering you but take a look at this page for slack text formatting:

https://api.slack.com/docs/message-formatting#linking_to_urls

For example using Python and the slack API:

from slackclient import SlackClient
slack_client = SlackClient(your_slack_token)
link_as_text_example = '<http://www.hyperlinkcode.com/|Hyperlink Code>'
slack_client.api_call("chat.postMessage", channel=channel_to_post, text=link_as_text_example , as_user=True)

You can also send a more advance JSON following the link: https://api.slack.com/docs/message-attachments

How do I reference the input of an HTML <textarea> control in codebehind?

First make sure you have the runat="server" attribute in your textarea tag like this

<textarea id="TextArea1" cols="20" rows="2" runat="server"></textarea>

Then you can access the content via:

string body = TextArea1.value;

What is the best IDE to develop Android apps in?

You can also develop rich UI filled Android applications using Adobe AIR. If you plan to go that route then Flex Builder Burrito is the best IDE. Take a look at this post as to how easy it is to build an AIR4Android app http://blog.air4android.com/?p=13

Should I always use a parallel stream when possible?

I watched one of the presentations of Brian Goetz (Java Language Architect & specification lead for Lambda Expressions). He explains in detail the following 4 points to consider before going for parallelization:

Splitting / decomposition costs
– Sometimes splitting is more expensive than just doing the work!
Task dispatch / management costs
– Can do a lot of work in the time it takes to hand work to another thread.
Result combination costs
– Sometimes combination involves copying lots of data. For example, adding numbers is cheap whereas merging sets is expensive.
Locality
– The elephant in the room. This is an important point which everyone may miss. You should consider cache misses, if a CPU waits for data because of cache misses then you wouldn't gain anything by parallelization. That's why array-based sources parallelize the best as the next indices (near the current index) are cached and there are fewer chances that CPU would experience a cache miss.

He also mentions a relatively simple formula to determine a chance of parallel speedup.

NQ Model:

N x Q > 10000

where,
N = number of data items
Q = amount of work per item

PostgreSQL delete with inner join

DELETE 
FROM m_productprice B  
     USING m_product C 
WHERE B.m_product_id = C.m_product_id AND
      C.upc = '7094' AND                 
      B.m_pricelist_version_id='1000020';

or

DELETE 
FROM m_productprice
WHERE m_pricelist_version_id='1000020' AND 
      m_product_id IN (SELECT m_product_id 
                       FROM m_product 
                       WHERE upc = '7094'); 

How to play a local video with Swift?

None of the above worked for me Swift 5 for Local Video Player

after reading apple documentation I was able to create simple example for playing video from Local resources

Here is code snip

import UIKit
import AVKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //TODO : Make Sure Add and copy "SampleVideo.mp4" file in project before play
    }

    @IBAction func playLocalVideo(_ sender: Any) {

        guard let path = Bundle.main.path(forResource: "SampleVideo", ofType: "mp4") else {
            return
        }
        let videoURL = NSURL(fileURLWithPath: path)

        // Create an AVPlayer, passing it the local video url path
        let player = AVPlayer(url: videoURL as URL)
        let controller = AVPlayerViewController()
        controller.player = player
        present(controller, animated: true) {
            player.play()
        }
    }

}

PS: Make sure you don't forget to add and copy video named "SampleVideo.mp4" in project

Count the cells with same color in google spreadsheet

The previous functions didn't work for me, so I've made another function that use the same logic of one of the answers above: parse the formula in the cell to find the referenced range of cells to examine and than look for the coloured cells. You can find a detailed description here: Google Script count coloured with reference, but the code is below:

function countColoured(reference) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var formula = SpreadsheetApp.getActiveRange().getFormula();
  var args = formula.match(/=\w+\((.*)\)/i)[1].split('!');
  try {
    if (args.length == 1) {
      var range = sheet.getRange(args[0]);
    }
    else {
      sheet = ss.getSheetByName(args[0].replace(/'/g, ''));
      range = sheet.getRange(args[1]);
    }
  }
  catch(e) {
    throw new Error(args.join('!') + ' is not a valid range');
  }
  var c = 0;
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();
  for (var i = 1; i <= numRows; i++) {
    for (var j = 1; j <= numCols; j++) {
      c = c + ( range.getCell(i,j).getBackground() == "#ffffff" ? 0 : 1 );
    }
  }
  return c > 0 ? c : "" ;
}

Change the background color of CardView programmatically

Cardview is a bit coy. I had list of colors in my structure and Model is like

class ModelColor : Serializable {

var id: Int? = 0
var title: String? = ""
var color: Int? = 0// HERE IS THE COLOR FIELD WE WILL USE

constructor(id: Int?, title: String?, color: Int?) {
    this.id = id
    this.title = title
    this.color = color
}

}

load the model with color, last item on constructure taking from R.color

 list.add(ModelColor(2, getString(R.string.orange), R.color.orange_500))

and finaly you can setBackgriundResource

 cv_add_goal_choose_color.setBackgroundResource(color)

Pick any kind of file via an Intent in Android

This gives me the best result:

    Intent intent;
    if (android.os.Build.MANUFACTURER.equalsIgnoreCase("samsung")) {
        intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
        intent.putExtra("CONTENT_TYPE", "*/*");
        intent.addCategory(Intent.CATEGORY_DEFAULT);
    } else {

        String[] mimeTypes =
                {"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
                        "application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
                        "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
                        "text/plain",
                        "application/pdf",
                        "application/zip", "application/vnd.android.package-archive"};

        intent = new Intent(Intent.ACTION_GET_CONTENT); // or ACTION_OPEN_DOCUMENT
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
    }

Select SQL Server database size

EXEC sp_spaceused @oneresultset = 1 show in 1 row all of the result

if you execute just 'EXEC sp_spaceused' you will see two rows Work in SQL Server Management Studio v17.9

serialize/deserialize java 8 java.time with Jackson JSON mapper

If you are using Jersey then you need to add the Maven dependency (jackson-datatype-jsr310) as the others suggested and register your object mapper instance like so:

@Provider
public class JacksonObjectMapper implements ContextResolver<ObjectMapper> {

  final ObjectMapper defaultObjectMapper;

  public JacksonObjectMapper() {
    defaultObjectMapper = createDefaultMapper();
  }

  @Override
  public ObjectMapper getContext(Class<?> type) {
    return defaultObjectMapper;
  }

  private static ObjectMapper createDefaultMapper() {
    final ObjectMapper mapper = new ObjectMapper();    
    mapper.registerModule(new JavaTimeModule());
    return mapper;
  }
}

When registering Jackson in your resources, you need to add this mapper like so:

final ResourceConfig rc = new ResourceConfig().packages("<your package>");
rc
  .register(JacksonObjectMapper.class)
  .register(JacksonJaxbJsonProvider.class);

Making a flex item float right

You can't use float inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle.

So if you want to position child element to right of parent element you can use margin-left: auto but now child element will also push other div to the right as you can see here Fiddle.

What you can do now is change order of elements and set order: 2 on child element so it doesn't affect second div

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
}_x000D_
.child {_x000D_
  margin-left: auto;_x000D_
  order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child">Ignore parent?</div>_x000D_
  <div>another child</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

HQL ERROR: Path expected for join

select u from UserGroup ug inner join ug.user u 
where ug.group_id = :groupId 
order by u.lastname

As a named query:

@NamedQuery(
  name = "User.findByGroupId",
  query =
    "SELECT u FROM UserGroup ug " +
    "INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)

Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.

Change UITableView height dynamically

There isn't a system feature to change the height of the table based upon the contents of the tableview. Having said that, it is possible to programmatically change the height of the tableview based upon the contents, specifically based upon the contentSize of the tableview (which is easier than manually calculating the height yourself). A few of the particulars vary depending upon whether you're using the new autolayout that's part of iOS 6, or not.

But assuming you're configuring your table view's underlying model in viewDidLoad, if you want to then adjust the height of the tableview, you can do this in viewDidAppear:

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self adjustHeightOfTableview];
}

Likewise, if you ever perform a reloadData (or otherwise add or remove rows) for a tableview, you'd want to make sure that you also manually call adjustHeightOfTableView there, too, e.g.:

- (IBAction)onPressButton:(id)sender
{
    [self buildModel];
    [self.tableView reloadData];

    [self adjustHeightOfTableview];
}

So the question is what should our adjustHeightOfTableview do. Unfortunately, this is a function of whether you use the iOS 6 autolayout or not. You can determine if you have autolayout turned on by opening your storyboard or NIB and go to the "File Inspector" (e.g. press option+command+1 or click on that first tab on the panel on the right):

enter image description here

Let's assume for a second that autolayout was off. In that case, it's quite simple and adjustHeightOfTableview would just adjust the frame of the tableview:

- (void)adjustHeightOfTableview
{
    CGFloat height = self.tableView.contentSize.height;
    CGFloat maxHeight = self.tableView.superview.frame.size.height - self.tableView.frame.origin.y;

    // if the height of the content is greater than the maxHeight of
    // total space on the screen, limit the height to the size of the
    // superview.

    if (height > maxHeight)
        height = maxHeight;

    // now set the frame accordingly

    [UIView animateWithDuration:0.25 animations:^{
        CGRect frame = self.tableView.frame;
        frame.size.height = height;
        self.tableView.frame = frame;

        // if you have other controls that should be resized/moved to accommodate
        // the resized tableview, do that here, too
    }];
}

If your autolayout was on, though, adjustHeightOfTableview would adjust a height constraint for your tableview:

- (void)adjustHeightOfTableview
{
    CGFloat height = self.tableView.contentSize.height;
    CGFloat maxHeight = self.tableView.superview.frame.size.height - self.tableView.frame.origin.y;

    // if the height of the content is greater than the maxHeight of
    // total space on the screen, limit the height to the size of the
    // superview.

    if (height > maxHeight)
        height = maxHeight;

    // now set the height constraint accordingly

    [UIView animateWithDuration:0.25 animations:^{
        self.tableViewHeightConstraint.constant = height;
        [self.view setNeedsUpdateConstraints];
    }];
}

For this latter constraint-based solution to work with autolayout, we must take care of a few things first:

  1. Make sure your tableview has a height constraint by clicking on the center button in the group of buttons here and then choose to add the height constraint:

    add height constraint

  2. Then add an IBOutlet for that constraint:

    add IBOutlet

  3. Make sure you adjust other constraints so they don't conflict if you adjust the size tableview programmatically. In my example, the tableview had a trailing space constraint that locked it to the bottom of the screen, so I had to adjust that constraint so that rather than being locked at a particular size, it could be greater or equal to a value, and with a lower priority, so that the height and top of the tableview would rule the day:

    adjust other constraints

    What you do here with other constraints will depend entirely upon what other controls you have on your screen below the tableview. As always, dealing with constraints is a little awkward, but it definitely works, though the specifics in your situation depend entirely upon what else you have on the scene. But hopefully you get the idea. Bottom line, with autolayout, make sure to adjust your other constraints (if any) to be flexible to account for the changing tableview height.

As you can see, it's much easier to programmatically adjust the height of a tableview if you're not using autolayout, but in case you are, I present both alternatives.

Loop through array of values with Arrow Function

One statement can be written as such:

someValues.forEach(x => console.log(x));

or multiple statements can be enclosed in {} like this:

someValues.forEach(x => { let a = 2 + x; console.log(a); });

How to run vi on docker container?

Alternatively, keep your docker images small by not installing unnecessary editors. You can edit the files over ssh from the docker host to the container:

vim scp://remoteuser@container-ip//path/to/document

How to Auto-start an Android Application?

If by autostart you mean auto start on phone bootup then you should register a BroadcastReceiver for the BOOT_COMPLETED Intent. Android systems broadcasts that intent once boot is completed.

Once you receive that intent you can launch a Service that can do whatever you want to do.

Keep note though that having a Service running all the time on the phone is generally a bad idea as it eats up system resources even when it is idle. You should launch your Service / application only when needed and then stop it when not required.

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

As @Jthorpe alluded to, ComponentClass only allows either Component or PureComponent but not a FunctionComponent.

If you attempt to pass a FunctionComponent, typescript will throw an error similar to...

Type '(props: myProps) => Element' provides no match for the signature 'new (props: myProps, context?: any): Component<myProps, any, any>'.

However, by using ComponentType rather than ComponentClass you allow for both cases. Per the react declaration file the type is defined as...

type ComponentType<P = {}> = ComponentClass<P, any> | FunctionComponent<P>

How to make an HTML back link?

You can also use history.back() alongside document.write() to show link only when there is actually somewhere to go back to:

<script>
  if (history.length > 1) {
    document.write('<a href="javascript:history.back()">Go back</a>');
  }
</script>

How to place a JButton at a desired location in a JFrame using Java

First, remember your JPanel size height and size width, then observe: JButton coordinates is (xo, yo, x length , y length). If your window is 800x600, you just need to write:

JButton.setBounds(0, 500, 100, 100);

You just need to use a coordinate gap to represent the button, and know where the window ends and where the window begins.

Is an HTTPS query string secure?

Yes, from the moment on you establish a HTTPS connection everyting is secure. The query string (GET) as the POST is sent over SSL.

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

How do I turn off the mysql password validation?

On some installations, you cannot execute this command until you have reset the root password. You cannot reset the root password, until you execute this command. Classic Catch-22.

One solution not mention by other responders is to temporarily disable the plugin via mysql configuration. In any my.cnf, in the [mysqld] section, add:

skip-validate_password=1

and restart the server. Change the password, and set the value back to 0, and restart again.

Laravel Redirect Back with() Message

Here is the 100% solution

*Above mentioned solutions does not works for me but this one works for me in laravel 5.8:

$status = 'Successfully Done';
return back()->with(['status' => $status]);

and receive it as:

@if(session()->has('status'))
     <p class="alert alert-success">{{session('status')}}</p>
@endif

How to add image in a TextView text?

This might Help You

  SpannableStringBuilder ssBuilder;

        ssBuilder = new SpannableStringBuilder(" ");
        // working code ImageSpan image = new ImageSpan(textView.getContext(), R.drawable.image);
        Drawable image = ContextCompat.getDrawable(textView.getContext(), R.drawable.image);
        float scale = textView.getContext().getResources().getDisplayMetrics().density;
        int width = (int) (12 * scale + 0.5f);
        int height = (int) (18 * scale + 0.5f);
        image.setBounds(0, 0, width, height);
        ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BASELINE);
        ssBuilder.setSpan(
                imageSpan, // Span to add
                0, // Start of the span (inclusive)
                1, // End of the span (exclusive)
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE);// Do not extend the span when text add later

        ssBuilder.append(" " + text);
        ssBuilder = new SpannableStringBuilder(text);
        textView.setText(ssBuilder);

nginx upload client_max_body_size issue

From the documentation:

It is necessary to keep in mind that the browsers do not know how to correctly show this error.

I suspect this is what's happening, if you inspect the HTTP to-and-fro using tools such as Firebug or Live HTTP Headers (both Firefox extensions) you'll be able to see what's really going on.

Parse XML using JavaScript

I'm guessing from your last question, asked 20 minutes before this one, that you are trying to parse (read and convert) the XML found through using GeoNames' FindNearestAddress.

If your XML is in a string variable called txt and looks like this:

<address>
  <street>Roble Ave</street>
  <mtfcc>S1400</mtfcc>
  <streetNumber>649</streetNumber>
  <lat>37.45127</lat>
  <lng>-122.18032</lng>
  <distance>0.04</distance>
  <postalcode>94025</postalcode>
  <placename>Menlo Park</placename>
  <adminCode2>081</adminCode2>
  <adminName2>San Mateo</adminName2>
  <adminCode1>CA</adminCode1>
  <adminName1>California</adminName1>
  <countryCode>US</countryCode>
</address>

Then you can parse the XML with Javascript DOM like this:

if (window.DOMParser)
{
    parser = new DOMParser();
    xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // Internet Explorer
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(txt);
}

And get specific values from the nodes like this:

//Gets house address number
xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue;

//Gets Street name
xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue;

//Gets Postal Code
xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;

JSFiddle


Feb. 2019 edit:

In response to @gaugeinvariante's concerns about xml with Namespace prefixes. Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:

NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge

_x000D_
_x000D_
// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt_x000D_
txt = `_x000D_
<address xmlns:p='example.com/postal' xmlns:s='example.com/street' xmlns:sn='example.com/streetNum'>_x000D_
  <s:street>Roble Ave</s:street>_x000D_
  <sn:streetNumber>649</sn:streetNumber>_x000D_
  <p:postalcode>94025</p:postalcode>_x000D_
</address>`;_x000D_
_x000D_
//Everything else the same_x000D_
if (window.DOMParser)_x000D_
{_x000D_
    parser = new DOMParser();_x000D_
    xmlDoc = parser.parseFromString(txt, "text/xml");_x000D_
}_x000D_
else // Internet Explorer_x000D_
{_x000D_
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");_x000D_
    xmlDoc.async = false;_x000D_
    xmlDoc.loadXML(txt);_x000D_
}_x000D_
_x000D_
//The prefix should not be included when you request the xml namespace_x000D_
//Gets "streetNumber" (note there is no prefix of "sn"_x000D_
console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Street name_x000D_
console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Postal Code_x000D_
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);
_x000D_
_x000D_
_x000D_

Spring Boot - Handle to Hibernate SessionFactory

It works with Spring Boot 2.1.0 and Hibernate 5

@PersistenceContext
private EntityManager entityManager;

Then you can create new Session by using entityManager.unwrap(Session.class)

Session session = null;
if (entityManager == null
    || (session = entityManager.unwrap(Session.class)) == null) {

    throw new NullPointerException();
}

example create query:

session.createQuery("FROM Student");

application.properties:

spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:db11g
spring.datasource.username=admin
spring.datasource.password=admin
spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect

Does Arduino use C or C++?

Arduino sketches are written in C++.

Here is a typical construct you'll encounter:

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
...
lcd.begin(16, 2);
lcd.print("Hello, World!");

That's C++, not C.

Hence do yourself a favor and learn C++. There are plenty of books and online resources available.

Convert char to int in C and C++

I was having problems converting a char array like "7c7c7d7d7d7d7c7c7c7d7d7d7d7c7c7c7c7c7c7d7d7c7c7c7c7d7c7d7d7d7c7c2e2e2e" into its actual integer value that would be able to be represented by `7C' as one hexadecimal value. So, after cruising for help I created this, and thought it would be cool to share.

This separates the char string into its right integers, and may be helpful to more people than just me ;)

unsigned int* char2int(char *a, int len)
{
    int i,u;
    unsigned int *val = malloc(len*sizeof(unsigned long));

    for(i=0,u=0;i<len;i++){
        if(i%2==0){
            if(a[i] <= 57)
                val[u] = (a[i]-50)<<4;
            else
                val[u] = (a[i]-55)<<4;
        }
        else{
            if(a[i] <= 57)
                val[u] += (a[i]-50);
            else
                val[u] += (a[i]-55);
            u++;
        }
    }
    return val;
}

Hope it helps!

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

Best way to check if a URL is valid

Actually... filter_var($url, FILTER_VALIDATE_URL); doesn't work very well. When you type in a real url, it works but, it only checks for http:// so if you type something like "http://weirtgcyaurbatc", it will still say it's real.

Difference between string object and string literal

There is a subtle differences between String object and string literal.

String s = "abc"; // creates one String object and one reference variable

In this simple case, "abc" will go in the pool and s will refer to it.

String s = new String("abc"); // creates two objects,and one reference variable

In this case, because we used the new keyword, Java will create a new String object in normal (non-pool) memory, and s will refer to it. In addition, the literal "abc" will be placed in the pool.

Reset push notification settings for app

The same tech note as refered to in the accepted answer (TN2265 - Troubleshooting Push Notifications) has since been updated with a solution for iOS 5 and above.

In short: create a backup and restore from it every time.

On iOS 5 and later, reset the push notifications permissions alert by restoring the device from a backup (r. 11450187). Here are the steps to do this efficiently:

  1. Use the Xcode Organizer to install your app on the device. The key is to install the app for the first time without running it.
  2. Use iTunes to back up the device.
  3. Run the app. The push notifications permissions alert will be presented.
  4. When you want to reset the push notifications permissions alert, restore the device from the backup you created in the first step.

Executing another application from Java

Here is an example of how to use ProcessBuilder to execute your remote application. Since you do not care about input/output and/or errors, you can do as follows:

List<String> args = new ArrayList<String>();
args.add ("script.bat"); // command name
args.add ("-option"); // optional args added as separate list items
ProcessBuilder pb = new ProcessBuilder (args);
Process p = pb.start();
p.waitFor();

the waitFor() method will wait until the process had ended before continuing. This method returns the error code of the process but, since you don't care about it, I didn't put it in the example.

Creating a new user and password with Ansible

try like this

vars_prompt:
 - name: "user_password"    
   prompt: "Enter a password for the user"    
   private: yes    
   encrypt: "md5_crypt" #need to have python-passlib installed in local machine before we can use it    
   confirm: yes    
   salt_size: 7

 - name: "add new user" user: name="{{user_name}}" comment="{{description_user}}" password="{{user_password}}" home="{{home_dir}}" shell="/bin/bash"

Recommended way to get hostname in Java

hostName == null;
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
{
    while (interfaces.hasMoreElements()) {
        NetworkInterface nic = interfaces.nextElement();
        Enumeration<InetAddress> addresses = nic.getInetAddresses();
        while (hostName == null && addresses.hasMoreElements()) {
            InetAddress address = addresses.nextElement();
            if (!address.isLoopbackAddress()) {
                hostName = address.getHostName();
            }
        }
    }
}