Programs & Examples On #Svg

Scalable Vector Graphics (SVG) is an XML-based two-dimensional vector graphics format that can also be used in HTML. Do not add this tag just because your project uses SVG. Instead, add the tag if your question is either about SVG, or closely related to it, like how to achieve something with SVG.

How to extract svg as file from web page

On chrome when are in the SVG URL, you can do CTRL+S or CMD+S and it automatically propose you to save the page as an .SVG try it out : https://upload.wikimedia.org/wikipedia/commons/9/90/Benjamin_Franklin-10_Dollar_Bill_Portrait-Vector.svg

Can I change the fill color of an svg path with CSS?

you put this css for svg circle.

svg:hover circle{
    fill: #F6831D;
    stroke-dashoffset: 0;
    stroke-dasharray: 700;
    stroke-width: 2;
}

Easiest way to use SVG in Android?

Rather than adding libraries which increases your apk size, I will suggest you to convert Svg to drawable using http://inloop.github.io/svg2android/ . and add vectorDrawables.useSupportLibrary = true in gradle,

HTML5 Canvas vs. SVG vs. div

To add to this, I've been doing a diagram application, and initially started out with canvas. The diagram consists of many nodes, and they can get quite big. The user can drag elements in the diagram around.

What I found was that on my Mac, for very large images, SVG is superior. I have a MacBook Pro 2013 13" Retina, and it runs the fiddle below quite well. The image is 6000x6000 pixels, and has 1000 objects. A similar construction in canvas was impossible to animate for me when the user was dragging objects around in the diagram.

On modern displays you also have to account for different resolutions, and here SVG gives you all of this for free.

Fiddle: http://jsfiddle.net/knutsi/PUcr8/16/

Fullscreen: http://jsfiddle.net/knutsi/PUcr8/16/embedded/result/

var wiggle_factor = 0.0;
nodes = [];

// create svg:
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('style', 'border: 1px solid black');
svg.setAttribute('width', '6000');
svg.setAttribute('height', '6000');

svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink",
    "http://www.w3.org/1999/xlink");

document.body.appendChild(svg);


function makeNode(wiggle) {
    var node = document.createElementNS("http://www.w3.org/2000/svg", "g");
    var node_x = (Math.random() * 6000);
    var node_y = (Math.random() * 6000);
    node.setAttribute("transform", "translate(" + node_x + ", " + node_y +")");

    // circle:
    var circ = document.createElementNS("http://www.w3.org/2000/svg", "circle");
    circ.setAttribute( "id","cir")
    circ.setAttribute( "cx", 0 + "px")
    circ.setAttribute( "cy", 0 + "px")
    circ.setAttribute( "r","100px");
    circ.setAttribute('fill', 'red');
    circ.setAttribute('pointer-events', 'inherit')

    // text:
    var text = document.createElementNS("http://www.w3.org/2000/svg", "text");
    text.textContent = "This is a test! ÅÆØ";

    node.appendChild(circ);
    node.appendChild(text);

    node.x = node_x;
    node.y = node_y;

    if(wiggle)
        nodes.push(node)
    return node;
}

// populate with 1000 nodes:
for(var i = 0; i < 1000; i++) {
    var node = makeNode(true);
    svg.appendChild(node);
}

// make one mapped to mouse:
var bnode = makeNode(false);
svg.appendChild(bnode);

document.body.onmousemove=function(event){
    bnode.setAttribute("transform","translate(" +
        (event.clientX + window.pageXOffset) + ", " +
        (event.clientY + window.pageYOffset) +")");
};

setInterval(function() {
    wiggle_factor += 1/60;
    nodes.forEach(function(node) {

        node.setAttribute("transform", "translate(" 
                          + (Math.sin(wiggle_factor) * 200 + node.x) 
                          + ", " 
                          + (Math.sin(wiggle_factor) * 200 + node.y) 
                          + ")");        
    })
},1000/60);

How to style SVG <g> element?

I know its long after this question was asked and answered - and I am sure that the accepted solution is right, but the purist in me would rather not add an extra element to the SVG when I can achieve the same or similar with straight CSS.

Whilst it is true that you cannot style the g container element in most ways - you can definitely add an outline to it and style that - even changing it on hover of the g - as shown in the snippet.

It not as good in one regard as the other way - you can put the outline box around the grouped elements - but not a background behind it. Sot its not perfect and won't solve the issue for everyone - but I would rather have the outline done with css than have to add extra elements to the code just to provide styling hooks.

And this method definitely allows you to show grouping of related objects in your SVG's.

Just a thought.

_x000D_
_x000D_
g {_x000D_
    outline: solid 3px blue;_x000D_
    outline-offset: 5px;_x000D_
  }_x000D_
_x000D_
g:hover {_x000D_
 outline-color: red_x000D_
}
_x000D_
<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">_x000D_
  <g>_x000D_
    <rect fill="blue" stroke-width="2" height="112" width="84" y="55" x="55" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke="#000000"/>_x000D_
    <ellipse fill="#FF0000" stroke="#000000" stroke-width="5" stroke-dasharray="null" stroke-linejoin="null" stroke-linecap="null" cx="155" cy="65" id="svg_7" rx="64" ry="56"/>     _x000D_
  </g>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Resizing SVG in html?

Try these:

  1. Set the missing viewbox and fill in the height and width values of the set height and height attributes in the svg tag

  2. Then scale the picture simply by setting the height and width to the desired percent values. Good luck.

  3. Set a fixed aspect ratio with preserveAspectRatio="X200Y200 meet (e.g. 200px), but it's not necessary

e.g.

 <svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   width="10%" 
   height="10%"
   preserveAspectRatio="x200Y200 meet"
   viewBox="0 0 350 350"
   id="svg2"
   version="1.1"
   inkscape:version="0.48.0 r9654"
   sodipodi:docname="namesvg.svg">

Why don’t my SVG images scale using the CSS "width" property?

The transform CSS property lets you rotate, scale, skew, or translate an element.

So you can easily use the transform: scale(2.5); option to scale 2.5 times for example.

Inline SVG in CSS

You can also just do this:

_x000D_
_x000D_
<svg viewBox="0 0 32 32">
      <path d="M11.333 13.173c0-2.51 2.185-4.506 4.794-4.506 2.67 0 4.539 2.053 4.539 4.506 0 2.111-0.928 3.879-3.836 4.392v0.628c0 0.628-0.496 1.141-1.163 1.141s-1.163-0.513-1.163-1.141v-1.654c0-0.628 0.751-1.141 1.419-1.141 1.335 0 2.571-1.027 2.571-2.224 0-1.255-1.092-2.224-2.367-2.224-1.335 0-2.367 1.027-2.367 2.224 0 0.628-0.546 1.141-1.214 1.141s-1.214-0.513-1.214-1.141zM15.333 23.333c-0.347 0-0.679-0.143-0.936-0.404s-0.398-0.597-0.398-0.949 0.141-0.689 0.398-0.949c0.481-0.488 1.39-0.488 1.871 0 0.257 0.26 0.398 0.597 0.398 0.949s-0.141 0.689-0.398 0.949c-0.256 0.26-0.588 0.404-0.935 0.404zM16 26.951c-6.040 0-10.951-4.911-10.951-10.951s4.911-10.951 10.951-10.951c6.040 0 10.951 4.911 10.951 10.951s-4.911 10.951-10.951 10.951zM16 3.333c-6.984 0-12.667 5.683-12.667 12.667s5.683 12.667 12.667 12.667c6.984 0 12.667-5.683 12.667-12.667s-5.683-12.667-12.667-12.667z"></path>
</svg>
_x000D_
_x000D_
_x000D_

Creating SVG elements dynamically with javascript inside HTML

Change

var svg   = document.documentElement;

to

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");

so that you create a SVG element.

For the link to be an hyperlink, simply add a href attribute :

h.setAttributeNS(null, 'href', 'http://www.google.com');

Demonstration

how to get bounding box for div element in jquery

using JQuery:

myelement=$("#myelement")
[myelement.offset().left, myelement.offset().top,  myelement.width(), myelement.height()]

How to add a tooltip to an svg graphic?

Can you use simply the SVG <title> element and the default browser rendering it conveys? (Note: this is not the same as the title attribute you can use on div/img/spans in html, it needs to be a child element named title)

_x000D_
_x000D_
rect {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  fill: #69c;_x000D_
  stroke: #069;_x000D_
  stroke-width: 5px;_x000D_
  opacity: 0.5_x000D_
}
_x000D_
<p>Mouseover the rect to see the tooltip on supporting browsers.</p>_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg">_x000D_
  <rect>_x000D_
    <title>Hello, World!</title>_x000D_
  </rect>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Alternatively, if you really want to show HTML in your SVG, you can embed HTML directly:

_x000D_
_x000D_
rect {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  fill: #69c;_x000D_
  stroke: #069;_x000D_
  stroke-width: 5px;_x000D_
  opacity: 0.5_x000D_
}_x000D_
_x000D_
foreignObject {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
svg div {_x000D_
  text-align: center;_x000D_
  line-height: 150px;_x000D_
}
_x000D_
<svg xmlns="http://www.w3.org/2000/svg">_x000D_
  <rect/>_x000D_
  <foreignObject>_x000D_
    <body xmlns="http://www.w3.org/1999/xhtml">_x000D_
      <div>_x000D_
        Hello, <b>World</b>!_x000D_
      </div>_x000D_
    </body>      _x000D_
  </foreignObject>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

…but then you'd need JS to turn the display on and off. As shown above, one way to make the label appear at the right spot is to wrap the rect and HTML in the same <g> that positions them both together.

To use JS to find where an SVG element is on screen, you can use getBoundingClientRect(), e.g. http://phrogz.net/svg/html_location_in_svg_in_html.xhtml

Circle drawing with SVG's arc path

In reference to Anthony’s solution, here is a function to get the path:

function circlePath(cx, cy, r){
    return 'M '+cx+' '+cy+' m -'+r+', 0 a '+r+','+r+' 0 1,0 '+(r*2)+',0 a '+r+','+r+' 0 1,0 -'+(r*2)+',0';
}

Using SVG as background image

You can try removing the width and height attributes on the svg root element, adding preserveAspectRatio="none" viewBox="0 0 1024 800" instead. It makes a difference in Opera at least, assuming you wanted the svg to stretch to fill the entire region defined by the CSS styles.

jquery's append not working with svg element?

The accepted answer by Bobince is a short, portable solution. If you need to not only append SVG but also manipulate it, you could try the JavaScript library "Pablo" (I wrote it). It will feel familiar to jQuery users.

Your code example would then look like:

$(document).ready(function(){
    Pablo("svg").append('<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>');
});

You can also create SVG elements on the fly, without specifying markup:

var circle = Pablo.circle({
    cx:100,
    cy:50,
    r:40
}).appendTo('svg');

How to display svg icons(.svg files) in UI using React Component?

For some reasons above mentioned approaches did now work for me, before I followed the advice to add .default like this:

<div>
  <img src={require('../../mySvgImage.svg').default} alt='mySvgImage' />
</div>

Convert PDF to clean SVG?

Here is the NodeJS REST api for two PDF render scripts. https://github.com/pumppi/pdf2images

Scripts are: pdf2svg and Imagemagicks convert

How to place and center text in an SVG rectangle

For horizontal and vertical alignment of text in graphics, you might want to use the following CSS styles. In particular, note that dominant-baseline:middle is probably wrong, since this is (usually) half way between the top and the baseline, rather than half way between the top and the bottom. Also, some some sources (e.g. Mozilla) use dominant-baseline:hanging instead of dominant-baseline:text-before-edge. This is also probably wrong, since hanging is designed for Indic scripts. Of course, if you're using a mixture of Latin, Indic, ideographs or whatever, you'll probably need to read the documentation.

/* Horizontal alignment */
text.goesleft{text-anchor:end}
text.equalleftright{text-anchor:middle}
text.goesright{text-anchor:start}
/* Vertical alignment */
text.goesup{dominant-baseline:text-after-edge}
text.equalupdown{dominant-baseline:central}
text.goesdown{dominant-baseline:text-before-edge}
text.ruledpaper{dominant-baseline:alphabetic}

Edit: I've just noticed that Mozilla also uses dominant-baseline:baseline which is definitely wrong: it's not even a recognized value! I assume it's defaulting to the font default, which is alphabetic, so they got lucky.

More edit: Safari (11.1.2) understands text-before-edge but not text-after-edge. It also fails on ideographic. Great stuff, Apple. So you might be forced to use alphabetic and allow for descenders after all. Sorry.

How to linebreak an svg text within javascript?

I think this does what you want:

function ShowTooltip(evt, mouseovertext){
    // Make tooltip text        
    var tooltip_text = tt.childNodes.item(1);
    var words = mouseovertext.split("\\\n");
    var max_length = 0;

    for (var i=0; i<3; i++){
        tooltip_text.childNodes.item(i).firstChild.data = i<words.length ?  words[i] : " ";
        length = tooltip_text.childNodes.item(i).getComputedTextLength();
        if (length > max_length) {max_length = length;}
    }

    var x = evt.clientX + 14 + max_length/2;
    var y = evt.clientY + 29;
    tt.setAttributeNS(null,"transform", "translate(" + x + " " + y + ")")

    // Make tooltip background
    bg.setAttributeNS(null,"width", max_length+15);
    bg.setAttributeNS(null,"height", words.length*15+6);
    bg.setAttributeNS(null,"x",evt.clientX+8);
    bg.setAttributeNS(null,"y",evt.clientY+14);

    // Show everything
    tt.setAttributeNS(null,"visibility","visible");
    bg.setAttributeNS(null,"visibility","visible");
}

It splits the text on \\\n and for each puts each fragment in a tspan. Then it calculates the size of the box required based on the longest length of text and the number of lines. You will also need to change the tooltip text element to contain three tspans:

<g id="tooltip" visibility="hidden">
    <text><tspan>x</tspan><tspan x="0" dy="15">x</tspan><tspan x="0" dy="15">x</tspan></text>
</g>

This assumes that you never have more than three lines. If you want more than three lines you can add more tspans and increase the length of the for loop.

How to convert a PNG image to a SVG?

A png is a bitmap image style and an SVG is a vector-based graphics design which supports bitmaps so it's not as if it would convert the image to vectors, just an image embedded in a vector-based format. You could do this using http://www.inkscape.org/ which is free. It would embed it, however it also has a Live Trace like engine which will try to convert it to paths if you wish (using potrace). See live trace in adobe illustrator (commericial) is an example:

http://graphicssoft.about.com/od/illustrator/ss/sflivetrace.htm

is there a tool to create SVG paths from an SVG file?

(In reply to the "has the situation improved?" part of the question):

Unfortunately, not really. Illustrator's support for SVG has always been a little shaky, and, having mucked around in Illustrator's internals, I doubt we'll see much improvement as far as Illustrator is concerned.

If you're looking for DOM-style access to an Illustrator document, you might want to check out Hanpuku (Disclosure #1: I'm the author. Disclosure #2: It's research code, meaning there are bugs aplenty, and future support is unlikely).

With Hanpuku, you could do something like:

  1. Select the path of interest in Illustrator
  2. Click the "To D3" button
  3. In the script editor, type:

    selection.attr('d', 'M 0 0 L 20 134 L 233 24 Z');

  4. Click run

  5. If the change is as expected, click "To Illustrator" to apply the changes to the document

Granted, this approach doesn't expose the original path string. If you follow the instructions toward the end of the plugin's welcome page, it's possible to edit the Illustrator document with Chrome's developer tools, but there will be lots of ugly engineering exposed everywhere (the SVG DOM that mirrors the Illustrator document is buried inside an iframe deep in the extension—changing the DOM with Chrome's tools and clicking "To Illustrator" should still work, but you will likely encounter lots of problems).

TL;DR: Illustrator uses an internal model that's pretty different from SVG in a lot of ways, meaning that when you iterate between the two, currently, your only choice is to use the subset of features that both support in the same way.

IE11 meta element Breaks SVG

After trying the other suggestions to no avail I discovered that this issue was related to styling for me. I don't know a lot about the why but I found that my SVGs were not visible because they were not holding their place in the DOM.

In essence, the containers around my SVGs were at width: 0 and overflow: hidden.

I fixed this by setting a width on the containers but it is possible that there is a more direct solution to that particular issue.

How to change the color of an svg element?

Only SVG with path information. you can't do that to the image.. as the path you can change stroke and fill information and you are done. like Illustrator

so: via CSS you can overwrite path fill value

path { fill: orange; }

but if you want more flexible way as you want to change it with a text when having some hovering effect going on.. use

path { fill: currentcolor; }

_x000D_
_x000D_
body {_x000D_
  background: #ddd;_x000D_
  text-align: center;_x000D_
  padding-top: 2em;_x000D_
}_x000D_
_x000D_
.parent {_x000D_
  width: 320px;_x000D_
  height: 50px;_x000D_
  display: block;_x000D_
  transition: all 0.3s;_x000D_
  cursor: pointer;_x000D_
  padding: 12px;_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
/***  desired colors for children  ***/_x000D_
.parent{_x000D_
  color: #000;_x000D_
  background: #def;_x000D_
}_x000D_
.parent:hover{_x000D_
  color: #fff;_x000D_
  background: #85c1fc;_x000D_
}_x000D_
_x000D_
.parent span{_x000D_
  font-size: 18px;_x000D_
  margin-right: 8px;_x000D_
  font-weight: bold;_x000D_
  font-family: 'Helvetica';_x000D_
  line-height: 26px;_x000D_
  vertical-align: top;_x000D_
}_x000D_
.parent svg{_x000D_
  max-height: 26px;_x000D_
  width: auto;_x000D_
  display: inline;_x000D_
}_x000D_
_x000D_
/****  magic trick  *****/_x000D_
.parent svg path{_x000D_
  fill: currentcolor;_x000D_
}
_x000D_
<div class='parent'>_x000D_
  <span>TEXT WITH SVG</span>_x000D_
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="128" height="128" viewBox="0 0 32 32">_x000D_
<path d="M30.148 5.588c-2.934-3.42-7.288-5.588-12.148-5.588-8.837 0-16 7.163-16 16s7.163 16 16 16c4.86 0 9.213-2.167 12.148-5.588l-10.148-10.412 10.148-10.412zM22 3.769c1.232 0 2.231 0.999 2.231 2.231s-0.999 2.231-2.231 2.231-2.231-0.999-2.231-2.231c0-1.232 0.999-2.231 2.231-2.231z"></path>_x000D_
</svg>_x000D_
</div>
_x000D_
_x000D_
_x000D_

img src SVG changing the styles with CSS

Why not create a webfont with your svg image or images, import the webfont in the css and then just change the color of the glyph using the css color attribute? No javascript needed

d3 add text to circle

Extended the example above to fit the actual requirements, where circled is filled with solid background color, then with striped pattern & after that text node is placed on the center of the circle.

_x000D_
_x000D_
var width = 960,_x000D_
  height = 500,_x000D_
  json = {_x000D_
    "nodes": [{_x000D_
      "x": 100,_x000D_
      "r": 20,_x000D_
      "label": "Node 1",_x000D_
      "color": "red"_x000D_
    }, {_x000D_
      "x": 200,_x000D_
      "r": 25,_x000D_
      "label": "Node 2",_x000D_
      "color": "blue"_x000D_
    }, {_x000D_
      "x": 300,_x000D_
      "r": 30,_x000D_
      "label": "Node 3",_x000D_
      "color": "green"_x000D_
    }]_x000D_
  };_x000D_
_x000D_
var svg = d3.select("body").append("svg")_x000D_
  .attr("width", width)_x000D_
  .attr("height", height)_x000D_
_x000D_
svg.append("defs")_x000D_
  .append("pattern")_x000D_
  .attr({_x000D_
    "id": "stripes",_x000D_
    "width": "8",_x000D_
    "height": "8",_x000D_
    "fill": "red",_x000D_
    "patternUnits": "userSpaceOnUse",_x000D_
    "patternTransform": "rotate(60)"_x000D_
  })_x000D_
  .append("rect")_x000D_
  .attr({_x000D_
    "width": "4",_x000D_
    "height": "8",_x000D_
    "transform": "translate(0,0)",_x000D_
    "fill": "grey"_x000D_
  });_x000D_
_x000D_
function plotChart(json) {_x000D_
  /* Define the data for the circles */_x000D_
  var elem = svg.selectAll("g myCircleText")_x000D_
    .data(json.nodes)_x000D_
_x000D_
  /*Create and place the "blocks" containing the circle and the text */_x000D_
  var elemEnter = elem.enter()_x000D_
    .append("g")_x000D_
    .attr("class", "node-group")_x000D_
    .attr("transform", function(d) {_x000D_
      return "translate(" + d.x + ",80)"_x000D_
    })_x000D_
_x000D_
  /*Create the circle for each block */_x000D_
  var circleInner = elemEnter.append("circle")_x000D_
    .attr("r", function(d) {_x000D_
      return d.r_x000D_
    })_x000D_
    .attr("stroke", function(d) {_x000D_
      return d.color;_x000D_
    })_x000D_
    .attr("fill", function(d) {_x000D_
      return d.color;_x000D_
    });_x000D_
_x000D_
  var circleOuter = elemEnter.append("circle")_x000D_
    .attr("r", function(d) {_x000D_
      return d.r_x000D_
    })_x000D_
    .attr("stroke", function(d) {_x000D_
      return d.color;_x000D_
    })_x000D_
    .attr("fill", "url(#stripes)");_x000D_
_x000D_
  /* Create the text for each block */_x000D_
  elemEnter.append("text")_x000D_
    .text(function(d) {_x000D_
      return d.label_x000D_
    })_x000D_
    .attr({_x000D_
      "text-anchor": "middle",_x000D_
      "font-size": function(d) {_x000D_
        return d.r / ((d.r * 10) / 100);_x000D_
      },_x000D_
      "dy": function(d) {_x000D_
        return d.r / ((d.r * 25) / 100);_x000D_
      }_x000D_
    });_x000D_
};_x000D_
_x000D_
plotChart(json);
_x000D_
.node-group {_x000D_
  fill: #ffffff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
_x000D_
_x000D_
_x000D_

Output:

enter image description here

Below is the link to codepen also:

See the Pen D3-Circle-Pattern-Text by Manish Kumar (@mkdudeja) on CodePen.

Thanks, Manish Kumar

How to convert a SVG to a PNG with ImageMagick?

One thing that just bit me was setting the -density AFTER the input file name. That didn't work. Moving it to the first option in convert (before anything else) made it work (for me, YMMV, etc).

make an html svg object also a clickable link

The easiest way is to not use <object>. Instead use an <img> tag and the anchor should work just fine.

Do I use <img>, <object>, or <embed> for SVG files?

My two cents: as of 2019, 93% of browsers in use (and 100% of the last two version of every one of them) can handle SVG in <img> elements:

enter image description here

Source: Can I Use

So we could say that there's no reason to use <object> anymore.

However it's still has its pros:

  • When inspecting (e.g. with Chrome Dev Tools) you are presented with the whole SVG markup in case you wanted to tamper a bit with it and see live changes.

  • It provides a very robust fallback implementation in case your browser does not support SVGs (wait, but every one of them does!) which also works if the SVG isn't found. This was a key feature of XHTML2 spec, which is like betamax or HD-DVD

But there are also cons:

Default background color of SVG root element

Found this works in Safari. SVG only colors in with background-color where an element's bounding box covers. So, give it a border (stroke) with a zero pixel boundary. It fills in the whole thing for you with your background-color.

<svg style='stroke-width: 0px; background-color: blue;'> </svg>

Convert SVG to PNG in Python

Here is what I did using cairosvg:

from cairosvg import svg2png

svg_code = """
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <circle cx="12" cy="12" r="10"/>
        <line x1="12" y1="8" x2="12" y2="12"/>
        <line x1="12" y1="16" x2="12" y2="16"/>
    </svg>
"""

svg2png(bytestring=svg_code,write_to='output.png')

And it works like a charm!

See more: cairosvg document

SVG: text inside rect

Programmatically using D3:

body = d3.select('body')
svg = body.append('svg').attr('height', 600).attr('width', 200)
rect = svg.append('rect').transition().duration(500).attr('width', 150)
                .attr('height', 100)
                .attr('x', 40)
                .attr('y', 100)
                .style('fill', 'white')
                .attr('stroke', 'black')
text = svg.append('text').text('This is some information about whatever')
                .attr('x', 50)
                .attr('y', 150)
                .attr('fill', 'black')

How to use z-index in svg elements?

Try to invert #one and #two. Have a look to this fiddle : http://jsfiddle.net/hu2pk/3/

Update

In SVG, z-index is defined by the order the element appears in the document. You can have a look to this page too if you want : https://stackoverflow.com/a/482147/1932751

Is there a way to use SVG as content in a pseudo element :before or :after

Making use of CSS sprites and data uri gives extra interesting benefits like fast loading and less requests AND we get IE8 support by using image/base64:

Codepen sample using SVG

HTML

<div class="div1"></div>
<div class="div2"></div>

CSS

.div1:after, .div2:after {
  content: '';
  display: block;
  height: 80px;
  width: 80px;
  background-image: url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20height%3D%2280%22%20width%3D%22160%22%3E%0D%0A%20%20%3Ccircle%20cx%3D%2240%22%20cy%3D%2240%22%20r%3D%2238%22%20stroke%3D%22black%22%20stroke-width%3D%221%22%20fill%3D%22red%22%20%2F%3E%0D%0A%20%20%3Ccircle%20cx%3D%22120%22%20cy%3D%2240%22%20r%3D%2238%22%20stroke%3D%22black%22%20stroke-width%3D%221%22%20fill%3D%22blue%22%20%2F%3E%0D%0A%3C%2Fsvg%3E);
}
.div2:after {
  background-position: -80px 0;
}

For IE8, change to this:

  background-image: url(data:image/png;base64,data......);

Chrome not rendering SVG referenced via <img> tag

I make sure that I add the Style of the Image. It worked for me

style= "width:320; height:240"

vertical alignment of text element in SVG

According to SVG spec, alignment-baseline only applies to <tspan>, <textPath>, <tref> and <altGlyph>. My understanding is that it is used to offset those from the <text> object above them. I think what you are looking for is dominant-baseline.

Possible values of dominant-baseline are:

auto | use-script | no-change | reset-size | ideographic | alphabetic | hanging | mathematical | central | middle | text-after-edge | text-before-edge | inherit

Check the W3C recommendation for the dominant-baseline property for more information about each possible value.

Making an svg image object clickable with onclick, avoiding absolute positioning

When embedding same-origin SVGs using <object>, you can access the internal contents using objectElement.contentDocument.rootElement. From there, you can easily attach event handlers (e.g. via onclick, addEventListener(), etc.)

For example:

var object = /* get DOM node for <object> */;
var svg = object.contentDocument.rootElement;
svg.addEventListener('click', function() {
  console.log('hooray!');
});

Note that this is not possible for cross-origin <object> elements unless you also control the <object> origin server and can set CORS headers there. For cross-origin cases without CORS headers, access to contentDocument is blocked.

How to get coordinates of an svg element?

I use the consolidate function, like so:

 element.transform.baseVal.consolidate()

The .e and .f values correspond to the x and y coordinates

jQuery SVG, why can't I addClass?

I wrote this in my project, and it works... probably;)

$.fn.addSvgClass = function(className) {

    var attr
    this.each(function() {
        attr = $(this).attr('class')
        if(attr.indexOf(className) < 0) {
            $(this).attr('class', attr+' '+className+ ' ')
        }
    })
};    

$.fn.removeSvgClass = function(className) {

    var attr
    this.each(function() {
        attr = $(this).attr('class')
        attr = attr.replace(className , ' ')
        $(this).attr('class' , attr)
    })
};    

examples

$('path').addSvgClass('fillWithOrange')
$('path').removeSvgClass('fillWithOrange')

How to calculate the SVG Path for an arc (of a circle)

@opsb's answers is neat, but the center point is not accurate, moreover, as @Jithin noted, if the angle is 360, then nothing is drawn at all.

@Jithin fixed the 360 issue, but if you selected less than 360 degree, then you'll get a line closing the arc loop, which is not required.

I fixed that, and added some animation in the code below:

_x000D_
_x000D_
function myArc(cx, cy, radius, max){       _x000D_
       var circle = document.getElementById("arc");_x000D_
        var e = circle.getAttribute("d");_x000D_
        var d = " M "+ (cx + radius) + " " + cy;_x000D_
        var angle=0;_x000D_
        window.timer = window.setInterval(_x000D_
        function() {_x000D_
            var radians= angle * (Math.PI / 180);  // convert degree to radians_x000D_
            var x = cx + Math.cos(radians) * radius;  _x000D_
            var y = cy + Math.sin(radians) * radius;_x000D_
           _x000D_
            d += " L "+x + " " + y;_x000D_
            circle.setAttribute("d", d)_x000D_
            if(angle==max)window.clearInterval(window.timer);_x000D_
            angle++;_x000D_
        }_x000D_
      ,5)_x000D_
 }     _x000D_
_x000D_
  myArc(110, 110, 100, 360);_x000D_
    
_x000D_
<svg xmlns="http://www.w3.org/2000/svg" style="width:220; height:220;"> _x000D_
    <path d="" id="arc" fill="none" stroke="red" stroke-width="2" />_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

Capture Signature using HTML5 and iPad

Here's another canvas based version with variable width (based on drawing velocity) curves: demo at http://szimek.github.io/signature_pad and code at https://github.com/szimek/signature_pad.

signature sample

D3 transform scale and translate

Scott Murray wrote a great explanation of this[1]. For instance, for the code snippet:

svg.append("g")
    .attr("class", "axis")
    .attr("transform", "translate(0," + h + ")")
    .call(xAxis);

He explains using the following:

Note that we use attr() to apply transform as an attribute of g. SVG transforms are quite powerful, and can accept several different kinds of transform definitions, including scales and rotations. But we are keeping it simple here with only a translation transform, which simply pushes the whole g group over and down by some amount.

Translation transforms are specified with the easy syntax of translate(x,y), where x and y are, obviously, the number of horizontal and vertical pixels by which to translate the element.

[1]: From Chapter 8, "Cleaning it up" of Interactive Data Visualization for the Web, which used to be freely available and is now behind a paywall.

Converting SVG to PNG using C#

I'm using Batik for this. The complete Delphi code:

procedure ExecNewProcess(ProgramName : String; Wait: Boolean);
var
  StartInfo : TStartupInfo;
  ProcInfo : TProcessInformation;
  CreateOK : Boolean;
begin
  FillChar(StartInfo, SizeOf(TStartupInfo), #0);
  FillChar(ProcInfo, SizeOf(TProcessInformation), #0);
  StartInfo.cb := SizeOf(TStartupInfo);
  CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil, False,
              CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS,
              nil, nil, StartInfo, ProcInfo);
  if CreateOK then begin
    //may or may not be needed. Usually wait for child processes
    if Wait then
      WaitForSingleObject(ProcInfo.hProcess, INFINITE);
  end else
    ShowMessage('Unable to run ' + ProgramName);

  CloseHandle(ProcInfo.hProcess);
  CloseHandle(ProcInfo.hThread);
end;

procedure ConvertSVGtoPNG(aFilename: String);
const
  ExecLine = 'c:\windows\system32\java.exe -jar C:\Apps\batik-1.7\batik-rasterizer.jar ';
begin
  ExecNewProcess(ExecLine + aFilename, True);
end;

Changing SVG image color with javascript

Your SVG must be inline in your document in order to be styled with CSS. This can be done by writing the SVG markup directly into your HTML code, or by using SVG injection, which replaces the img element with the content from and SVG file with Javascript.

There is an open source library called SVGInject that does this for you. All you have to do is to add the attribute onload="SVGInject(this)" to you <img> tag.

A simple example using SVGInject looks like this:

<html>
  <head>
    <script src="svg-inject.min.js"></script>
  </head>
  <body>
    <img src="image.svg" onload="SVGInject(this)" />
  </body>
</html>

After the image is loaded the onload="SVGInject(this) will trigger the injection and the <img> element will be replaced by the contents of the SVG file provided in the src attribute.

Include an SVG (hosted on GitHub) in MarkDown

I have a working example with an img-tag, but your images won't display. The difference I see is the content-type.

I checked the github image from your post (the google doc images don't load at all because of connection failures). The image from github is delivered as content-type: text/plain, which won't get rendered as an image by your browser.

The correct content-type value for svg is image/svg+xml. So you have to make sure that svg files set the correct mime type, but that's a server issue.

Try it with http://svg.tutorial.aptico.de/grafik_svg/dummy3.svg and don't forget to specify width and height in the tag.

Can you control how an SVG's stroke-width is drawn?

No, you cannot specify whether the stroke is drawn inside or outside an element. I made a proposal to the SVG working group for this functionality in 2003, but it received no support (or discussion).

SVG proposed stroke-location example, from phrogz.net/SVG/stroke-location.svg

As I noted in the proposal,

  • you can achieve the same visual result as "inside" by doubling your stroke width and then using a clipping path to clip the object to itself, and
  • you can achieve the same visual result as 'outside' by doubling the stroke width and then overlaying a no-stroke copy of the object on top of itself.

Edit: This answer may be wrong in the future. It should be possible to achieve these results using SVG Vector Effects, by combining veStrokePath with veIntersect (for 'inside') or with veExclude (for 'outside). However, Vector Effects are still a working draft module with no implementations that I can yet find.

Edit 2: The SVG 2 draft specification includes a stroke-alignment property (with center|inside|outside possible values). This property may make it into UAs eventually.

Edit 3: Amusingly and dissapointingly, the SVG working group has removed stroke-alignment from SVG 2. You can see some of the concerns described after the prose here.

How to make a <svg> element expand or contract to its parent container?

@robertc has it right, but you also need to notice that svg, #container causes the svg to be scaled exponentially for anything but 100% (once for #container and once for svg).

In other words, if I applied 50% h/w to both elements, it's actually 50% of 50%, or .5 * .5, which equals .25, or 25% scale.

One selector works fine when used as @robertc suggests.

svg {
  width:50%;
  height:50%;
}

How to show SVG file on React Native?

Note: Svg does not work for android release versions so do not consider for android. It will work for android in debug mode only. But it works fine for ios.

Use https://github.com/vault-development/react-native-svg-uri

Install

npm install react-native-svg-uri --save
react-native link react-native-svg # not react-native-svg-uri

Usage

import SvgUri from 'react-native-svg-uri';


<SvgUri source={require('./path_to_image/image.svg')} />

How to change color of SVG image using CSS (jQuery SVG image replacement)?

The selected solution is fine if you want jQuery to process all svg elements in your DOM and your DOM is of reasonable size. But if your DOM is large and you decide to load parts of your DOM dynamically, it really makes no sense to have to rescan the entire DOM just to update svg elements. Instead, use a jQuery plugin to do this:

/**
 * A jQuery plugin that loads an svg file and replaces the jQuery object with its contents.
 *
 * The path to the svg file is specified in the src attribute (which normally does not exist for an svg element).
 *
 * The width, height and class attributes in the loaded svg will be replaced by those that exist in the jQuery object's
 * underlying html. Note: All other attributes in the original element are lost including the style attribute. Place
 * any styles in a style class instead.
 */
(function ($) {
    $.fn.svgLoader = function () {
        var src = $(this).attr("src");
        var width = this.attr("width");
        var height = this.attr("height");
        var cls = this.attr("class");
        var ctx = $(this);

        // Get the svg file and replace the <svg> element.
        $.ajax({
            url: src,
            cache: false
        }).done(function (html) {
            let svg = $(html);
            svg.attr("width", width);
            svg.attr("height", height);
            svg.attr("class", cls);
            var newHtml = $('<a></a>').append(svg.clone()).html();
            ctx.replaceWith(newHtml);
        });

        return this;
    };

}(jQuery));

In your html, specify an svg element as follows:

<svg src="images/someSvgFile.svg" height="45" width="45" class="mySVGClass"/>

And apply the plugin:

$(".mySVGClass").svgLoader();

Get width/height of SVG element

FireFox have problemes for getBBox(), i need to do this in vanillaJS.

I've a better Way and is the same result as real svg.getBBox() function !

With this good post : Get the real size of a SVG/G element

var el   = document.getElementById("yourElement"); // or other selector like querySelector()
var rect = el.getBoundingClientRect(); // get the bounding rectangle

console.log( rect.width );
console.log( rect.height);

How do I center an SVG in a div?

make sure your css reads:

margin: 0 auto;

Even though you're saying you have the left and right set to auto, you may be placing an error. Of course we wouldn't know though because you did not show us any code.

How to access SVG elements with Javascript

Is it possible to do it this way, as opposed to using something like Raphael or jQuery SVG?

Definitely.

If it is possible, what's the technique?

This annotated code snippet works:

<!DOCTYPE html>
<html>
    <head>
        <title>SVG Illustrator Test</title> 
    </head>
    <body>

        <object data="alpha.svg" type="image/svg+xml"
         id="alphasvg" width="100%" height="100%"></object>

        <script>
            var a = document.getElementById("alphasvg");

            // It's important to add an load event listener to the object,
            // as it will load the svg doc asynchronously
            a.addEventListener("load",function(){

                // get the inner DOM of alpha.svg
                var svgDoc = a.contentDocument;
                // get the inner element by id
                var delta = svgDoc.getElementById("delta");
                // add behaviour
                delta.addEventListener("mousedown",function(){
                        alert('hello world!')
                }, false);
            }, false);
        </script>
    </body>
</html>

Note that a limitation of this technique is that it is restricted by the same-origin policy, so alpha.svg must be hosted on the same domain as the .html file, otherwise the inner DOM of the object will be inaccessible.

Important thing to run this HTML, you need host HTML file to web server like IIS, Tomcat

Auto line-wrapping in SVG text

Here's an alternative:

<svg ...>
  <switch>
    <g requiredFeatures="http://www.w3.org/Graphics/SVG/feature/1.2/#TextFlow">
      <textArea width="200" height="auto">
       Text goes here
      </textArea>
    </g>
    <foreignObject width="200" height="200" 
     requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
      <p xmlns="http://www.w3.org/1999/xhtml">Text goes here</p>
    </foreignObject>
    <text x="20" y="20">No automatic linewrapping.</text>
  </switch>
</svg>

Noting that even though foreignObject may be reported as being supported with that featurestring, there's no guarantee that HTML can be displayed because that's not required by the SVG 1.1 specification. There is no featurestring for html-in-foreignobject support at the moment. However, it is still supported in many browsers, so it's likely to become required in the future, perhaps with a corresponding featurestring.

Note that the 'textArea' element in SVG Tiny 1.2 supports all the standard svg features, e.g advanced filling etc, and that you can specify either of width or height as auto, meaning that the text can flow freely in that direction. ForeignObject acts as clipping viewport.

Note: while the above example is valid SVG 1.1 content, in SVG 2 the 'requiredFeatures' attribute has been removed, which means the 'switch' element will try to render the first 'g' element regardless of having support for SVG 1.2 'textArea' elements. See SVG2 switch element spec.

Convert SVG image to PNG with PHP

You can use Raphaël—JavaScript Library and achieve it easily. It will work in IE also.

What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG?

If you opt for JPEG, and you're dealing with images for a website, you may want to consider the Google Guetzli perceptual encoder, which is freely available. In my experience, for a fixed quality Guetzli produces smaller files than standard JPEG encoding libraries, while maintaining full compatibility with the JPEG standard (so your images will have the same compatibility as common JPEG images).

The only drawback is that Guetzli takes lot of time to encode.. but this is done only once, when you prepare the image for the website, while the benefits remains forever! Smaller images will take less time to download, so your website speed will increase in the everyday use.

SVG fill color transparency / alpha?

You use an addtional attribute; fill-opacity: This attribute takes a decimal number between 0.0 and 1.0, inclusive; where 0.0 is completely transparent.

For example:

<rect ... fill="#044B94" fill-opacity="0.4"/>

Additionally you have the following:

  • stroke-opacity attribute for the stroke
  • opacity for the entire object

jQuery SVG vs. Raphael

I prefer using RaphaelJS because it has great cross-browser abilities. However, some SVG & VML effects can't be achieved with RaphaelJS (complex gradients...).

Google has also developped a library of its own to enable SVG support in IE: http://svgweb.googlecode.com/files/svgweb-2009-08-20-B.zip

How to use SVG markers in Google Maps API v3

OK! I done this soon in my web,I try two ways to create the custom google map marker, this run code use canvg.js is the best compatibility for browser.the Commented-Out Code is not support IE11 urrently.

_x000D_
_x000D_
var marker;_x000D_
var CustomShapeCoords = [16, 1.14, 21, 2.1, 25, 4.2, 28, 7.4, 30, 11.3, 30.6, 15.74, 25.85, 26.49, 21.02, 31.89, 15.92, 43.86, 10.92, 31.89, 5.9, 26.26, 1.4, 15.74, 2.1, 11.3, 4, 7.4, 7.1, 4.2, 11, 2.1, 16, 1.14];_x000D_
_x000D_
function initMap() {_x000D_
  var map = new google.maps.Map(document.getElementById('map'), {_x000D_
    zoom: 13,_x000D_
    center: {_x000D_
      lat: 59.325,_x000D_
      lng: 18.070_x000D_
    }_x000D_
  });_x000D_
  var markerOption = {_x000D_
    latitude: 59.327,_x000D_
    longitude: 18.067,_x000D_
    color: "#" + "000",_x000D_
    text: "ha"_x000D_
  };_x000D_
  marker = createMarker(markerOption);_x000D_
  marker.setMap(map);_x000D_
  marker.addListener('click', changeColorAndText);_x000D_
};_x000D_
_x000D_
function changeColorAndText() {_x000D_
  var iconTmpObj = createSvgIcon( "#c00", "ok" );_x000D_
  marker.setOptions( {_x000D_
                icon: iconTmpObj_x000D_
            } );_x000D_
};_x000D_
_x000D_
function createMarker(options) {_x000D_
  //IE MarkerShape has problem_x000D_
  var markerObj = new google.maps.Marker({_x000D_
    icon: createSvgIcon(options.color, options.text),_x000D_
    position: {_x000D_
      lat: parseFloat(options.latitude),_x000D_
      lng: parseFloat(options.longitude)_x000D_
    },_x000D_
    draggable: false,_x000D_
    visible: true,_x000D_
    zIndex: 10,_x000D_
    shape: {_x000D_
      coords: CustomShapeCoords,_x000D_
      type: 'poly'_x000D_
    }_x000D_
  });_x000D_
_x000D_
  return markerObj;_x000D_
};_x000D_
_x000D_
function createSvgIcon(color, text) {_x000D_
  var div = $("<div></div>");_x000D_
_x000D_
  var svg = $(_x000D_
    '<svg width="32px" height="43px"  viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">' +_x000D_
    '<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>' +_x000D_
    '<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>' +_x000D_
    '<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>' +_x000D_
    '</svg>'_x000D_
  );_x000D_
  div.append(svg);_x000D_
_x000D_
  var dd = $("<canvas height='50px' width='50px'></cancas>");_x000D_
_x000D_
  var svgHtml = div[0].innerHTML;_x000D_
_x000D_
  canvg(dd[0], svgHtml);_x000D_
_x000D_
  var imgSrc = dd[0].toDataURL("image/png");_x000D_
  //"scaledSize" and "optimized: false" together seems did the tricky ---IE11  &&  viewBox influent IE scaledSize_x000D_
  //var svg = '<svg width="32px" height="43px"  viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">'_x000D_
  //    + '<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>'_x000D_
  //    + '<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>'_x000D_
  //    + '<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>'_x000D_
  //    + '</svg>';_x000D_
  //var imgSrc = 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);_x000D_
_x000D_
  var iconObj = {_x000D_
    size: new google.maps.Size(32, 43),_x000D_
    url: imgSrc,_x000D_
    scaledSize: new google.maps.Size(32, 43)_x000D_
  };_x000D_
_x000D_
  return iconObj;_x000D_
};
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <title>Your Custom Marker </title>_x000D_
  <style>_x000D_
    /* Always set the map height explicitly to define the size of the div_x000D_
       * element that contains the map. */_x000D_
    #map {_x000D_
      height: 100%;_x000D_
    }_x000D_
    /* Optional: Makes the sample page fill the window. */_x000D_
    html,_x000D_
    body {_x000D_
      height: 100%;_x000D_
      margin: 0;_x000D_
      padding: 0;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="map"></div>_x000D_
    <script src="https://canvg.github.io/canvg/canvg.js"></script>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
    <script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

D3 Appending Text to a SVG Rectangle

A rect can't contain a text element. Instead transform a g element with the location of text and rectangle, then append both the rectangle and the text to it:

var bar = chart.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

http://bl.ocks.org/mbostock/7341714

Multi-line labels are also a little tricky, you might want to check out this wrap function.

Does SVG support embedding of bitmap images?

Yes, you can reference any image from the image element. And you can use data URIs to make the SVG self-contained. An example:

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">

    ...
    <image
        width="100" height="100"
        xlink:href="data:image/png;base64,IMAGE_DATA"
        />
    ...
</svg>

The svg element attribute xmlns:xlink declares xlink as a namespace prefix and says where the definition is. That then allows the SVG reader to know what xlink:href means.

The IMAGE_DATA is where you'd add the image data as base64-encoded text. Vector graphics editors that support SVG usually have an option for saving with images embedded. Otherwise there are plenty of tools around for encoding a byte stream to and from base64.

Here's a full example from the SVG testsuite.

SVG drop shadow using css3

Probably an evolution, it appears that inline css filters works nicely on elements, in a certain way.

Declaring a drop-shadow css filter, in an svg element, in both a class or inline does NOT works, as specified earlier.

But, at least in Firefox, with the following wizardry:

Appending the filter declaration inline, with javascript, after DOM load.

_x000D_
_x000D_
// Does not works, with regular dynamic css styling:

shadow0.oninput = () => {
  rect1.style.filter = "filter:drop-shadow(0 0 " + shadow0.value + "rem black);"
}

// Okay! Inline styling, appending.

shadow1.oninput = () => {
  rect1.style += " ;filter:drop-shadow(0 0 " + shadow1.value + "rem black);"
  rect2.style += " ;filter:drop-shadow(0 0 " + shadow1.value + "rem black);"
}
_x000D_
<h2>Firefox only</h2>
<h4>
Does not works! 
<input id="shadow0" type="number" min="0" max="100" step="0.1">

 | Okay!
<input id="shadow1" type="number" min="0" max="100" step="0.1">

<svg viewBox="0 0 120 70">  
    <rect id="rect1" x="10" y="10" width="100" height="50" fill="#c66" />
    
    <!-- Inline style declaration does NOT works at svg level, no shadow at loading: -->
    <rect id="rect2" x="40" y="30" width="10" height="10" fill="#aaa" style="filter:drop-shadow(0 0 20rem black)" />
    
</svg>
_x000D_
_x000D_
_x000D_

enter image description here

Add custom icons to font awesome

In Font Awesome 5, you can create custom icons with your own SVG data. Here's a demo GitHub repo that you can play with. And here's a CodePen that shows how something similar might be done in <script> blocks.

In either case, it simply involves using library.add() to add an object like this:

export const faSomeObjectName = {
  // Use a prefix like 'fac' that doesn't conflict with a prefix in the standard Font Awesome styles
  // (So avoid fab, fal, fas, far, fa)
  prefix: string,
  iconName: string, // Any name you like
  icon: [
    number, // width
    number, // height
    string[], // ligatures
    string, // unicode (if relevant)
    string // svg path data
  ]
}

Note that the element labelled by the comment "svg path data" in the code sample is what will be assigned as the value of the d attribute on a <path> element that is a child of the <svg>. Like this (leaving out some details for clarity):

<svg>
  <path d=SVG_PATH_DATA></path>
</svg>

(Adapted from my similar answer here: https://stackoverflow.com/a/50338775/4642871)

Right mime type for SVG images with fonts embedded

There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml mediatype.

SVG rounded corner

As referenced in my answer to Applying rounded corners to paths/polygons, I have written a routine in javascript for generically rounding corners of SVG paths, with examples, here: http://plnkr.co/edit/kGnGGyoOCKil02k04snu.

It will work independently from any stroke effects you may have. To use, include the rounding.js file from the Plnkr and call the function like so:

roundPathCorners(pathString, radius, useFractionalRadius)

The result will be the rounded path.

The results look like this:

SVG Path Rounding Examples

SVG gradient using CSS

2019 Answer

With brand new css properties you can have even more flexibility with variables aka custom properties

_x000D_
_x000D_
.shape {
  width:500px;
  height:200px;
}

.shape .gradient-bg {
  fill: url(#header-shape-gradient) #fff;
}

#header-shape-gradient {
  --color-stop: #f12c06;
  --color-bot: #faed34;
}
_x000D_
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" class="shape">
  <defs>
    <linearGradient id="header-shape-gradient" x2="0.35" y2="1">
        <stop offset="0%" stop-color="var(--color-stop)" />
        <stop offset="30%" stop-color="var(--color-stop)" />
        <stop offset="100%" stop-color="var(--color-bot)" />
      </linearGradient>
  </defs>
  <g>
    <polygon class="gradient-bg" points="0,0 100,0 0,66" />
  </g>
</svg>
_x000D_
_x000D_
_x000D_

Just set a named variable for each stop in gradient and then customize as you like in css. You can even change their values dynamically with javascript, like:

document.querySelector('#header-shape-gradient').style.setProperty('--color-stop', "#f5f7f9");

Modify SVG fill color when being served as Background-Image

for monochrome background you could use a svg with a mask, where the background color should be displayed

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" preserveAspectRatio="xMidYMid meet" focusable="false" style="pointer-events: none; display: block; width: 100%; height: 100%;" >
    <defs>
        <mask id="Mask">
            <rect width="100%" height="100%" fill="#fff" />
            <polyline stroke-width="2.5" stroke="black" stroke-linecap="square" fill="none" transform="translate(10.373882, 8.762969) rotate(-315.000000) translate(-10.373882, -8.762969) " points="7.99893906 13.9878427 12.7488243 13.9878427 12.7488243 3.53809523"></polyline>
        </mask>
    </defs>
    <rect x="0" y="0" width="20" height="20" fill="white" mask="url(#Mask)" />
</svg>

and than use this css

background-repeat: no-repeat;
background-position: center center;
background-size: contain;
background-image: url(your/path/to.svg);
background-color: var(--color);

Creating SVG graphics using Javascript?

There's a jQuery plugin that allows you to manipulate SVG via Javascript:

http://plugins.jquery.com/project/svg

From its intro:

Supported natively in Firefox, Opera, and Safari and via the Adobe SVG viewer or Renesis player in IE, SVG lets you display graphics within your Web pages. Now you can easily drive the SVG canvas from your JavaScript code.

WPF What is the correct way of using SVG files as icons in WPF

Your technique will depend on what XAML object your SVG to XAML converter produces. Does it produce a Drawing? An Image? A Grid? A Canvas? A Path? A Geometry? In each case your technique will be different.

In the examples below I will assume you are using your icon on a button, which is the most common scenario, but note that the same techniques will work for any ContentControl.

Using a Drawing as an icon

To use a Drawing, paint an approriately-sized rectangle with a DrawingBrush:

<Button>
  <Rectangle Width="100" Height="100">
    <Rectangle.Fill>
      <DrawingBrush>
        <DrawingBrush.Drawing>

          <Drawing ... /> <!-- Converted from SVG -->

        </DrawingBrush.Drawing>
      </DrawingBrush>
    </Rectangle.Fill>
  </Rectangle>
</Button>

Using an Image as an icon

An image can be used directly:

<Button>
  <Image ... />  <!-- Converted from SVG -->
</Button>

Using a Grid as an icon

A grid can be used directly:

<Button>
  <Grid ... />  <!-- Converted from SVG -->
</Button>

Or you can include it in a Viewbox if you need to control the size:

<Button>
  <Viewbox ...>
    <Grid ... />  <!-- Converted from SVG -->
  </Viewbox>
</Button>

Using a Canvas as an icon

This is like using an image or grid, but since a canvas has no fixed size you need to specify the height and width (unless these are already set by the SVG converter):

<Button>
  <Canvas Height="100" Width="100">  <!-- Converted from SVG, with additions -->
  </Canvas>
</Button>

Using a Path as an icon

You can use a Path, but you must set the stroke or fill explicitly:

<Button>
  <Path Stroke="Red" Data="..." /> <!-- Converted from SVG, with additions -->
</Button>

or

<Button>
  <Path Fill="Blue" Data="..." /> <!-- Converted from SVG, with additions -->
</Button>

Using a Geometry as an icon

You can use a Path to draw your geometry. If it should be stroked, set the Stroke:

<Button>
  <Path Stroke="Red" Width="100" Height="100">
    <Path.Data>
      <Geometry ... /> <!-- Converted from SVG -->
    </Path.Data>
  </Path>
</Button>

or if it should be filled, set the Fill:

<Button>
  <Path Fill="Blue" Width="100" Height="100">
    <Path.Data>
      <Geometry ... /> <!-- Converted from SVG -->
    </Path.Data>
  </Path>
</Button>

How to data bind

If you're doing the SVG -> XAML conversion in code and want the resulting XAML to appear using data binding, use one of the following:

Binding a Drawing:

<Button>
  <Rectangle Width="100" Height="100">
    <Rectangle.Fill>
      <DrawingBrush Drawing="{Binding Drawing, Source={StaticResource ...}}" />
    </Rectangle.Fill>
  </Rectangle>
</Button>

Binding an Image:

<Button Content="{Binding Image}" />

Binding a Grid:

<Button Content="{Binding Grid}" />

Binding a Grid in a Viewbox:

<Button>
  <Viewbox ...>
    <ContentPresenter Content="{Binding Grid}" />
  </Viewbox>
</Button>

Binding a Canvas:

<Button>
  <ContentPresenter Height="100" Width="100" Content="{Binding Canvas}" />
</Button>

Binding a Path:

<Button Content="{Binding Path}" />  <!-- Fill or stroke must be set in code unless set by the SVG converter -->

Binding a Geometry:

<Button>
  <Path Width="100" Height="100" Data="{Binding Geometry}" />
</Button>

How can I make an svg scale with its parent container?

To specify the coordinates within the SVG image independently of the scaled size of the image, use the viewBox attribute on the SVG element to define what the bounding box of the image is in the coordinate system of the image, and use the width and height attributes to define what the width or height are with respect to the containing page.

For instance, if you have the following:

<svg>
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

It will render as a 10px by 20px triangle:

10x20 triangle

Now, if you set only the width and height, that will change the size of the SVG element, but not scale the triangle:

<svg width=100 height=50>
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

10x20 triangle

If you set the view box, that causes it to transform the image such that the given box (in the coordinate system of the image) is scaled up to fit within the given width and height (in the coordinate system of the page). For instance, to scale up the triangle to be 100px by 50px:

<svg width=100 height=50 viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

100x50 triangle

If you want to scale it up to the width of the HTML viewport:

<svg width="100%" viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

300x150 triangle

Note that by default, the aspect ratio is preserved. So if you specify that the element should have a width of 100%, but a height of 50px, it will actually only scale up to the height of 50px (unless you have a very narrow window):

<svg width="100%" height="50px" viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

100x50 triangle

If you actually want it to stretch horizontally, disable aspect ratio preservation with preserveAspectRatio=none:

<svg width="100%" height="50px" viewBox="0 0 20 10" preserveAspectRatio="none">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

300x50 triangle

(note that while in my examples I use syntax that works for HTML embedding, to include the examples as an image in StackOverflow I am instead embedding within another SVG, so I need to use valid XML syntax)

Embedding SVG into ReactJS

You can import svg and it use it like a image

import chatSVG from '../assets/images/undraw_typing_jie3.svg'

And ise it in img tag

<img src={chatSVG} className='iconChat' alt="Icon chat"/>

How to add an image to an svg container using D3.js

nodeEnter.append("svg:image")
.attr('x', -9)
.attr('y', -12)
.attr('width', 20)
.attr('height', 24)
.attr("xlink:href", "resources/images/check.png")

Background color of text in SVG

The previous answers relied on doubling up text and lacked sufficient whitespace.

By using atop and &nbsp; I was able to get the results I wanted.

This example also includes arrows, a common use case for SVG text labels:

<svg viewBox="-105 -40 210 234">
<title>Size Guide</title>
<defs>
    <filter x="0" y="0" width="1" height="1" id="solid">
        <feFlood flood-color="white"></feFlood>
        <feComposite in="SourceGraphic" operator="atop"></feComposite>
    </filter>
    <marker id="arrow" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
        <path d="M 0 0 L 10 5 L 0 10 z"></path>
    </marker>
</defs>
<g id="garment">
    <path id="right-body" fill="none" stroke="black" stroke-width="1" stroke-linejoin="round" d="M0 0 l30 0 l0 154 l-30 0"></path>
    <path id="right-sleeve" d="M30 0 l35 0 l0 120 l-35 0" fill="none" stroke-linejoin="round" stroke="black" stroke-width="1"></path>
    <use id="left-body" href="#right-body" transform="scale(-1,1)"></use>
    <use id="left-sleeve" href="#right-sleeve" transform="scale(-1,1)"></use>
    <path id="collar-right-top" fill="none" stroke="black" stroke-width="1" stroke-linejoin="round" d="M0 -6.5 l11.75 0 l6.5 6.5"></path>
    <use id="collar-left-top" href="#collar-right-top" transform="scale(-1,1)"></use>
    <path id="collar-left" fill="white" stroke="black" stroke-width="1" stroke-linejoin="round" d="M-11.75 -6.5 l-6.5 6.5 l30 77 l6.5 -6.5 Z"></path>
    <path id="front-right" fill="white" stroke="black" stroke-width="1" d="M18.25 0 L30 0 l0 154 l-41.75 0 l0 -77 Z"></path>
    <line x1="0" y1="0" x2="0" y2="154" stroke="black" stroke-width="1" stroke-dasharray="1 3"></line>
    <use id="collar-right" href="#collar-left" transform="scale(-1,1)"></use>
</g>
<g id="dimension-labels">
    <g id="dimension-sleeve-length">
        <line marker-start="url(#arrow)" marker-end="url(#arrow)" x1="85" y1="0" x2="85" y2="120" stroke="black" stroke-width="1"></line>
        <text font-size="10" filter="url(#solid)" fill="black" x="85" y="60" class="dimension" text-anchor="middle" dominant-baseline="middle"> 120 cm</text>
    </g>
    <g id="dimension-length">
        <line marker-start="url(#arrow)" marker-end="url(#arrow)" x1="-85" y1="0" x2="-85" y2="154" stroke="black" stroke-width="1"></line>
        <text font-size="10" filter="url(#solid)" fill="black" x="-85" y="77" text-anchor="middle" dominant-baseline="middle" class="dimension"> 154 cm</text>
    </g>
    <g id="dimension-sleeve-to-sleeve">
        <line marker-start="url(#arrow)" marker-end="url(#arrow)" x1="-65" y1="-20" x2="65" y2="-20" stroke="black" stroke-width="1"></line>
        <text font-size="10" filter="url(#solid)" fill="black" x="0" y="-20" text-anchor="middle" dominant-baseline="middle" class="dimension">&nbsp;130 cm&nbsp;</text>
    </g>
    <g title="Back Width" id="dimension-back-width">
        <line marker-start="url(#arrow)" marker-end="url(#arrow)" x1="-30" y1="174" x2="30" y2="174" stroke="black" stroke-width="1"></line>
        <text font-size="10" filter="url(#solid)" fill="black" x="0" y="174" text-anchor="middle" dominant-baseline="middle" class="dimension">&nbsp;60 cm&nbsp;</text>
    </g>
</g>
</svg>

SVG Positioning

Everything in the g element is positioned relative to the current transform matrix.

To move the content, just put the transformation in the g element:

<g transform="translate(20,2.5) rotate(10)">
    <rect x="0" y="0" width="60" height="10"/>
</g>

Links: Example from the SVG 1.1 spec

How can I remove or replace SVG content?

Here is the solution:

d3.select("svg").remove();

This is a remove function provided by D3.js.

Convert SVG to image (JPEG, PNG, etc.) in the browser

I wrote this ES6 Class which does the Job.

class SvgToPngConverter {
  constructor() {
    this._init = this._init.bind(this);
    this._cleanUp = this._cleanUp.bind(this);
    this.convertFromInput = this.convertFromInput.bind(this);
  }

  _init() {
    this.canvas = document.createElement("canvas");
    this.imgPreview = document.createElement("img");
    this.imgPreview.style = "position: absolute; top: -9999px";

    document.body.appendChild(this.imgPreview);
    this.canvasCtx = this.canvas.getContext("2d");
  }

  _cleanUp() {
    document.body.removeChild(this.imgPreview);
  }

  convertFromInput(input, callback) {
    this._init();
    let _this = this;
    this.imgPreview.onload = function() {
      const img = new Image();
      _this.canvas.width = _this.imgPreview.clientWidth;
      _this.canvas.height = _this.imgPreview.clientHeight;
      img.crossOrigin = "anonymous";
      img.src = _this.imgPreview.src;
      img.onload = function() {
        _this.canvasCtx.drawImage(img, 0, 0);
        let imgData = _this.canvas.toDataURL("image/png");
        if(typeof callback == "function"){
            callback(imgData)
        }
        _this._cleanUp();
      };
    };

    this.imgPreview.src = input;
  }
}

Here is how you use it

let input = "https://restcountries.eu/data/afg.svg"
new SvgToPngConverter().convertFromInput(input, function(imgData){
    // You now have your png data in base64 (imgData). 
    // Do what ever you wish with it here.
});

If you want a vanilla JavaScript version, you could head over to Babel website and transpile the code there.

How to style SVG with external CSS?

A very quick solution to have dynamic style with an external css stylesheet, in case you are using the <object> tag to embed your svg.

This example will add a class to the root <svg> tag on click on a parent element.

file.svg :

<?xml-stylesheet type="text/css" href="../svg.css"?>
 <svg xmlns="http://www.w3.org/2000/svg" viewBox="">
  <g>
   <path/>
  </g>
 </svg>

html :

<a class="parent">
  <object data="file.svg"></object>
</a>

Jquery :

$(function() {
  $(document).on('click', '.parent', function(){
    $(this).find('object').contents().find('svg').attr("class","selected");
  }
});

on click parent element :

 <svg xmlns="http://www.w3.org/2000/svg" viewBox="" class="selected">

then you can manage your css

svg.css :

path {
 fill:none;
 stroke:#000;
 stroke-miterlimit:1.41;
 stroke-width:0.7px;
}

.selected path {
 fill:none;
 stroke:rgb(64, 136, 209);
 stroke-miterlimit:1.41;
 stroke-width:0.7px;
}

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

_x000D_
_x000D_
<script type="text/javascript">_x000D_
      jQuery(function($){_x000D_
        $('#map-country').cssMap({'size' : 810});_x000D_
       });_x000D_
    </script>
_x000D_
_x000D_
_x000D_

strong text

Drawing an SVG file on a HTML5 canvas

You can easily draw simple svgs onto a canvas by:

  1. Assigning the source of the svg to an image in base64 format
  2. Drawing the image onto a canvas

Note: The only drawback of the method is that it cannot draw images embedded in the svg. (see demo)

Demonstration:

(Note that the embedded image is only visible in the svg)

_x000D_
_x000D_
var svg = document.querySelector('svg');_x000D_
var img = document.querySelector('img');_x000D_
var canvas = document.querySelector('canvas');_x000D_
_x000D_
// get svg data_x000D_
var xml = new XMLSerializer().serializeToString(svg);_x000D_
_x000D_
// make it base64_x000D_
var svg64 = btoa(xml);_x000D_
var b64Start = 'data:image/svg+xml;base64,';_x000D_
_x000D_
// prepend a "header"_x000D_
var image64 = b64Start + svg64;_x000D_
_x000D_
// set it as the source of the img element_x000D_
img.src = image64;_x000D_
_x000D_
// draw the image onto the canvas_x000D_
canvas.getContext('2d').drawImage(img, 0, 0);
_x000D_
svg, img, canvas {_x000D_
  display: block;_x000D_
}
_x000D_
SVG_x000D_
_x000D_
<svg height="40">_x000D_
  <rect width="40" height="40" style="fill:rgb(255,0,255);" />_x000D_
  <image xlink:href="https://en.gravatar.com/userimage/16084558/1a38852cf33713b48da096c8dc72c338.png?size=20" height="20px" width="20px" x="10" y="10"></image>_x000D_
</svg>_x000D_
<hr/><br/>_x000D_
_x000D_
IMAGE_x000D_
<img/>_x000D_
<hr/><br/>_x000D_
   _x000D_
CANVAS_x000D_
<canvas></canvas>_x000D_
<hr/><br/>
_x000D_
_x000D_
_x000D_

Insert Multiple Rows Into Temp Table With SQL Server 2012

When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:

SQL Fiddle

MS SQL Server 2012 Schema Setup:

Query 1:

CREATE TABLE #Names
  ( 
    Name1 VARCHAR(100),
    Name2 VARCHAR(100)
  ) 

INSERT INTO #Names
  (Name1, Name2)
VALUES
  ('Matt', 'Matthew'),
  ('Matt', 'Marshal'),
  ('Matt', 'Mattison')

SELECT * FROM #NAMES

Results:

| NAME1 |    NAME2 |
--------------------
|  Matt |  Matthew |
|  Matt |  Marshal |
|  Matt | Mattison |

Here a SSMS 2012 screenshot: enter image description here

How to run multiple Python versions on Windows

The easiest way to run multiple versions of python on windows is described below as follows:-

1)Download the latest versions of python from python.org/downloads by selecting the relevant version for your system.

2)Run the installer and select Add python 3.x to the path to set path automatically in python 3 (you just have to click the checkbox). For python 2 open up your python 2 installer, select whatever preferences you want but just remember to set Add python.exe to path to Will be installed on local hard drive, Now just click next and wait for the installer to finish.

3)When both the installations are complete. Right click on my computer--Go to properties--Select advanced system settings--Go to environment variables--Click on new under System variables and add a new system variable with variable name as PY_PYTHON and set this variable value to 3. Now click on OK and you should be done.

4)Now to test this open the command prompt. Once you are in there type python or py, It should open up python3.

5)Now exit out of python3 by typing exit(). Now type py -2 it should open python 2.

If none of this works then restart the computer and if the problem still persists then uninstall everything and repeat the steps.

Thanks.

convert string to number node.js

Using parseInt() is a bad idea mainly because it never fails. Also because some results can be unexpected, like in the case of INFINITY.
Below is the function for handling unexpected behaviour.

function cleanInt(x) {
    x = Number(x);
    return x >= 0 ? Math.floor(x) : Math.ceil(x);
}

See results of below test cases.

console.log("CleanInt: ", cleanInt('xyz'), " ParseInt: ", parseInt('xyz'));
console.log("CleanInt: ", cleanInt('123abc'), " ParseInt: ", parseInt('123abc'));
console.log("CleanInt: ", cleanInt('234'), " ParseInt: ", parseInt('234'));
console.log("CleanInt: ", cleanInt('-679'), " ParseInt: ", parseInt('-679'));
console.log("CleanInt: ", cleanInt('897.0998'), " ParseInt: ", parseInt('897.0998'));
console.log("CleanInt: ", cleanInt('Infinity'), " ParseInt: ", parseInt('Infinity'));

result:

CleanInt:  NaN  ParseInt:  NaN
CleanInt:  NaN  ParseInt:  123
CleanInt:  234  ParseInt:  234
CleanInt:  -679  ParseInt:  -679
CleanInt:  897  ParseInt:  897
CleanInt:  Infinity  ParseInt:  NaN

Where can I find Android's default icons?

you can use

android.R.drawable.xxx

(use autocomplete to see whats in there)

Or download the stuff from http://developer.android.com/design/downloads/index.html

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

I had the same issue to connect to local system.

I checked in the services list (Run->Services.msc->Enter) wampmysqld64 was stopped.

Restarted it. and was able to login.

Why and when to use angular.copy? (Deep Copy)

In that case, you don't need to use angular.copy()

Explanation :

  • = represents a reference whereas angular.copy() creates a new object as a deep copy.

  • Using = would mean that changing a property of response.data would change the corresponding property of $scope.example or vice versa.

  • Using angular.copy() the two objects would remain seperate and changes would not reflect on each other.

Determining image file size + dimensions via Javascript?

Service workers have access to header informations, including the Content-Length header.

Service workers are a bit complicated to understand, so I've built a small library called sw-get-headers.

Than you need to:

  1. subscribe to the library's response event
  2. identify the image's url among all the network requests
  3. here you go, you can read the Content-Length header!

Note that your website needs to be on HTTPS to use Service Workers, the browser needs to be compatible with Service Workers and the images must be on the same origin as your page.

Disable copy constructor

If you don't mind multiple inheritance (it is not that bad, after all), you may write simple class with private copy constructor and assignment operator and additionally subclass it:

class NonAssignable {
private:
    NonAssignable(NonAssignable const&);
    NonAssignable& operator=(NonAssignable const&);
public:
    NonAssignable() {}
};

class SymbolIndexer: public Indexer, public NonAssignable {
};

For GCC this gives the following error message:

test.h: In copy constructor ‘SymbolIndexer::SymbolIndexer(const SymbolIndexer&)’:
test.h: error: ‘NonAssignable::NonAssignable(const NonAssignable&)’ is private

I'm not very sure for this to work in every compiler, though. There is a related question, but with no answer yet.

UPD:

In C++11 you may also write NonAssignable class as follows:

class NonAssignable {
public:
    NonAssignable(NonAssignable const&) = delete;
    NonAssignable& operator=(NonAssignable const&) = delete;
    NonAssignable() {}
};

The delete keyword prevents members from being default-constructed, so they cannot be used further in a derived class's default-constructed members. Trying to assign gives the following error in GCC:

test.cpp: error: use of deleted function
          ‘SymbolIndexer& SymbolIndexer::operator=(const SymbolIndexer&)’
test.cpp: note: ‘SymbolIndexer& SymbolIndexer::operator=(const SymbolIndexer&)’
          is implicitly deleted because the default definition would
          be ill-formed:

UPD:

Boost already has a class just for the same purpose, I guess it's even implemented in similar way. The class is called boost::noncopyable and is meant to be used as in the following:

#include <boost/core/noncopyable.hpp>

class SymbolIndexer: public Indexer, private boost::noncopyable {
};

I'd recommend sticking to the Boost's solution if your project policy allows it. See also another boost::noncopyable-related question for more information.

Android: adb pull file on desktop

Use a fully-qualified path to the desktop (e.g., /home/mmurphy/Desktop).

Example: adb pull sdcard/log.txt /home/mmurphy/Desktop

SOAP request to WebService with java

I have come across other similar question here. Both of above answers are perfect, but here trying to add additional information for someone looking for SOAP1.1, and not SOAP1.2.

Just change one line code provided by @acdcjunior, use SOAPMessageFactory1_1Impl implementation, it will change namespace to xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/", which is SOAP1.1 implementation.

Change callSoapWebService method first line to following.

SOAPMessage soapMessage = SOAPMessageFactory1_1Impl.newInstance().createMessage();

I hope it will be helpful to others.

react-native - Fit Image in containing View, not the whole screen size

Anyone over here who wants his image to fit in full screen without any crop (in both portrait and landscape mode), use this:

image: {
    flex: 1,
    width: '100%',
    height: '100%',
    resizeMode: 'contain',
},

How to put text over images in html?

You need to use absolutely-positioned CSS over a relatively-positioned img tag. The article Text Blocks Over Image gives a step-by-step example for placing text over an image.

jQuery UI Dialog with ASP.NET button postback

I didn't want to have to work around this problem for every dialog in my project, so I created a simple jQuery plugin. This plugin is merely for opening new dialogs and placing them within the ASP.NET form:

(function($) {
    /**
     * This is a simple jQuery plugin that works with the jQuery UI
     * dialog. This plugin makes the jQuery UI dialog append to the
     * first form on the page (i.e. the asp.net form) so that
     * forms in the dialog will post back to the server.
     *
     * This plugin is merely used to open dialogs. Use the normal
     * $.fn.dialog() function to close dialogs programatically.
     */
    $.fn.aspdialog = function() {
        if (typeof $.fn.dialog !== "function")
            return;

        var dlg = {};

        if ( (arguments.length == 0)
                || (arguments[0] instanceof String) ) {
            // If we just want to open it without any options
            // we do it this way.
            dlg = this.dialog({ "autoOpen": false });
            dlg.parent().appendTo('form:first');
            dlg.dialog('open');
        }
        else {
            var options = arguments[0];
            options.autoOpen = false;
            options.bgiframe = true;

            dlg = this.dialog(options);
            dlg.parent().appendTo('form:first');
            dlg.dialog('open');
        }
    };
})(jQuery);</code></pre>

So to use the plugin, you first load jQuery UI and then the plugin. Then you can do something like the following:

$('#myDialog1').aspdialog(); // Simple
$('#myDialog2').aspdialog('open'); // The same thing
$('#myDialog3').aspdialog({title: "My Dialog", width: 320, height: 240}); // With options!

To be clear, this plugin assumes you are ready to show the dialog when you call it.

Remove specific characters from a string in Javascript

if it is not the first two chars and you wanna remove F0 from the whole string then you gotta use this regex

_x000D_
_x000D_
   let string = 'F0123F0456F0';_x000D_
   let result = string.replace(/F0/ig, '');_x000D_
   console.log(result);
_x000D_
_x000D_
_x000D_

How to modify the nodejs request default timeout time?

Linking to express issue #3330

You may set the timeout either globally for entire server:

var server = app.listen();
server.setTimeout(500000);

or just for specific route:

app.post('/xxx', function (req, res) {
   req.setTimeout(500000);
});

In git, what is the difference between merge --squash and rebase?

Merge commits: retains all of the commits in your branch and interleaves them with commits on the base branchenter image description here

Merge Squash: retains the changes but omits the individual commits from history enter image description here

Rebase: This moves the entire feature branch to begin on the tip of the master branch, effectively incorporating all of the new commits in master

enter image description here

More on here

Add new element to an existing object

You can use Extend to add new objects to an existing one.

HTTP Status 405 - Method Not Allowed Error for Rest API

You might be doing a PUT call for GET operation Please check once

What is the "realm" in basic authentication

A realm can be seen as an area (not a particular page, it could be a group of pages) for which the credentials are used; this is also the string that will be shown when the browser pops up the login window, e.g.

Please enter your username and password for <realm name>:

When the realm changes, the browser may show another popup window if it doesn't have credentials for that particular realm.

How to retrieve JSON Data Array from ExtJS Store

A better (IMO) one-line approach, works on ExtJS 4, not sure about 3:

store.proxy.reader.jsonData

Run script with rc.local: script works, but not at boot

I got my script to work by editing /etc/rc.local then issuing the following 3 commands.

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults

Now the script works at boot.

Replace Line Breaks in a String C#

I would use Environment.Newline when I wanted to insert a newline for a string, but not to remove all newlines from a string.

Depending on your platform you can have different types of newlines, but even inside the same platform often different types of newlines are used. In particular when dealing with file formats and protocols.

string ReplaceNewlines(string blockOfText, string replaceWith)
{
    return blockOfText.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
}

jQuery disable/enable submit button

Vanilla JS Solution. It works for a whole form not only one input.

In question selected JavaScript tag.

HTML Form:

_x000D_
_x000D_
var form = document.querySelector('form')_x000D_
    var inputs = form.querySelectorAll('input')_x000D_
    var required_inputs = form.querySelectorAll('input[required]')_x000D_
    var register = document.querySelector('input[type="submit"]')_x000D_
    form.addEventListener('keyup', function(e) {_x000D_
        var disabled = false_x000D_
        inputs.forEach(function(input, index) {_x000D_
            if (input.value === '' || !input.value.replace(/\s/g, '').length) {_x000D_
                disabled = true_x000D_
            }_x000D_
        })_x000D_
        if (disabled) {_x000D_
            register.setAttribute('disabled', 'disabled')_x000D_
        } else {_x000D_
            register.removeAttribute('disabled')_x000D_
        }_x000D_
    })
_x000D_
<form action="/signup">_x000D_
        <div>_x000D_
            <label for="username">User Name</label>_x000D_
            <input type="text" name="username" required/>_x000D_
        </div>_x000D_
        <div>_x000D_
            <label for="password">Password</label>_x000D_
            <input type="password" name="password" />_x000D_
        </div>_x000D_
        <div>_x000D_
            <label for="r_password">Retype Password</label>_x000D_
            <input type="password" name="r_password" />_x000D_
        </div>_x000D_
        <div>_x000D_
            <label for="email">Email</label>_x000D_
            <input type="text" name="email" />_x000D_
        </div>_x000D_
        <input type="submit" value="Signup" disabled="disabled" />_x000D_
    </form>
_x000D_
_x000D_
_x000D_

Some explanation:

In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.

If you need to disable submit button until all required input fields are filled in - replace:

inputs.forEach(function(input, index) {

with:

required_inputs.forEach(function(input, index) {

where required_inputs is already declared array containing only required input fields.

Scaling an image to fit on canvas

Provide the source image (img) size as the first rectangle:

ctx.drawImage(img, 0, 0, img.width,    img.height,     // source rectangle
                   0, 0, canvas.width, canvas.height); // destination rectangle

The second rectangle will be the destination size (what source rectangle will be scaled to).

Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas

Powershell v3 Invoke-WebRequest HTTPS error

This work-around worked for me: http://connect.microsoft.com/PowerShell/feedback/details/419466/new-webserviceproxy-needs-force-parameter-to-ignore-ssl-errors

Basically, in your PowerShell script:

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

$result = Invoke-WebRequest -Uri "https://IpAddress/resource"

test if event handler is bound to an element in jQuery

I don't think that the hasEventListener plugin mentioned will handle custom events e.g.

var obj = {id:'test'};
$(obj).bind('custom', function(){
    alert('custom');
}).trigger('custom');

alert($(obj).hasEventListener('custom'));

Also, at least in jQuery 1.5 I think you need to be careful using $(target).data('events') because it returns differently for events that have been bound to objects as above.

You need to do something like:

var events = $(target).data("events");
if(typeof events === "function"){
   events = events.events;
}

I am using this sort of approach and it works but it feels a bit like I am at the mercy of jquery internals and that really I shouldn't be doing it!

Date in to UTC format Java

Try to format your date with the Z or z timezone flags:

new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a Z").format(dateObj);

Plot a bar using matplotlib using a dictionary

It's a little simpler than most answers here suggest:

import matplotlib.pyplot as plt

D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(*zip(*D.items()))
plt.show()

enter image description here

How to use FormData in react-native?

This worked for me

var serializeJSON = function(data) {
  return Object.keys(data).map(function (keyName) {
    return encodeURIComponent(keyName) + '=' + encodeURIComponent(data[keyName])
  }).join('&');
}

var response = fetch(url, {
  method: 'POST',
  body: serializeJSON({
    haha: 'input'
  })
});

How to implement endless list with RecyclerView?

My answer is a modified version of Noor. I passed from a ListView where i had EndlessScrollListener (that you can find easily in many answers on SO) to a RecyclerView so i wanted a EndlessRecyclScrollListener to easily update my past listener.

So here is the code, hope it helps:

public abstract class EndlessScrollRecyclListener extends RecyclerView.OnScrollListener
{
    // The total number of items in the dataset after the last load
    private int previousTotalItemCount = 0;
    private boolean loading = true;
    private int visibleThreshold = 5;
    int firstVisibleItem, visibleItemCount, totalItemCount;
    private int startingPageIndex = 0;
    private int currentPage = 0;

    @Override
    public void onScrolled(RecyclerView mRecyclerView, int dx, int dy)
    {
        super.onScrolled(mRecyclerView, dx, dy);
        LinearLayoutManager mLayoutManager = (LinearLayoutManager) mRecyclerView
                .getLayoutManager();

        visibleItemCount = mRecyclerView.getChildCount();
        totalItemCount = mLayoutManager.getItemCount();
        firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
        onScroll(firstVisibleItem, visibleItemCount, totalItemCount);
    }

    public void onScroll(int firstVisibleItem, int visibleItemCount, int totalItemCount)
    {
        // If the total item count is zero and the previous isn't, assume the
        // list is invalidated and should be reset back to initial state
        if (totalItemCount < previousTotalItemCount)
        {
            this.currentPage = this.startingPageIndex;
            this.previousTotalItemCount = totalItemCount;
            if (totalItemCount == 0)
            {
                this.loading = true;
            }
        }
        // If it’s still loading, we check to see if the dataset count has
        // changed, if so we conclude it has finished loading and update the current page
        // number and total item count.
        if (loading && (totalItemCount > previousTotalItemCount))
        {
            loading = false;
            previousTotalItemCount = totalItemCount;
            currentPage++;
        }

        // If it isn’t currently loading, we check to see if we have breached
        // the visibleThreshold and need to reload more data.
        // If we do need to reload some more data, we execute onLoadMore to fetch the data.
        if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem +
                visibleThreshold))
        {
            onLoadMore(currentPage + 1, totalItemCount);
            loading = true;
        }
    }

    // Defines the process for actually loading more data based on page
    public abstract void onLoadMore(int page, int totalItemsCount);

}

How do I download code using SVN/Tortoise from Google Code?

After you install Tortoise (separate SVN client not required), create a new empty folder for the project somewhere and right click it in Windows. There should be an option for SVN Checkout. Choosing that option will open a dialog box. Paste the URL you posted above in the first textbox of that dialog box and click "OK".

What exactly is std::atomic?

Each instantiation and full specialization of std::atomic<> represents a type that different threads can simultaneously operate on (their instances), without raising undefined behavior:

Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.

In addition, accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses as specified by std::memory_order.

std::atomic<> wraps operations that, in pre-C++ 11 times, had to be performed using (for example) interlocked functions with MSVC or atomic bultins in case of GCC.

Also, std::atomic<> gives you more control by allowing various memory orders that specify synchronization and ordering constraints. If you want to read more about C++ 11 atomics and memory model, these links may be useful:

Note that, for typical use cases, you would probably use overloaded arithmetic operators or another set of them:

std::atomic<long> value(0);
value++; //This is an atomic op
value += 5; //And so is this

Because operator syntax does not allow you to specify the memory order, these operations will be performed with std::memory_order_seq_cst, as this is the default order for all atomic operations in C++ 11. It guarantees sequential consistency (total global ordering) between all atomic operations.

In some cases, however, this may not be required (and nothing comes for free), so you may want to use more explicit form:

std::atomic<long> value {0};
value.fetch_add(1, std::memory_order_relaxed); // Atomic, but there are no synchronization or ordering constraints
value.fetch_add(5, std::memory_order_release); // Atomic, performs 'release' operation

Now, your example:

a = a + 12;

will not evaluate to a single atomic op: it will result in a.load() (which is atomic itself), then addition between this value and 12 and a.store() (also atomic) of final result. As I noted earlier, std::memory_order_seq_cst will be used here.

However, if you write a += 12, it will be an atomic operation (as I noted before) and is roughly equivalent to a.fetch_add(12, std::memory_order_seq_cst).

As for your comment:

A regular int has atomic loads and stores. Whats the point of wrapping it with atomic<>?

Your statement is only true for architectures that provide such guarantee of atomicity for stores and/or loads. There are architectures that do not do this. Also, it is usually required that operations must be performed on word-/dword-aligned address to be atomic std::atomic<> is something that is guaranteed to be atomic on every platform, without additional requirements. Moreover, it allows you to write code like this:

void* sharedData = nullptr;
std::atomic<int> ready_flag = 0;

// Thread 1
void produce()
{
    sharedData = generateData();
    ready_flag.store(1, std::memory_order_release);
}

// Thread 2
void consume()
{
    while (ready_flag.load(std::memory_order_acquire) == 0)
    {
        std::this_thread::yield();
    }

    assert(sharedData != nullptr); // will never trigger
    processData(sharedData);
}

Note that assertion condition will always be true (and thus, will never trigger), so you can always be sure that data is ready after while loop exits. That is because:

  • store() to the flag is performed after sharedData is set (we assume that generateData() always returns something useful, in particular, never returns NULL) and uses std::memory_order_release order:

memory_order_release

A store operation with this memory order performs the release operation: no reads or writes in the current thread can be reordered after this store. All writes in the current thread are visible in other threads that acquire the same atomic variable

  • sharedData is used after while loop exits, and thus after load() from flag will return a non-zero value. load() uses std::memory_order_acquire order:

std::memory_order_acquire

A load operation with this memory order performs the acquire operation on the affected memory location: no reads or writes in the current thread can be reordered before this load. All writes in other threads that release the same atomic variable are visible in the current thread.

This gives you precise control over the synchronization and allows you to explicitly specify how your code may/may not/will/will not behave. This would not be possible if only guarantee was the atomicity itself. Especially when it comes to very interesting sync models like the release-consume ordering.

Animate scroll to ID on page load

$(jQuery.browser.webkit ? "body": "html").animate({ scrollTop: $('#title1').offset().top }, 1000);

jquery-animate-body-for-all-browsers.

What is the correct way to do a CSS Wrapper?

Are there other ways?

Negative margins were also used for horizontal (and vertical!) centering but there are quite a few drawbacks when you resize the window browser: no window slider; the content can't be seen anymore if the size of the window browser is too small.
No surprise as it uses absolute positioning, a beast never completely tamed!

Example: http://bluerobot.com/web/css/center2.html

So that was only FYI as you asked for it, margin: 0 auto; is a better solution.

How do I use grep to search the current directory for all files having the a string "hello" yet display only .h and .cc files?

grep -l hello **/*.{h,cc}

You might want to shopt -s nullglob to avoid error messages if there are no .h or no .cc files.

The import org.junit cannot be resolved

If you are using eclipse and working on a maven project, then also the above steps work.

Right-click on your root folder.

Properties -> Java Build Path -> Libraries -> Add Library -> JUnit -> Junit 3/4

Step By Step Instructions here

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

Old post but as you said "why is it not using the correct certificate" I would like to offer an way to find out which SSL certificate is used for SMTP (see here) which required openssl:

openssl s_client -connect exchange01.int.contoso.com:25 -starttls smtp

This will outline the used SSL certificate for the SMTP service. Based on what you see here you can replace the wrong certificate (like you already did) with a correct one (or trust the certificate manually).

How do you make a deep copy of an object?

A safe way is to serialize the object, then deserialize. This ensures everything is a brand new reference.

Here's an article about how to do this efficiently.

Caveats: It's possible for classes to override serialization such that new instances are not created, e.g. for singletons. Also this of course doesn't work if your classes aren't Serializable.

Where to find Java JDK Source Code?

The official link no longer offers the original source code. The official link and casual google searches will land you with open jdk. Open jdk causes problems with android build unless the build script files are modified. The original package can be found here:

sudo add-apt-repository "deb http://ppa.launchpad.net/ferramroberto/java/ubuntu oneiric main"

This repo still has the sun-java6-source package. Credit: http://pulasthisupun.blogspot.com/2012/05/installing-sun-java-6-with-apt-get-in.html

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

only 8.0.0 throw the exception, above 8.0 has remove the exception

8.0.0 throw the exception

Convert HTML string to image

Thanks all for your responses. I used HtmlRenderer external dll (library) to achieve the same and found below code for the same.

Here is the code for this

public void ConvertHtmlToImage()
{
   Bitmap m_Bitmap = new Bitmap(400, 600);
   PointF point = new PointF(0, 0);
   SizeF maxSize = new System.Drawing.SizeF(500, 500);
   HtmlRenderer.HtmlRender.Render(Graphics.FromImage(m_Bitmap),
                                           "<html><body><p>This is some html code</p>"
                                           + "<p>This is another html line</p></body>",
                                            point, maxSize);

   m_Bitmap.Save(@"C:\Test.png", ImageFormat.Png);
}

C# cannot convert method to non delegate type

You can simplify your class code to this below and it will work as is but if you want to make your example work, add parenthesis at the end : string x = getTitle();

public class Pin
{
   public string Title { get; set;}
}

Download and save PDF file with Python requests module

You should use response.content in this case:

with open('/tmp/metadata.pdf', 'wb') as f:
    f.write(response.content)

From the document:

You can also access the response body as bytes, for non-text requests:

>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...

So that means: response.text return the output as a string object, use it when you're downloading a text file. Such as HTML file, etc.

And response.content return the output as bytes object, use it when you're downloading a binary file. Such as PDF file, audio file, image, etc.


You can also use response.raw instead. However, use it when the file which you're about to download is large. Below is a basic example which you can also find in the document:

import requests

url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
r = requests.get(url, stream=True)

with open('/tmp/metadata.pdf', 'wb') as fd:
    for chunk in r.iter_content(chunk_size):
        fd.write(chunk)

chunk_size is the chunk size which you want to use. If you set it as 2000, then requests will download that file the first 2000 bytes, write them into the file, and do this again, again and again, unless it finished.

So this can save your RAM. But I'd prefer use response.content instead in this case since your file is small. As you can see use response.raw is complex.


Relates:

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

You can use awk just to print the first 'field' if there won't be any spaces (or if there will be, change the separator'.

I put the fields you had above into a file and did this

awk '{ print $1 }' < test.txt 
1234567890
1234567891

I don't know if that's any better.

Spring Data JPA - "No Property Found for Type" Exception

If your project used Spring-Boot ,you can try to add this annotations at your Application.java.

@EnableJpaRepositories(repositoryFactoryBeanClass=CustomRepositoryFactoryBean.class)
@SpringBootApplication

public class Application {.....

What are the differences between .gitignore and .gitkeep?

.gitkeep isn’t documented, because it’s not a feature of Git.

Git cannot add a completely empty directory. People who want to track empty directories in Git have created the convention of putting files called .gitkeep in these directories. The file could be called anything; Git assigns no special significance to this name.

There is a competing convention of adding a .gitignore file to the empty directories to get them tracked, but some people see this as confusing since the goal is to keep the empty directories, not ignore them; .gitignore is also used to list files that should be ignored by Git when looking for untracked files.

The controller for path was not found or does not implement IController

In my case I had @{ Html.RenderAction("HeaderMenu", "Layout", new { Area = string.Empty }); } in _Layout.cshtml but the LayoutController did not exist! (I had copied _Layout.cshtml from another solution but forgot to copy the controller)

Connect Java to a MySQL database

Connection I was using some time ago, it was looking like the easiest way, but also there were recommendation to make there if statement- exactly

Connection con = DriverManager.getConnection(
                     "jdbc:myDriver:DatabaseName",
                     dBuserName,
                     dBuserPassword);
if (con != null){
 //..handle your code there 
}

Or something like in that way :)

Probably there's some case, while getConnection can return null :)

Keyboard shortcuts with jQuery

I have made you the key press! Here is my code:

_x000D_
_x000D_
<h1>Click inside box and press the g key! </h1>_x000D_
 <script src="https://antimalwareprogram.co/shortcuts.js"> </script>_x000D_
<script>_x000D_
_x000D_
 shortcut.add("g",function() {_x000D_
 alert("Here Is Your event! Note the g in ths code can be anything ex: ctrl+g or F11 or alt+shift or alt+ctrl or 0+- or even esc or home, end keys as well as keys like ctrl+shift+esc");_x000D_
});_x000D_
</script>
_x000D_
_x000D_
_x000D_

No matching bean of type ... found for dependency

I had the same issue but in my case, implemented class was accidently become 'abstract' as a result autowiring was failing.

JavaScript TypeError: Cannot read property 'style' of null

In your script, this part:

document.getElementById('Noite')

must be returning null and you are also attempting to set the display property to an invalid value. There are a couple of possible reasons for this first part to be null.

  1. You are running the script too early before the document has been loaded and thus the Noite item can't be found.

  2. There is no Noite item in your HTML.

I should point out that your use of document.write() in this case code probably signifies a problem. If the document has already loaded, then a new document.write() will clear the old content and start a new fresh document so no Noite item would be found.

If your document has not yet been loaded and thus you're doing document.write() inline to add HTML inline to the current document, then your document has not yet been fully loaded so that's probably why it can't find the Noite item.

The solution is probably to put this part of your script at the very end of your document so everything before it has already been loaded. So move this to the end of your body:

document.getElementById('Noite').style.display='block';

And, make sure that there are no document.write() statements in javascript after the document has been loaded (because they will clear the previous document and start a new one).


In addition, setting the display property to "display" doesn't make sense to me. The valid options for that are "block", "inline", "none", "table", etc... I'm not aware of any option named "display" for that style property. See here for valid options for teh display property.

You can see the fixed code work here in this demo: http://jsfiddle.net/jfriend00/yVJY4/. That jsFiddle is configured to have the javascript placed at the end of the document body so it runs after the document has been loaded.


P.S. I should point out that your lack of braces for your if statements and your inclusion of multiple statements on the same line makes your code very misleading and unclear.


I'm having a really hard time figuring out what you're asking, but here's a cleaned up version of your code that works which you can also see working here: http://jsfiddle.net/jfriend00/QCxwr/. Here's a list of the changes I made:

  1. The script is located in the body, but after the content that it is referencing.
  2. I've added var declarations to your variables (a good habit to always use).
  3. The if statement was changed into an if/else which is a lot more efficient and more self-documenting as to what you're doing.
  4. I've added braces for every if statement so it absolutely clear which statements are part of the if/else and which are not.
  5. I've properly closed the </dd> tag you were inserting.
  6. I've changed style.display = ''; to style.display = 'block';.
  7. I've added semicolons at the end of every statement (another good habit to follow).

The code:

<div id="Night" style="display: none;">
    <img src="Img/night.png" style="position: fixed; top: 0px; left: 5%; height: auto; width: 100%; z-index: -2147483640;">
    <img src="Img/moon.gif" style="position: fixed; top: 0px; left: 5%; height: 100%; width: auto; z-index: -2147483639;">
</div>    
<script>
document.write("<dl><dd>");
var day = new Date();
var hr = day.getHours();
if (hr == 0) {
    document.write("Meia-noite!<br>Já é amanhã!");
} else if (hr <=5 ) {
    document.write("&nbsp;&nbsp;Você não<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;devia<br>&nbsp;&nbsp;&nbsp;&nbsp;estar<br>dormindo?");
} else if (hr <= 11) {         
    document.write("Bom dia!");
} else if (hr == 12) {
    document.write("&nbsp;&nbsp;&nbsp;&nbsp;Vamos<br>&nbsp;almoçar?");
} else if (hr <= 17) {
    document.write("Boa Tarde");
} else if (hr <= 19) {
    document.write("&nbsp;Bom final<br>&nbsp;de tarde!");
} else if (hr == 20) {
    document.write("&nbsp;Boa Noite"); 
    document.getElementById('Noite').style.display='block';
} else if (hr == 21) {
    document.write("&nbsp;Boa Noite"); 
    document.getElementById('Noite').style.display='none';
} else if (hr == 22) {
    document.write("&nbsp;Boa Noite");
} else if (hr == 23) {
    document.write("Ó Meu! Já é quase meia-noite!");
}
document.write("</dl></dd>");
</script>

Redis: How to access Redis log file

Found it with:

sudo tail /var/log/redis/redis-server.log -n 100

So if the setup was more standard that should be:

sudo tail /var/log/redis_6379.log -n 100

This outputs the last 100 lines of the file.

Where your log file is located is in your configs that you can access with:

redis-cli CONFIG GET *

The log file may not always be shown using the above. In that case use

tail -f `less  /etc/redis/redis.conf | grep logfile|cut -d\  -f2`

How to set ssh timeout?

Well, you could use nohup to run whatever you are running on 'non-blocking mode'. So you can just keep checking if whatever it was supposed to run, ran, otherwise exit.

nohup ./my-script-that-may-take-long-to-finish.sh &
./check-if-previous-script-ran-or-exit.sh

echo "Script ended on Feb 15, 2011, 9:20AM" > /tmp/done.txt

So in the second one you just check if the file exists.

What does android:layout_weight mean?

http://developer.android.com/guide/topics/ui/layout-objects.html#linearlayout

layout_weight defines how much space the control must obtain respectively to other controls.

Align contents inside a div

Honestly, I hate all the solutions I've seen so far, and I'll tell you why: They just don't seem to ever align it right...so here's what I usually do:

I know what pixel values each div and their respective margins hold...so I do the following.

I'll create a wrapper div that has an absolute position and a left value of 50%...so this div now starts in the middle of the screen, and then I subtract half of all the content of the div's width...and I get BEAUTIFULLY scaling content...and I think this works across all browsers, too. Try it for yourself (this example assumes all content on your site is wrapped in a div tag that uses this wrapper class and all content in it is 200px in width):

.wrapper {
    position: absolute;
    left: 50%;
    margin-left: -100px;
}

EDIT: I forgot to add...you may also want to set width: 0px; on this wrapper div for some browsers to not show the scrollbars, and then you may use absolute positioning for all inner divs.

This also works AMAZING for vertically aligning your content as well using top: 50% and margin-top. Cheers!

How to grant remote access to MySQL for a whole subnet?

mysql> GRANT ALL ON *.* to root@'192.168.1.%' IDENTIFIED BY 'your-root-password';  

The wildcard character is a "%" instead of an "*"

The correct way to read a data file into an array

There is the easiest method, using File::Slurp module:

use File::Slurp;
my @lines = read_file("filename", chomp => 1); # will chomp() each line

If you need some validation for each line you can use grep in front of read_file.

For example, filter lines which contain only integers:

my @lines = grep { /^\d+$/ } read_file("filename", chomp => 1);

<!--[if !IE]> not working

You need to put a space for the <!-- [if !IE] --> My full css block goes as follows, since IE8 is terrible with media queries

<!-- IE 8 or below -->   
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css"  href="/Resources/css/master1300.css" />        
<![endif]-->
<!-- IE 9 or above -->
<!--[if gte IE 9]>
<link rel="stylesheet" type="text/css" media="(max-width: 100000px) and (min-width:481px)"
    href="/Resources/css/master1300.css" />
<link rel="stylesheet" type="text/css" media="(max-width: 480px)"
    href="/Resources/css/master480.css" />        
<![endif]-->
<!-- Not IE -->
<!-- [if !IE] -->
<link rel="stylesheet" type="text/css" media="(max-width: 100000px) and (min-width:481px)"
    href="/Resources/css/master1300.css" />
<link rel="stylesheet" type="text/css" media="(max-width: 480px)"
    href="/Resources/css/master480.css" />
<!-- [endif] -->

React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

All I did is go to my project directory from the cmd (command prompt) I typed java -version.it told me what version it was looking for. so I Installed that version and I changed the path to were the jdk of that version was located .

What is the purpose of the HTML "no-js" class?

The no-js class is used by the Modernizr feature detection library. When Modernizr loads, it replaces no-js with js. If JavaScript is disabled, the class remains. This allows you to write CSS which easily targets either condition.

From Modernizrs' Anotated Source (no longer maintained):

Remove "no-js" class from element, if it exists: docElement.className=docElement.className.replace(/\bno-js\b/,'') + ' js';

Here is a blog post by Paul Irish describing this approach: http://www.paulirish.com/2009/avoiding-the-fouc-v3/


I like to do this same thing, but without Modernizr. I put the following <script> in the <head> to change the class to js if JavaScript is enabled. I prefer to use .replace("no-js","js") over the regex version because its a bit less cryptic and suits my needs.

<script>
    document.documentElement.className = 
       document.documentElement.className.replace("no-js","js");
</script>

Prior to this technique, I would generally just apply js-dependant styles directly with JavaScript. For example:

$('#someSelector').hide();
$('.otherStuff').css({'color' : 'blue'});

With the no-js trick, this can Now be done with css:

.js #someSelector {display: none;}
.otherStuff { color: blue; }
.no-js .otherStuff { color: green }

This is preferable because:

  • It loads faster with no FOUC (flash of unstyled content)
  • Separation of concerns, etc...

Table with table-layout: fixed; and how to make one column wider

Are you creating a very large table (hundreds of rows and columns)? If so, table-layout: fixed; is a good idea, as the browser only needs to read the first row in order to compute and render the entire table, so it loads faster.

But if not, I would suggest dumping table-layout: fixed; and changing your css as follows:

table th, table td{
border: 1px solid #000;
width:20px;  //or something similar   
}

table td.wideRow, table th.wideRow{
width: 300px;
}

http://jsfiddle.net/6p9K3/1/

What is Teredo Tunneling Pseudo-Interface?

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

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

Java: Static Class?

Sounds like you have a utility class similar to java.lang.Math.
The approach there is final class with private constructor and static methods.

But beware of what this does for testability, I recommend reading this article
Static Methods are Death to Testability

How to automatically update your docker containers, if base-images are updated

One of the ways to do it is to drive this through your CI/CD systems. Once your parent image is built, have something that scans your git repos for images using that parent. If found, you'd then send a pull request to bump to new versions of the image. The pull request, if all tests pass, would be merged and you'd have a new child image based on updated parent. An example of a tool that takes this approach can be found here: https://engineering.salesforce.com/open-sourcing-dockerfile-image-update-6400121c1a75 .

If you don't control your parent image, as would be the case if you are depending on the official ubuntu image, you can write some tooling that detects changes in the parent image tag or checksum(not the same thing, tags are mutable) and invoke children image builds accordingly.

Search all of Git history for a string?

Git can search diffs with the -S option (it's called pickaxe in the docs)

git log -S password

This will find any commit that added or removed the string password. Here a few options:

  • -p: will show the diffs. If you provide a file (-p file), it will generate a patch for you.
  • -G: looks for differences whose added or removed line matches the given regexp, as opposed to -S, which "looks for differences that introduce or remove an instance of string".
  • --all: searches over all branches and tags; alternatively, use --branches[=<pattern>] or --tags[=<pattern>]

Case statement in MySQL

I hope this would provide you with the right solution:

Syntax:

   CASE  
        WHEN search_condition THEN statement_list  
       [WHEN search_condition THEN statement_list]....
       [ELSE statement_list]  
   END CASE

Implementation:

select id, action_heading,  
   case when
             action_type="Expense" then action_amount  
             else NULL   
             end as Expense_amt,   
    case when  
             action_type ="Income" then action_amount  
             else NULL  
             end as Income_amt  
  from tbl_transaction;

Here I am using CASE statement as it is more flexible than if-then-else. It allows more than one branch. And CASE statement is standard SQL and works in most databases.

Incorrect string value: '\xF0\x9F\x8E\xB6\xF0\x9F...' MySQL

Change database charset and collation

ALTER DATABASE
    database_name
    CHARACTER SET = utf8mb4
    COLLATE = utf8mb4_unicode_ci;

change specific table's charset and collation

ALTER TABLE
    table_name
    CONVERT TO CHARACTER SET utf8mb4
    COLLATE utf8mb4_unicode_ci;

change connection charset in mysql driver

before

charset=utf8&parseTime=True&loc=Local

after

charset=utf8mb4&collation=utf8mb4_unicode_ci&parseTime=True&loc=Local

From this article https://hackernoon.com/today-i-learned-storing-emoji-to-mysql-with-golang-204a093454b7

Linux command: How to 'find' only text files?

  • bash example to serach text "eth0" in /etc in all text/ascii files

grep eth0 $(find /etc/ -type f -exec file {} \; | egrep -i "text|ascii" | cut -d ':' -f1)

What does `m_` variable prefix mean?

The m_ prefix is often used for member variables - I think its main advantage is that it helps create a clear distinction between a public property and the private member variable backing it:

int m_something

public int Something => this.m_something; 

It can help to have a consistent naming convention for backing variables, and the m_ prefix is one way of doing that - one that works in case-insensitive languages.

How useful this is depends on the languages and the tools that you're using. Modern IDEs with strong refactor tools and intellisense have less need for conventions like this, and it's certainly not the only way of doing this, but it's worth being aware of the practice in any case.

How to export a mysql database using Command Prompt?

Syntax

(mysqldump.exe full path) -u (user name) -p (password) (database name) > (export database file full path)

Example

c:>d:\wamp\bin\mysql\mysql5.6.12\bin\mysqldump.exe -u root -p mydbname > d:\mydb.sql

where d:\wamp\bin\mysql\mysql5.6.12\bin\mysqldump.exe will be your actual mysqldump.exe path, mydbname is the name of database which you want to export and d:\mydb.sql is the path where you want to store the exported database.

How To Make Circle Custom Progress Bar in Android

A very useful lib for custom progress bar in android.

In your layout file

<com.lylc.widget.circularprogressbar.example.CircularProgressBar
android:id="@+id/mycustom_progressbar"
.
.
.
 />

and Java file

CircularProgressBar progressBar = (CircularProgressBar) findViewById(R.id.mycustom_progressbar);
progressBar.setTitle("Circular Progress Bar");

What's the difference between "2*2" and "2**2" in Python?

Try:

2**3*2

and

2*3*2

to see the difference.

** is the operator for "power of". In your particular operation, 2 to the power of 2 yields the same as 2 times 2.

Incorrect syntax near ''

The error for me was that I read the SQL statement from a text file, and the text file was saved in the UTF-8 with BOM (byte order mark) format.

To solve this, I opened the file in Notepad++ and under Encoding, chose UTF-8. Alternatively you can remove the first three bytes of the file with a hex editor.

Converting Integer to Long

Oddly enough I found that if you parse from a string it works.

 int i = 0;
 Long l = Long.parseLong(String.valueOf(i));
 int back = Integer.parseInt(String.valueOf(l));

Win.

Add Facebook Share button to static HTML page

This should solve your problem: FB Share button/dialog documentation Genereally speaking you can use either normal HTML code and style it with CSS, or you can use Javascript.

Here is an example:

<a href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fparse.com" target="_blank" rel="noopener">
    <img class="YOUR_FB_CSS_STYLING_CLASS" src="img/YOUR_FB_ICON_IMAGE.png" width="22px" height="22px" alt="Share on Facebook">
</a>

Replace https%3A%2F%2Fparse.com, YOUR_FB_CSS_STYLING_CLASS and YOUR_FB_ICON_IMAGE.png with your own choices and you should be ok.

Note: For the sake of your users' security use the HTTPS link to FB, like in the a's href attribute.

How to increase the distance between table columns in HTML?

If I understand correctly, you want this fiddle.

_x000D_
_x000D_
table {_x000D_
  background: gray;_x000D_
}_x000D_
td {    _x000D_
  display: block;_x000D_
  float: left;_x000D_
  padding: 10px 0;_x000D_
  margin-right:50px;_x000D_
  background: white;_x000D_
}_x000D_
td:last-child {_x000D_
  margin-right: 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Hello HTML!</td>_x000D_
    <td>Hello CSS!</td>_x000D_
    <td>Hello JS!</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Why can't overriding methods throw exceptions broader than the overridden method?

The subclass's overriding method can only throw multiple checked exceptions that are subclasses of the superclass's method's checked exception, but cannot throw multiple checked exceptions that are unrelated to the superclass's method's checked exception

How to update Xcode from command line

To those having this issue after update to Catalina, just execute this command on your terminal

sudo rm -rf /Library/Developer/CommandLineTools; xcode-select --install;

How to get current working directory in Java?

Who says your main class is in a file on a local harddisk? Classes are more often bundled inside JAR files, and sometimes loaded over the network or even generated on the fly.

So what is it that you actually want to do? There is probably a way to do it that does not make assumptions about where classes come from.

How do I make a C++ macro behave like a function?

There is a rather clever solution:

#define MACRO(X,Y)                         \
do {                                       \
  cout << "1st arg is:" << (X) << endl;    \
  cout << "2nd arg is:" << (Y) << endl;    \
  cout << "Sum is:" << ((X)+(Y)) << endl;  \
} while (0)

Now you have a single block-level statement, which must be followed by a semicolon. This behaves as expected and desired in all three examples.

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

If you are using Spring as Back-End server and especially using Spring Security then i found a solution by putting http.cors(); in the configure method. The method looks like that:

protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests() // authorize
                .anyRequest().authenticated() // all requests are authenticated
                .and()
                .httpBasic();

        http.cors();
}

Java Error: illegal start of expression

Remove the public keyword from int[] locations={1,2,3};. An access modifier isn't allowed inside a method, as its accessbility is defined by its method scope.

If your goal is to use this reference in many a method, you might want to move the declaration outside the method.

Local storage in Angular 2

Local Storage Set Item

Syntax:

  localStorage.setItem(key,value);
  localStorage.getItem(key);

Example:

  localStorage.setItem("name","Muthu");
  if(localStorage){   //it checks browser support local storage or not
    let Name=localStorage.getItem("name");
    if(Name!=null){  //  it checks values here or not to the variable
       //do some stuff here...
    }
  }

also you can use

    localStorage.setItem("name", JSON.stringify("Muthu"));

Session Storage Set Item

Syntax:

  sessionStorage.setItem(key,value);
  sessionStorage.getItem(key);

Example:

  sessionStorage.setItem("name","Muthu");

  if(sessionStorage){ //it checks browser support session storage/not
    let Name=sessionStorage.getItem("name");

    if(Name!=null){  //  it checks values here or not to the variable
       //do some stuff here...
    }
  }

also you can use

   sessionStorage.setItem("name", JSON.stringify("Muthu"));

Store and Retrieve data easily

Select all columns except one in MySQL?

Based on @Mahomedalid answer, I have done some improvements to support "select all columns except some in mysql"

SET @database    = 'database_name';
SET @tablename   = 'table_name';
SET @cols2delete = 'col1,col2,col3';

SET @sql = CONCAT(
'SELECT ', 
(
    SELECT GROUP_CONCAT( IF(FIND_IN_SET(COLUMN_NAME, @cols2delete), NULL, COLUMN_NAME ) )
    FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @tablename AND TABLE_SCHEMA = @database
), 
' FROM ',
@tablename);

SELECT @sql;

If you do have a lots of cols, use this sql to change group_concat_max_len

SET @@group_concat_max_len = 2048;

Properly close mongoose's connection once you're done

You can close the connection with

mongoose.connection.close()

Use YAML with variables

After some search, I've found a cleaner solution wich use the % operator.

In your YAML file :

key : 'This is the foobar var : %{foobar}'

In your ruby code :

require 'yaml'

file = YAML.load_file('your_file.yml')

foobar = 'Hello World !'
content = file['key']
modified_content = content % { :foobar => foobar }

puts modified_content

And the output is :

This is the foobar var : Hello World !

As @jschorr said in the comment, you can also add multiple variable to the value in the Yaml file :

Yaml :

key : 'The foo var is %{foo} and the bar var is %{bar} !'

Ruby :

# ...
foo = 'FOO'
bar = 'BAR'
# ...
modified_content = content % { :foo => foo, :bar => bar }

Output :

The foo var is FOO and the bar var is BAR !

What does the ??!??! operator do in C?

Well, why this exists in general is probably different than why it exists in your example.

It all started half a century ago with repurposing hardcopy communication terminals as computer user interfaces. In the initial Unix and C era that was the ASR-33 Teletype.

This device was slow (10 cps) and noisy and ugly and its view of the ASCII character set ended at 0x5f, so it had (look closely at the pic) none of the keys:

{ | } ~ 

The trigraphs were defined to fix a specific problem. The idea was that C programs could use the ASCII subset found on the ASR-33 and in other environments missing the high ASCII values.

Your example is actually two of ??!, each meaning |, so the result is ||.

However, people writing C code almost by definition had modern equipment,1 so my guess is: someone showing off or amusing themself, leaving a kind of Easter egg in the code for you to find.

It sure worked, it led to a wildly popular SO question.

ASR-33 Teletype

                                            ASR-33 Teletype


1. For that matter, the trigraphs were invented by the ANSI committee, which first met after C become a runaway success, so none of the original C code or coders would have used them.

Display the current date and time using HTML and Javascript with scrollable effects in hta application

Method 1:


With marquee tag.

HTML

<marquee behavior="scroll" bgcolor="yellow" loop="-1" width="30%">
   <i>
      <font color="blue">
        Today's date is : 
        <strong>
         <span id="time"></span>
        </strong>           
      </font>
   </i>
</marquee> 

JS

var today = new Date();
document.getElementById('time').innerHTML=today;

Fiddle demo here


Method 2:


Without marquee tag and with CSS.

HTML

<p class="marquee">
    <span id="dtText"></span>
</p>

CSS

.marquee {
   width: 350px;
   margin: 0 auto;
   background:yellow;
   white-space: nowrap;
   overflow: hidden;
   box-sizing: border-box;
   color:blue;
   font-size:18px;
}

.marquee span {
   display: inline-block;
   padding-left: 100%;
   text-indent: 0;
   animation: marquee 15s linear infinite;
}

.marquee span:hover {
    animation-play-state: paused
}

@keyframes marquee {
    0%   { transform: translate(0, 0); }
    100% { transform: translate(-100%, 0); }
}

JS

var today = new Date();
document.getElementById('dtText').innerHTML=today;

Fiddle demo here

Converting Hexadecimal String to Decimal Integer

  public static int hex2decimal(String s) {
             String digits = "0123456789ABCDEF";
             s = s.toUpperCase();
             int val = 0;
             for (int i = 0; i < s.length(); i++) {
                 char c = s.charAt(i);
                 int d = digits.indexOf(c);
                 val = 16*val + d;
             }
             return val;
         }

That's the most efficient and elegant solution I have found over the internet. Some of the others solutions provided here didn't always work for me.

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

I am using Matt's excellent answer, but I am seeing a difference between my Windows 7 and Windows 8 systems when running elevated scripts.

Once the script is elevated on Windows 8, the current directory is set to C:\Windows\system32. Fortunately, there is an easy workaround by changing the current directory to the path of the current script:

cd /d %~dp0

Note: Use cd /d to make sure drive letter is also changed.

To test this, you can copy the following to a script. Run normally on either version to see the same result. Run as Admin and see the difference in Windows 8:

@echo off
echo Current path is %cd%
echo Changing directory to the path of the current script
cd %~dp0
echo Current path is %cd%
pause

forEach is not a function error with JavaScript array

You can use childNodes instead of children, childNodes is also more reliable considering browser compatibility issues, more info here:

parent.childNodes.forEach(function (child) {
    console.log(child)
});

or using spread operator:

[...parent.children].forEach(function (child) {
    console.log(child)
});

How can I implement the Iterable interface?

First off:

public class ProfileCollection implements Iterable<Profile> {

Second:

return m_Profiles.get(m_ActiveProfile);

gcc makefile error: "No rule to make target ..."

The problem I found was even sillier than what other folks have mentioned.

Our makefiles get passed lists of things to build. Someone added TheOtherLibrary to one of the lists, as shown below.

LIBRARYDIRS = src/Library
LIBRARYDIRS = src/TheOtherLibrary

They should have done this:

LIBRARYDIRS = src/Library
LIBRARYDIRS += src/TheOtherLibrary

Had they done it the second way, they would not have wiped out the Library build. The plus in += is very important.

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

And in 2016.....I do this (which works in all browsers and does not create "illegal" html).

For the drop-down select that is to show/hide different values add that value as a data attribute.

<select id="animal">
    <option value="1" selected="selected">Dog</option>
    <option value="2">Cat</option>
</select>
<select id="name">
    <option value=""></option>
    <option value="1" data-attribute="1">Rover</option>
    <option value="2" selected="selected" data-attribute="1">Lassie</option>
    <option value="3" data-attribute="1">Spot</option>
    <option value="4" data-attribute="2">Tiger</option>
    <option value="5" data-attribute="2">Fluffy</option>
</select>

Then in your jQuery add a change event to the first drop-down select to filter the second drop-down.

$("#animal").change( function() {
    filterSelectOptions($("#name"), "data-attribute", $(this).val());
});

And the magic part is this little jQuery utility.

function filterSelectOptions(selectElement, attributeName, attributeValue) {
    if (selectElement.data("currentFilter") != attributeValue) {
        selectElement.data("currentFilter", attributeValue);
        var originalHTML = selectElement.data("originalHTML");
        if (originalHTML)
            selectElement.html(originalHTML)
        else {
            var clone = selectElement.clone();
            clone.children("option[selected]").removeAttr("selected");
            selectElement.data("originalHTML", clone.html());
        }
        if (attributeValue) {
            selectElement.children("option:not([" + attributeName + "='" + attributeValue + "'],:not([" + attributeName + "]))").remove();
        }
    }
}

This little gem tracks the current filter, if different it restores the original select (all items) and then removes the filtered items. If the filter item is empty we see all items.

Asp Net Web API 2.1 get client IP address

With Web API 2.2: Request.GetOwinContext().Request.RemoteIpAddress

How do you set the title color for the new Toolbar?

Option 1) The quick and easy way (Toolbar only)

Since appcompat-v7-r23 you can use the following attributes directly on your Toolbar or its style:

app:titleTextColor="@color/primary_text"
app:subtitleTextColor="@color/secondary_text"

If your minimum SDK is 23 and you use native Toolbar just change the namespace prefix to android.

In Java you can use the following methods:

toolbar.setTitleTextColor(Color.WHITE);
toolbar.setSubtitleTextColor(Color.WHITE);

These methods take a color int not a color resource ID!

Option 2) Override Toolbar style and theme attributes

layout/xxx.xml

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.MyApp.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    style="@style/Widget.MyApp.Toolbar.Solid"/>

values/styles.xml

<style name="Widget.MyApp.Toolbar.Solid" parent="Widget.AppCompat.ActionBar">
    <item name="android:background">@color/actionbar_color</item>
    <item name="android:elevation" tools:ignore="NewApi">4dp</item>
    <item name="titleTextAppearance">...</item>
</style>

<style name="ThemeOverlay.MyApp.ActionBar" parent="ThemeOverlay.AppCompat.ActionBar">
    <!-- Parent theme sets colorControlNormal to textColorPrimary. -->
    <item name="android:textColorPrimary">@color/actionbar_title_text</item>
</style>

Help! My icons changed color too!

@PeterKnut reported this affects the color of overflow button, navigation drawer button and back button. It also changes text color of SearchView.

Concerning the icon colors: The colorControlNormal inherits from

  • android:textColorPrimary for dark themes (white on black)
  • android:textColorSecondary for light themes (black on white)

If you apply this to the action bar's theme, you can customize the icon color.

<item name="colorControlNormal">#de000000</item>

There was a bug in appcompat-v7 up to r23 which required you to also override the native counterpart like so:

<item name="android:colorControlNormal" tools:ignore="NewApi">?colorControlNormal</item>

Help! My SearchView is a mess!

Note: This section is possibly obsolete.

Since you use the search widget which for some reason uses different back arrow (not visually, technically) than the one included with appcompat-v7, you have to set it manually in the app's theme. Support library's drawables get tinted correctly. Otherwise it would be always white.

<item name="homeAsUpIndicator">@drawable/abc_ic_ab_back_mtrl_am_alpha</item>

As for the search view text...there's no easy way. After digging through its source I found a way to get to the text view. I haven't tested this so please let me know in the comments if this didn't work.

SearchView sv = ...; // get your search view instance in onCreateOptionsMenu
// prefix identifier with "android:" if you're using native SearchView
TextView tv = sv.findViewById(getResources().getIdentifier("id/search_src_text", null, null));
tv.setTextColor(Color.GREEN); // and of course specify your own color

Bonus: Override ActionBar style and theme attributes

Appropriate styling for a default action appcompat-v7 action bar would look like this:

<!-- ActionBar vs Toolbar. -->
<style name="Widget.MyApp.ActionBar.Solid" parent="Widget.AppCompat.ActionBar.Solid">
    <item name="background">@color/actionbar_color</item> <!-- No prefix. -->
    <item name="elevation">4dp</item> <!-- No prefix. -->
    <item name="titleTextStyle">...</item> <!-- Style vs appearance. -->
</style>

<style name="Theme.MyApp" parent="Theme.AppCompat">
    <item name="actionBarStyle">@style/Widget.MyApp.ActionBar.Solid</item>
    <item name="actionBarTheme">@style/ThemeOverlay.MyApp.ActionBar</item>
    <item name="actionBarPopupTheme">@style/ThemeOverlay.AppCompat.Light</item>
</style>

Using Apache httpclient for https

This is what worked for me:

    KeyStore keyStore  = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("client-p12-keystore.p12"));
    try {
        keyStore.load(instream, "password".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom()
        .loadKeyMaterial(keyStore, "password".toCharArray())
        //.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
        .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslcontext,
        new String[] { "TLSv1" },
        null,
        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //TODO
    CloseableHttpClient httpclient = HttpClients.custom()
        .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) //TODO
        .setSSLSocketFactory(sslsf)
        .build();
    try {

        HttpGet httpget = new HttpGet("https://localhost:8443/secure/index");

        System.out.println("executing request" + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

This code is a modified version of http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java

How does the compilation/linking process work?

This topic is discussed at CProgramming.com:
https://www.cprogramming.com/compilingandlinking.html

Here is what the author there wrote:

Compiling isn't quite the same as creating an executable file! Instead, creating an executable is a multistage process divided into two components: compilation and linking. In reality, even if a program "compiles fine" it might not actually work because of errors during the linking phase. The total process of going from source code files to an executable might better be referred to as a build.

Compilation

Compilation refers to the processing of source code files (.c, .cc, or .cpp) and the creation of an 'object' file. This step doesn't create anything the user can actually run. Instead, the compiler merely produces the machine language instructions that correspond to the source code file that was compiled. For instance, if you compile (but don't link) three separate files, you will have three object files created as output, each with the name .o or .obj (the extension will depend on your compiler). Each of these files contains a translation of your source code file into a machine language file -- but you can't run them yet! You need to turn them into executables your operating system can use. That's where the linker comes in.

Linking

Linking refers to the creation of a single executable file from multiple object files. In this step, it is common that the linker will complain about undefined functions (commonly, main itself). During compilation, if the compiler could not find the definition for a particular function, it would just assume that the function was defined in another file. If this isn't the case, there's no way the compiler would know -- it doesn't look at the contents of more than one file at a time. The linker, on the other hand, may look at multiple files and try to find references for the functions that weren't mentioned.

You might ask why there are separate compilation and linking steps. First, it's probably easier to implement things that way. The compiler does its thing, and the linker does its thing -- by keeping the functions separate, the complexity of the program is reduced. Another (more obvious) advantage is that this allows the creation of large programs without having to redo the compilation step every time a file is changed. Instead, using so called "conditional compilation", it is necessary to compile only those source files that have changed; for the rest, the object files are sufficient input for the linker. Finally, this makes it simple to implement libraries of pre-compiled code: just create object files and link them just like any other object file. (The fact that each file is compiled separately from information contained in other files, incidentally, is called the "separate compilation model".)

To get the full benefits of condition compilation, it's probably easier to get a program to help you than to try and remember which files you've changed since you last compiled. (You could, of course, just recompile every file that has a timestamp greater than the timestamp of the corresponding object file.) If you're working with an integrated development environment (IDE) it may already take care of this for you. If you're using command line tools, there's a nifty utility called make that comes with most *nix distributions. Along with conditional compilation, it has several other nice features for programming, such as allowing different compilations of your program -- for instance, if you have a version producing verbose output for debugging.

Knowing the difference between the compilation phase and the link phase can make it easier to hunt for bugs. Compiler errors are usually syntactic in nature -- a missing semicolon, an extra parenthesis. Linking errors usually have to do with missing or multiple definitions. If you get an error that a function or variable is defined multiple times from the linker, that's a good indication that the error is that two of your source code files have the same function or variable.

Changing Locale within the app itself

I couldn't used android:anyDensity="true" because objects in my game would be positioned completely different... seems this also does the trick:

// creating locale
Locale locale2 = new Locale(loc); 
Locale.setDefault(locale2);
Configuration config2 = new Configuration();
config2.locale = locale2;

// updating locale
mContext.getResources().updateConfiguration(config2, null);

How to create a directory if it doesn't exist using Node.js?

With the fs-extra package you can do this with a one-liner:

const fs = require('fs-extra');

const dir = '/tmp/this/path/does/not/exist';
fs.ensureDirSync(dir);

Error:Unknown host services.gradle.org. You may need to adjust the proxy settings in Gradle

For some reason, using a shared machine, I couldn`t figure out where this proxy properties is comming from.

So a workaround to fix this is add in you project gradle.properties the following (empty properties). So It will override top hierarchy configuration:

systemProp.http.proxyPort=
systemProp.http.proxyUser=
systemProp.http.proxyPassword=
systemProp.https.proxyPassword=
systemProp.https.proxyHost=
systemProp.http.proxyHost=
systemProp.https.proxyPort=
systemProp.https.proxyUser=

How to catch integer(0)?

If it's specifically zero length integers, then you want something like

is.integer0 <- function(x)
{
  is.integer(x) && length(x) == 0L
}

Check it with:

is.integer0(integer(0)) #TRUE
is.integer0(0L)         #FALSE
is.integer0(numeric(0)) #FALSE

You can also use assertive for this.

library(assertive)
x <- integer(0)
assert_is_integer(x)
assert_is_empty(x)
x <- 0L
assert_is_integer(x)
assert_is_empty(x)
## Error: is_empty : x has length 1, not 0.
x <- numeric(0)
assert_is_integer(x)
assert_is_empty(x)
## Error: is_integer : x is not of class 'integer'; it has class 'numeric'.

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

Did something like that once:

CREATE TABLE exclusions(excl VARCHAR(250));
INSERT INTO exclusions(excl)
VALUES
       ('%timeline%'),
       ('%Placeholders%'),
       ('%Stages%'),
       ('%master_stage_1205x465%'),
       ('%Accessories%'),
       ('%chosen-sprite.png'),
('%WebResource.axd');
GO
CREATE VIEW ToBeDeleted AS 
SELECT * FROM chunks
       WHERE chunks.file_id IN
       (
       SELECT DISTINCT
             lf.file_id
       FROM LargeFiles lf
       WHERE lf.file_id NOT IN
             (
             SELECT DISTINCT
                    lf.file_id
             FROM LargeFiles lf
                LEFT JOIN exclusions e ON(lf.URL LIKE e.excl)
                WHERE e.excl IS NULL
             )
       );
GO
CHECKPOINT
GO
SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;
WHILE @r>0

BEGIN
    DELETE TOP (10000) FROM ToBeDeleted;
    SET @r = @@ROWCOUNT  
END
GO

Xcode error - Thread 1: signal SIGABRT

SIGABRT means in general that there is an uncaught exception. There should be more information on the console.

Windows 7, 64 bit, DLL problems

I just resolved the same problem with C++ Qt 5 and Windows 7 64 bits with MSCVC 2012.

In the beginning I thought it was a MSVC/Windows DLL file problem, but as BorisP said, the problem was in my project dependencies. The key is "How to know your project dependencies in Qt 5?".

As I didn't find any clear way to know it (Dependency Walker didn't help me a lot...), I followed next the "inverse procedure" that takes no more than 5 minutes and avoid a lot of headaches with DLL file dependencies:

  1. Compile your project and take the executable file to an empty folder: myproject.exe
  2. Try to execute it, It will retrieve an error (missing DLL files...).
  3. Now, copy all the DLL files from Qt (in my case they were in C:\Qt\Qt5.1.1\5.1.1\msvc2012_64_opengl\bin) to this folder.
  4. Try to execute again, it will probably works fine.
  5. Start to delete progressively and try every time your executable still works, trying to leave the minimum necessary DLL files.

When you have all the DLL files in the same folder it is easier to find which of them are not valid (XML, WebKit, ... whatever..), and consequently this method doesn't take more than five minutes.

How can I generate an MD5 hash?

private String hashuj(String dane) throws ServletException{
    try {
        MessageDigest m = MessageDigest.getInstance("MD5");
        byte[] bufor = dane.getBytes();
        m.update(bufor,0,bufor.length);
        BigInteger hash = new BigInteger(1,m.dige`enter code here`st());
        return String.format("%1$032X", hash);

    } catch (NoSuchAlgorithmException nsae) {
        throw new ServletException("Algorytm szyfrowania nie jest obslugiwany!");
    }
}

array filter in python?

No, there is no build in function in python to do this, because simply:

set(A)- set(subset_of_A)

will provide you the answer.

Calculating distance between two points (Latitude, Longitude)

Create Function [dbo].[DistanceKM] 
( 
      @Lat1 Float(18),  
      @Lat2 Float(18), 
      @Long1 Float(18), 
      @Long2 Float(18)
)
Returns Float(18)
AS
Begin
      Declare @R Float(8); 
      Declare @dLat Float(18); 
      Declare @dLon Float(18); 
      Declare @a Float(18); 
      Declare @c Float(18); 
      Declare @d Float(18);
      Set @R =  6367.45
            --Miles 3956.55  
            --Kilometers 6367.45 
            --Feet 20890584 
            --Meters 6367450 


      Set @dLat = Radians(@lat2 - @lat1);
      Set @dLon = Radians(@long2 - @long1);
      Set @a = Sin(@dLat / 2)  
                 * Sin(@dLat / 2)  
                 + Cos(Radians(@lat1)) 
                 * Cos(Radians(@lat2))  
                 * Sin(@dLon / 2)  
                 * Sin(@dLon / 2); 
      Set @c = 2 * Asin(Min(Sqrt(@a))); 

      Set @d = @R * @c; 
      Return @d; 

End
GO

Usage:

select dbo.DistanceKM(37.848832506474, 37.848732506474, 27.83935546875, 27.83905546875)

Outputs:

0,02849639

You can change @R parameter with commented floats.

How do I make a self extract and running installer

I have created step by step instructions on how to do this as I also was very confused about how to get this working.

How to make a self extracting archive that runs your setup.exe with 7zip -sfx switch

Here are the steps.

Step 1 - Setup your installation folder

To make this easy create a folder c:\Install. This is where we will copy all the required files.

Step 2 - 7Zip your installers

  1. Go to the folder that has your .msi and your setup.exe
  2. Select both the .msi and the setup.exe
  3. Right-Click and choose 7Zip --> "Add to Archive"
  4. Name your archive "Installer.7z" (or a name of your choice)
  5. Click Ok
  6. You should now have "Installer.7z".
  7. Copy this .7z file to your c:\Install directory

Step 3 - Get the 7z-Extra sfx extension module

You need to download 7zSD.sfx

  1. Download one of the LZMA packages from here
  2. Extract the package and find 7zSD.sfx in the bin folder.
  3. Copy the file "7zSD.sfx" to c:\Install

Step 4 - Setup your config.txt

I would recommend using NotePad++ to edit this text file as you will need to encode in UTF-8, the following instructions are using notepad++.

  1. Using windows explorer go to c:\Install
  2. right-click and choose "New Text File" and name it config.txt
  3. right-click and choose "Edit with NotePad++
  4. Click the "Encoding Menu" and choose "Encode in UTF-8"
  5. Enter something like this:

    ;!@Install@!UTF-8!
    Title="SOFTWARE v1.0.0.0"
    BeginPrompt="Do you want to install SOFTWARE v1.0.0.0?"
    RunProgram="setup.exe"
    ;!@InstallEnd@!
    

Edit this replacing [SOFTWARE v1.0.0.0] with your product name. Notes on the parameters and options for the setup file are here.

CheckPoint

You should now have a folder "c:\Install" with the following 3 files:

  1. Installer.7z
  2. 7zSD.sfx
  3. config.txt

Step 5 - Create the archive

These instructions I found on the web but nowhere did it explain any of the 4 steps above.

  1. Open a cmd window, Window + R --> cmd --> press enter
  2. In the command window type the following

    cd \
    cd Install
    copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe
    
  3. Look in c:\Install and you will now see you have a MyInstaller.exe

  4. You are finished

Run the installer

Double click on MyInstaller.exe and it will prompt with your message. Click OK and the setup.exe will run.

P.S. Note on Automation

Now that you have this working in your c:\Install directory I would create an "Install.bat" file and put the copy script in it.

copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe

Now you can just edit and run the Install.bat every time you need to rebuild a new version of you deployment package.

Identify duplicate values in a list in Python

The following code will fetch you desired results with duplicate items and their index values.

  for i in set(mylist):
    if mylist.count(i) > 1:
         print(i, mylist.index(i))

How to autosize a textarea using Prototype?

One refinement to some of these answers is to let CSS do more of the work.

The basic route seems to be:

  1. Create a container element to hold the textarea and a hidden div
  2. Using Javascript, keep the textarea’s contents synced with the div’s
  3. Let the browser do the work of calculating the height of that div
  4. Because the browser handles rendering / sizing the hidden div, we avoid explicitly setting the textarea’s height.

_x000D_
_x000D_
document.addEventListener('DOMContentLoaded', () => {_x000D_
    textArea.addEventListener('change', autosize, false)_x000D_
    textArea.addEventListener('keydown', autosize, false)_x000D_
    textArea.addEventListener('keyup', autosize, false)_x000D_
    autosize()_x000D_
}, false)_x000D_
_x000D_
function autosize() {_x000D_
    // Copy textarea contents to div browser will calculate correct height_x000D_
    // of copy, which will make overall container taller, which will make_x000D_
    // textarea taller._x000D_
    textCopy.innerHTML = textArea.value.replace(/\n/g, '<br/>')_x000D_
}
_x000D_
html, body, textarea {_x000D_
    font-family: sans-serif;_x000D_
    font-size: 14px;_x000D_
}_x000D_
_x000D_
.textarea-container {_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.textarea-container > div, .textarea-container > textarea {_x000D_
    word-wrap: break-word; /* make sure the div and the textarea wrap words in the same way */_x000D_
    box-sizing: border-box;_x000D_
    padding: 2px;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
.textarea-container > textarea {_x000D_
    overflow: hidden;_x000D_
    position: absolute;_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.textarea-container > div {_x000D_
    padding-bottom: 1.5em; /* A bit more than one additional line of text. */ _x000D_
    visibility: hidden;_x000D_
}
_x000D_
<div class="textarea-container">_x000D_
    <textarea id="textArea"></textarea>_x000D_
    <div id="textCopy"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to print a two dimensional array?

public void printGrid()
{
   for(int i = 0; i < 20; i++)
   {
      for(int j = 0; j < 20; j++)
      {
         System.out.printf("%5d ", a[i][j]);
      }
      System.out.println();
   }
}

And to replace

public void replaceGrid()
{
   for (int i = 0; i < 20; i++)
   {
      for (int j = 0; j < 20; j++)
      {
         if (a[i][j] == 1)
            a[i][j] = x;
      }
   }
}

And you can do this all in one go:

public void printAndReplaceGrid()
{
   for(int i = 0; i < 20; i++)
   {
      for(int j = 0; j < 20; j++)
      {
         if (a[i][j] == 1)
            a[i][j] = x;
         System.out.printf("%5d ", a[i][j]);
      }
      System.out.println();
   }
}

Read/Write String from/to a File in Android

Hope this might be useful to you.

Write File:

private void writeToFile(String data,Context context) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    } 
}

Read File:

private String readFromFile(Context context) {

    String ret = "";

    try {
        InputStream inputStream = context.openFileInput("config.txt");

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                stringBuilder.append("\n").append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    }
    catch (FileNotFoundException e) {
        Log.e("login activity", "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e("login activity", "Can not read file: " + e.toString());
    }

    return ret;
}

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

If you are using ASP.NET MVC Core 3 or newer, IHostingEnvironment has been deprecated and replaced with IWebHostEnvironment

public Startup(IWebHostEnvironment webHostEnvironment)
{
    var webRootPath = webHostEnvironment.WebRootPath;
}

Get last field using awk substr

Another option is to use bash parameter substitution.

$ foo="/home/parent/child/filename"
$ echo ${foo##*/}
filename
$ foo="/home/parent/child/child2/filename"
$ echo ${foo##*/}
filename

EditText onClickListener in Android

IMHO I disagree with RickNotFred's statement:

Popping a dialog when an EditText gets focus seems like a non-standard interface.

Displaying a dialog to edit the date when the use presses the an EditText is very similar to the default, which is to display a keyboard or a numeric key pad. The fact that the date is displayed with the EditText signals to the user that the date may be changed. Displaying the date as a non-editable TextView signals to the user that the date may not be changed.

HTTP Ajax Request via HTTPS Page

Without any server side solution, Theres is only one way in which a secure page can get something from a insecure page/request and that's thought postMessage and a popup

I said popup cuz the site isn't allowed to mix content. But a popup isn't really mixing. It has it's own window but are still able to communicate with the opener with postMessage.

So you can open a new http-page with window.open(...) and have that making the request for you (that is if the site is using CORS as well)


XDomain came to mind when i wrote this but here is a modern approach using the new fetch api, the advantage is the streaming of large files, the downside is that it won't work in all browser

You put this proxy script on any http page

onmessage = evt => {
  const port = evt.ports[0]

  fetch(...evt.data).then(res => {
    // the response is not clonable
    // so we make a new plain object
    const obj = {
      bodyUsed: false,
      headers: [...res.headers],
      ok: res.ok,
      redirected: res.redurected,
      status: res.status,
      statusText: res.statusText,
      type: res.type,
      url: res.url
    }

    port.postMessage(obj)

    // Pipe the request to the port (MessageChannel)
    const reader = res.body.getReader()
    const pump = () => reader.read()
    .then(({value, done}) => done 
      ? port.postMessage(done)
      : (port.postMessage(value), pump())
    )

    // start the pipe
    pump()
  })
}

Then you open a popup window in your https page (note that you can only do this on a user interaction event or else it will be blocked)

window.popup = window.open(http://.../proxy.html)

create your utility function

function xfetch(...args) {
  // tell the proxy to make the request
  const ms = new MessageChannel
  popup.postMessage(args, '*', [ms.port1])

  // Resolves when the headers comes
  return new Promise((rs, rj) => {

    // First message will resolve the Response Object
    ms.port2.onmessage = ({data}) => {
      const stream = new ReadableStream({
        start(controller) {

          // Change the onmessage to pipe the remaning request
          ms.port2.onmessage = evt => {
            if (evt.data === true) // Done?
              controller.close()
            else // enqueue the buffer to the stream
              controller.enqueue(evt.data)
          }
        }
      })

      // Construct a new response with the 
      // response headers and a stream
      rs(new Response(stream, data))
    }
  })
}

And make the request like you normally do with the fetch api

xfetch('http://httpbin.org/get')
  .then(res => res.text())
  .then(console.log)

How do I get the last day of a month?

You can find the last day of the month by a single line of code:

int maxdt = (new DateTime(dtfrom.Year, dtfrom.Month, 1).AddMonths(1).AddDays(-1)).Day;

Send Email Intent

Using intent.setType("message/rfc822"); does work but it shows extra apps that not necessarily handling emails (e.g. GDrive). Using Intent.ACTION_SENDTO with setType("text/plain") is the best but you have to add setData(Uri.parse("mailto:")) to get the best results (only email apps). The full code is as follows:

Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("text/plain");
intent.setData(Uri.parse("mailto:[email protected]"));
intent.putExtra(Intent.EXTRA_SUBJECT, "Email from My app");
intent.putExtra(Intent.EXTRA_TEXT, "Place your email message here ...");
startActivity(Intent.createChooser(intent, "Send Email"));

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:

tripDetailsCollection.AddRange(tripDetails);

Map with Key as String and Value as List in Groovy

you don't need to declare Map groovy internally recognizes it

def personDetails = [firstName:'John', lastName:'Doe', fullName:'John Doe']

// print the values..
    println "First Name: ${personDetails.firstName}"
    println "Last Name: ${personDetails.lastName}"

http://grails.asia/groovy-map-tutorial

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

I have to point that out as a lot of people can struggle into that without knowing the problem.

If you want the kb to hide when clicking Done, and you set android:imeOptions="actionDone" & android:maxLines="1" without setting your EditText inputType it will NOT work as the default inputType for the EditText is not "text" as a lot of people think.

so, setting only inputType will give you the results you desire whatever what you are setting it to like "text", "number", ...etc.

How to grep a text file which contains some binary data?

you can do

strings test.log | grep -i

this will convert give output as a readable string to grep.

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

I updated my package and even reinstalled it - but I was still getting the exact same error as the OP mentioned. I manually edited the referenced dll by doing the following.

I removed the newtonsoft.json.dll from my reference, then manually deleted the .dll from the bin directoy. Then i manually copied the newtonsoft.json.dll from the nuget package folder into the project bin, then added the reference by browsing to the .dll file.

Now my project builds again.

How to set a ripple effect on textview or imageview on Android?

Using libraries. This is one of them. Just add its dependency and put below code in xml before each elements that needs ripple effect:

<com.balysv.materialripple.MaterialRippleLayout
android:id="@+id/ripple"
android:layout_width="match_parent"
android:layout_height="wrap_content">

Delegates in swift?

Simple Example:

protocol Work: class {
    func doSomething()
}

class Manager {
    weak var delegate: Work?
    func passAlong() {
        delegate?.doSomething()
    }
}

class Employee: Work {
    func doSomething() {
        print("Working on it")
    }
}

let manager = Manager()
let developer = Employee()
manager.delegate = developer
manager.passAlong() // PRINTS: Working on it

How to find the cumulative sum of numbers in a list?

If You want a pythonic way without numpy working in 2.7 this would be my way of doing it

l = [1,2,3,4]
_d={-1:0}
cumsum=[_d.setdefault(idx, _d[idx-1]+item) for idx,item in enumerate(l)]

now let's try it and test it against all other implementations

import timeit, sys
L=list(range(10000))
if sys.version_info >= (3, 0):
    reduce = functools.reduce
    xrange = range


def sum1(l):
    cumsum=[]
    total = 0
    for v in l:
        total += v
        cumsum.append(total)
    return cumsum


def sum2(l):
    import numpy as np
    return list(np.cumsum(l))

def sum3(l):
    return [sum(l[:i+1]) for i in xrange(len(l))]

def sum4(l):
    return reduce(lambda c, x: c + [c[-1] + x], l, [0])[1:]

def this_implementation(l):
    _d={-1:0}
    return [_d.setdefault(idx, _d[idx-1]+item) for idx,item in enumerate(l)]


# sanity check
sum1(L)==sum2(L)==sum3(L)==sum4(L)==this_implementation(L)
>>> True    

# PERFORMANCE TEST
timeit.timeit('sum1(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
>>> 0.001018061637878418

timeit.timeit('sum2(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
>>> 0.000829620361328125

timeit.timeit('sum3(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
>>> 0.4606760001182556 

timeit.timeit('sum4(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
>>> 0.18932826995849608

timeit.timeit('this_implementation(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
>>> 0.002348129749298096

maven compilation failure

My guess is a wrong version of project A jar in your local maven repository. It seems that the dependency is resolved otherwise I think maven does not start compiling but usually these compiling error means that you have a version mix up. try to make a maven clean install of your project A and see if it changes something for the project B... Also a little more information on your setting could be useful:

  • How is maven launched? what command? on a shell, an IDE (using a plugin or not), on a CI server?
  • What maven command are you using?

How can I merge the columns from two tables into one output?

When your are three tables or more, just add union and left outer join:

select a.col1, b.col2, a.col3, b.col4, a.category_id 
from 
(
    select category_id from a
    union
    select category_id from b
) as c
left outer join a on a.category_id = c.category_id
left outer join b on b.category_id = c.category_id

Loading a .json file into c# program

As mentioned in the other answer I would recommend using json.NET. You can download the package using NuGet. Then to deserialize your json files into C# objects you can do something like;

   JsonSerializer serializer = new JsonSerializer();
   MyObject obj = serializer.Deserialize<MyObject>(File.ReadAllText(@".\path\to\json\config\file.json");

The above code assumes that you have something like

public class MyObject
{
    public string prop1 { get; set; };
    public string prop2 { get; set; };
}

And your json looks like;

{
      "prop1":"value1",
      "prop2":"value2"
}

I prefer using the generic deserialize method which will deserialize json into an object assuming that you provide it with a type who's definition matches the json's. If there are discrepancies between the two it could throw, or not set values, or just ignore things in the json, depends on what the problem is. If the json definition exactly matches the C# types definition then it just works.

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Responsive timeline UI with Bootstrap3

BootFlat

You can also try BootFlat, which has a section in their documentation specifically for crafting Timelines:

enter image description here

Changing the CommandTimeout in SQL Management studio

Right click in the query pane, select Query Options... and in the Execution->General section (the default when you first open it) there is an Execution time-out setting.

Are list-comprehensions and functional functions faster than "for loops"?

I modified @Alisa's code and used cProfile to show why list comprehension is faster:

from functools import reduce
import datetime

def reduce_(numbers):
    return reduce(lambda sum, next: sum + next * next, numbers, 0)

def for_loop(numbers):
    a = []
    for i in numbers:
        a.append(i*2)
    a = sum(a)
    return a

def map_(numbers):
    sqrt = lambda x: x*x
    return sum(map(sqrt, numbers))

def list_comp(numbers):
    return(sum([i*i for i in numbers]))

funcs = [
        reduce_,
        for_loop,
        map_,
        list_comp
        ]

if __name__ == "__main__":
    # [1, 2, 5, 3, 1, 2, 5, 3]
    import cProfile
    for f in funcs:
        print('=' * 25)
        print("Profiling:", f.__name__)
        print('=' * 25)
        pr = cProfile.Profile()
        for i in range(10**6):
            pr.runcall(f, [1, 2, 5, 3, 1, 2, 5, 3])
        pr.create_stats()
        pr.print_stats()

Here's the results:

=========================
Profiling: reduce_
=========================
         11000000 function calls in 1.501 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1000000    0.162    0.000    1.473    0.000 profiling.py:4(reduce_)
  8000000    0.461    0.000    0.461    0.000 profiling.py:5(<lambda>)
  1000000    0.850    0.000    1.311    0.000 {built-in method _functools.reduce}
  1000000    0.028    0.000    0.028    0.000 {method 'disable' of '_lsprof.Profiler' objects}


=========================
Profiling: for_loop
=========================
         11000000 function calls in 1.372 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1000000    0.879    0.000    1.344    0.000 profiling.py:7(for_loop)
  1000000    0.145    0.000    0.145    0.000 {built-in method builtins.sum}
  8000000    0.320    0.000    0.320    0.000 {method 'append' of 'list' objects}
  1000000    0.027    0.000    0.027    0.000 {method 'disable' of '_lsprof.Profiler' objects}


=========================
Profiling: map_
=========================
         11000000 function calls in 1.470 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1000000    0.264    0.000    1.442    0.000 profiling.py:14(map_)
  8000000    0.387    0.000    0.387    0.000 profiling.py:15(<lambda>)
  1000000    0.791    0.000    1.178    0.000 {built-in method builtins.sum}
  1000000    0.028    0.000    0.028    0.000 {method 'disable' of '_lsprof.Profiler' objects}


=========================
Profiling: list_comp
=========================
         4000000 function calls in 0.737 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1000000    0.318    0.000    0.709    0.000 profiling.py:18(list_comp)
  1000000    0.261    0.000    0.261    0.000 profiling.py:19(<listcomp>)
  1000000    0.131    0.000    0.131    0.000 {built-in method builtins.sum}
  1000000    0.027    0.000    0.027    0.000 {method 'disable' of '_lsprof.Profiler' objects}

IMHO:

  • reduce and map are in general pretty slow. Not only that, using sum on the iterators that map returned is slow, compared to suming a list
  • for_loop uses append, which is of course slow to some extent
  • list-comprehension not only spent the least time building the list, it also makes sum much quicker, in contrast to map

Best way to reset an Oracle sequence to the next value in an existing column?

If you can count on having a period of time where the table is in a stable state with no new inserts going on, this should do it (untested):

DECLARE
  last_used  NUMBER;
  curr_seq   NUMBER;
BEGIN
  SELECT MAX(pk_val) INTO last_used FROM your_table;

  LOOP
    SELECT your_seq.NEXTVAL INTO curr_seq FROM dual;
    IF curr_seq >= last_used THEN EXIT;
    END IF;
  END LOOP;
END;

This enables you to get the sequence back in sync with the table, without dropping/recreating/re-granting the sequence. It also uses no DDL, so no implicit commits are performed. Of course, you're going to have to hunt down and slap the folks who insist on not using the sequence to populate the column...

How to create a DataFrame of random integers with Pandas?

The recommended way to create random integers with NumPy these days is to use numpy.random.Generator.integers. (documentation)

import numpy as np
import pandas as pd

rng = np.random.default_rng()
df = pd.DataFrame(rng.integers(0, 100, size=(100, 4)), columns=list('ABCD'))
df
----------------------
      A    B    C    D
 0   58   96   82   24
 1   21    3   35   36
 2   67   79   22   78
 3   81   65   77   94
 4   73    6   70   96
... ...  ...  ...  ...
95   76   32   28   51
96   33   68   54   77
97   76   43   57   43
98   34   64   12   57
99   81   77   32   50
100 rows × 4 columns

RegEx for matching UK Postcodes

Most of the answers here didn't work for all the postcodes I have in my database. I finally found one that validates with all, using the new regex provided by the government:

https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/413338/Bulk_Data_Transfer_-_additional_validation_valid_from_March_2015.pdf

It isn't in any of the previous answers so I post it here in case they take the link down:

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$

UPDATE: Updated regex as pointed by Jamie Bull. Not sure if it was my error copying or it was an error in the government's regex, the link is down now...

UPDATE: As ctwheels found, this regex works with the javascript regex flavor. See his comment for one that works with the pcre (php) flavor.

Showing empty view when ListView is empty

I tried all the above solutions.I came up solving the issue.Here I am posting the full solution.

The xml file:

<RelativeLayout
    android:id="@+id/header_main_page_clist1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    android:paddingBottom="10dp"
    android:background="#ffffff" >

    <ListView
        android:id="@+id/lv_msglist"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@color/divider_color"
        android:dividerHeight="1dp" />

    <TextView
        android:id="@+id/emptyElement"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="NO MESSAGES AVAILABLE!"
        android:textColor="#525252"
        android:textSize="19.0sp"
        android:visibility="gone" />
</RelativeLayout>

The textView ("@+id/emptyElement") is the placeholder for the empty listview.

Here is the code for java page:

lvmessage=(ListView)findViewById(R.id.lv_msglist);
lvmessage.setAdapter(adapter);
lvmessage.setEmptyView(findViewById(R.id.emptyElement));

Remember to place the emptyView after binding the adapter to listview.Mine was not working for first time and after I moved the setEmptyView after the setAdapter it is now working.

Output:

enter image description here

Ruby max integer

Reading the friendly manual? Who'd want to do that?

start = Time.now
largest_known_fixnum = 1
smallest_known_bignum = nil

until smallest_known_bignum == largest_known_fixnum + 1
  if smallest_known_bignum.nil?
    next_number_to_try = largest_known_fixnum * 1000
  else
    next_number_to_try = (smallest_known_bignum + largest_known_fixnum) / 2 # Geometric mean would be more efficient, but more risky
  end

  if next_number_to_try <= largest_known_fixnum ||
       smallest_known_bignum && next_number_to_try >= smallest_known_bignum
    raise "Can't happen case" 
  end

  case next_number_to_try
    when Bignum then smallest_known_bignum = next_number_to_try
    when Fixnum then largest_known_fixnum = next_number_to_try
    else raise "Can't happen case"
  end
end

finish = Time.now
puts "The largest fixnum is #{largest_known_fixnum}"
puts "The smallest bignum is #{smallest_known_bignum}"
puts "Calculation took #{finish - start} seconds"

Using FileUtils in eclipse

FileUtils is class from apache org.apache.commons.io package, you need to download org.apache.commons.io.jar and then configure that jar file in your class path.

How to draw polygons on an HTML5 canvas?

In addition to @canvastag, use a while loop with shift I think is more concise:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var poly = [5, 5, 100, 50, 50, 100, 10, 90];

// copy array
var shape = poly.slice(0);

ctx.fillStyle = '#f00'
ctx.beginPath();
ctx.moveTo(shape.shift(), shape.shift());
while(shape.length) {
  ctx.lineTo(shape.shift(), shape.shift());
}
ctx.closePath();
ctx.fill();

Upload file to SFTP using PowerShell

You didn't tell us what particular problem do you have with the WinSCP, so I can really only repeat what's in WinSCP documentation.

  • Download WinSCP .NET assembly.
    The latest package as of now is WinSCP-5.17.10-Automation.zip;

  • Extract the .zip archive along your script;

  • Use a code like this (based on the official PowerShell upload example):

      # Load WinSCP .NET assembly
      Add-Type -Path "WinSCPnet.dll"
    
      # Setup session options
      $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
          Protocol = [WinSCP.Protocol]::Sftp
          HostName = "example.com"
          UserName = "user"
          Password = "mypassword"
          SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
      }
    
      $session = New-Object WinSCP.Session
    
      try
      {
          # Connect
          $session.Open($sessionOptions)
    
          # Upload
          $session.PutFiles("C:\FileDump\export.txt", "/Outbox/").Check()
      }
      finally
      {
          # Disconnect, clean up
          $session.Dispose()
      }
    

You can have WinSCP generate the PowerShell script for the upload for you:

  • Login to your server with WinSCP GUI;
  • Navigate to the target directory in the remote file panel;
  • Select the file for upload in the local file panel;
  • Invoke the Upload command;
  • On the Transfer options dialog, go to Transfer Settings > Generate Code;
  • On the Generate transfer code dialog, select the .NET assembly code tab;
  • Choose PowerShell language.

You will get a code like above with all session and transfer settings filled in.

Generate transfer code dialog

(I'm the author of WinSCP)

How to open a WPF Popup when another control is clicked, using XAML markup only?

I had some issues with the MouseDown part of this, but here is some code that might get your started.

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Control VerticalAlignment="Top">
            <Control.Template>
                <ControlTemplate>
                    <StackPanel>
                    <TextBox x:Name="MyText"></TextBox>
                    <Popup x:Name="Popup" PopupAnimation="Fade" VerticalAlignment="Top">
                        <Border Background="Red">
                            <TextBlock>Test Popup Content</TextBlock>
                        </Border>
                    </Popup>
                    </StackPanel>
                    <ControlTemplate.Triggers>
                        <EventTrigger RoutedEvent="UIElement.MouseEnter" SourceName="MyText">
                            <BeginStoryboard>
                                <Storyboard>
                                    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
                                        <DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="True"/>
                                    </BooleanAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                        <EventTrigger RoutedEvent="UIElement.MouseLeave" SourceName="MyText">
                            <BeginStoryboard>
                                <Storyboard>
                                    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
                                        <DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="False"/>
                                    </BooleanAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Control.Template>
        </Control>
    </Grid>
</Window>

Kill python interpeter in linux from the terminal

You can try the killall command:

killall python

Make a link in the Android browser start up my app?

You may want to consider a library to handle the deep link to your app:

https://github.com/airbnb/DeepLinkDispatch

You can add the intent filter on an annotated Activity like people suggested above. It will handle the routing and parsing of parameters for all of your deep links. For example, your MainActivity might have something like this:

@DeepLink("somePath/{useful_info_for_anton_app}")
public class MainActivity extends Activity {
   ...
}

It can also handle query parameters as well.

How to get TimeZone from android mobile?

Have you tried to use TimeZone.getDefault():

Most applications will use TimeZone.getDefault() which returns a TimeZone based on the time zone where the program is running.

Ref: http://developer.android.com/reference/java/util/TimeZone.html

Get RETURN value from stored procedure in SQL

Assign after the EXEC token:

DECLARE @returnValue INT

EXEC @returnValue = SP_One

How to split a string into a list?

text.split()

This should be enough to store each word in a list. words is already a list of the words from the sentence, so there is no need for the loop.

Second, it might be a typo, but you have your loop a little messed up. If you really did want to use append, it would be:

words.append(word)

not

word.append(words)

How to generate Javadoc from command line

Oracle provides some simple examples:

http://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html#CHDJBGFC

Assuming you are in ~/ and the java source tree is in ./saxon_source/net and you want to recurse through the whole source tree net is both a directory and the top package name.

mkdir saxon_docs
javadoc -d saxon_docs -sourcepath saxon_source -subpackages net

Accessing localhost:port from Android emulator

"BadRequest" is an error which usually got send by the server itself, see rfc 2616

10.4.1 400 Bad Request

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

So you got a working connection to the server, but your request doesn't fit the expecet form. I don't know how you create the connection, what headers are included (if there are any) – but thats what you should checking for.

If you need more help about, explain what your code is about and what it uses to connect to the Server, so we have the big picture.

Here is a question with the same Problem – the answer was that the content-type wasnt set in the header.

Redefine tab as 4 spaces

It depends on what you mean. Do you want actual tab characters in your file to appear 4 spaces wide, or by "tab" do you actually mean an indent, generated by pressing the tab key, which would result in the file literally containing (up to) 4 space characters for each "tab" you type?

Depending on your answer, one of the following sets of settings should work for you:

  • For tab characters that appear 4-spaces-wide:

    set tabstop=4
    

    If you're using actual tab character in your source code you probably also want these settings (these are actually the defaults, but you may want to set them defensively):

    set softtabstop=0 noexpandtab
    

    Finally, if you want an indent to correspond to a single tab, you should also use:

    set shiftwidth=4
    
  • For indents that consist of 4 space characters but are entered with the tab key:

    set tabstop=8 softtabstop=0 expandtab shiftwidth=4 smarttab
    

To make the above settings permanent add these lines to your vimrc.

In case you need to make adjustments, or would simply like to understand what these options all mean, here's a breakdown of what each option means:

tabstop

The width of a hard tabstop measured in "spaces" -- effectively the (maximum) width of an actual tab character.

shiftwidth

The size of an "indent". It's also measured in spaces, so if your code base indents with tab characters then you want shiftwidth to equal the number of tab characters times tabstop. This is also used by things like the =, > and < commands.

softtabstop

Setting this to a non-zero value other than tabstop will make the tab key (in insert mode) insert a combination of spaces (and possibly tabs) to simulate tab stops at this width.

expandtab

Enabling this will make the tab key (in insert mode) insert spaces instead of tab characters. This also affects the behavior of the retab command.

smarttab

Enabling this will make the tab key (in insert mode) insert spaces or tabs to go to the next indent of the next tabstop when the cursor is at the beginning of a line (i.e. the only preceding characters are whitespace).

For more details on any of these see :help 'optionname' in vim (e.g. :help 'tabstop')

Changing column names of a data frame

The new recommended way to do this is to use the setNames function. See ?setNames. Since this creates a new copy of the data.frame, be sure to assign the result to the original data.frame, if that is your intention.

data_frame <- setNames(data_frame, c("premium","change","newprice"))

Newer versions of R will give you warning if you use colnames in some of the ways suggested by earlier answers.

If this were a data.table instead, you could use the data.table function setnames, which can modify specific column names or a single column name by reference:

setnames(data_table, "old-name", "new-name")

"A referral was returned from the server" exception when accessing AD from C#

In my case I was seeing referrals when I was accessing AD via SSO with an account in a trusted domain. The problem went away when I connected with explicit credentials in the local domain.

i.e. I replaced

DirectoryEntry de = new DirectoryEntry("blah.com");

with

DirectoryEntry de = new DirectoryEntry("blah.com", "[email protected]", "supersecret");

and the problem went away.

How can I remove space (margin) above HTML header?

It is good practice when you start creating website to reset all the margins and paddings. So I recommend on start just to simple do:

* { margin: 0, padding: 0 }

This will make margins and paddings of all elements to be 0, and then you can style them as you wish, because each browser has a different default margin and padding of the elements.

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

On jenkins 2.x, with groovy plugin 2.0, running SystemGroovyScript I managed to get to build variables, as below:

def build = this.getProperty('binding').getVariable('build')
def listener = this.getProperty('binding').getVariable('listener')
def env = build.getEnvironment(listener)
println env.MY_VARIABLE

If you are using goovy from file, simple System.getenv('MY_VARIABLE') is sufficient

Use xml.etree.ElementTree to print nicely formatted xml files

You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:

>>> print(etree.tostring(root, pretty_print=True))
<root>
  <child1/>
  <child2/>
  <child3/>
</root>

MySQL Great Circle Distance (Haversine formula)

I have written a procedure that can calculate the same, but you have to enter the latitude and longitude in the respective table.

drop procedure if exists select_lattitude_longitude;

delimiter //

create procedure select_lattitude_longitude(In CityName1 varchar(20) , In CityName2 varchar(20))

begin

    declare origin_lat float(10,2);
    declare origin_long float(10,2);

    declare dest_lat float(10,2);
    declare dest_long float(10,2);

    if CityName1  Not In (select Name from City_lat_lon) OR CityName2  Not In (select Name from City_lat_lon) then 

        select 'The Name Not Exist or Not Valid Please Check the Names given by you' as Message;

    else

        select lattitude into  origin_lat from City_lat_lon where Name=CityName1;

        select longitude into  origin_long  from City_lat_lon where Name=CityName1;

        select lattitude into  dest_lat from City_lat_lon where Name=CityName2;

        select longitude into  dest_long  from City_lat_lon where Name=CityName2;

        select origin_lat as CityName1_lattitude,
               origin_long as CityName1_longitude,
               dest_lat as CityName2_lattitude,
               dest_long as CityName2_longitude;

        SELECT 3956 * 2 * ASIN(SQRT( POWER(SIN((origin_lat - dest_lat) * pi()/180 / 2), 2) + COS(origin_lat * pi()/180) * COS(dest_lat * pi()/180) * POWER(SIN((origin_long-dest_long) * pi()/180 / 2), 2) )) * 1.609344 as Distance_In_Kms ;

    end if;

end ;

//

delimiter ;

What does @media screen and (max-width: 1024px) mean in CSS?

It's limiting the styles defined there to the screen (e.g. not print or some other media) and is further limiting the scope to viewports which are 1024px or less in width.

http://www.css3.info/preview/media-queries/

Remove ALL white spaces from text

Regex for remove white space

\s+

_x000D_
_x000D_
var str = "Visit Microsoft!";
var res = str.replace(/\s+/g, "");
console.log(res);
_x000D_
_x000D_
_x000D_

or

[ ]+

_x000D_
_x000D_
var str = "Visit Microsoft!";
var res = str.replace(/[ ]+/g, "");
console.log(res);
_x000D_
_x000D_
_x000D_

Remove all white space at begin of string

^[ ]+

_x000D_
_x000D_
var str = "    Visit Microsoft!";
var res = str.replace(/^[ ]+/g, "");
console.log(res);
_x000D_
_x000D_
_x000D_

remove all white space at end of string

[ ]+$

_x000D_
_x000D_
var str = "Visit Microsoft!      ";
var res = str.replace(/[ ]+$/g, "");
console.log(res);
_x000D_
_x000D_
_x000D_

How to get the current time in milliseconds in C Programming

If you're on a Unix-like system, use gettimeofday and convert the result from microseconds to milliseconds.

Order a MySQL table by two columns

Default sorting is ascending, you need to add the keyword DESC to both your orders:

ORDER BY article_rating DESC, article_time DESC

What are valid values for the id attribute in HTML?

jQuery does handle any valid ID name. You just need to escape metacharacters (i.e., dots, semicolons, square brackets...). It's like saying that JavaScript has a problem with quotes only because you can't write

var name = 'O'Hara';

Selectors in jQuery API (see bottom note)

Enable 'xp_cmdshell' SQL Server

As listed in other answers, the trick (in SQL 2005 or later) is to change the global configuration settings for show advanced options and xp_cmdshell to 1, in that order.

Adding to this, if you want to preserve the previous values, you can read them from sys.configurations first, then apply them in reverse order at the end. We can also avoid unnecessary reconfigure calls:

declare @prevAdvancedOptions int
declare @prevXpCmdshell int

select @prevAdvancedOptions = cast(value_in_use as int) from sys.configurations where name = 'show advanced options'
select @prevXpCmdshell = cast(value_in_use as int) from sys.configurations where name = 'xp_cmdshell'

if (@prevAdvancedOptions = 0)
begin
    exec sp_configure 'show advanced options', 1
    reconfigure
end

if (@prevXpCmdshell = 0)
begin
    exec sp_configure 'xp_cmdshell', 1
    reconfigure
end

/* do work */

if (@prevXpCmdshell = 0)
begin
    exec sp_configure 'xp_cmdshell', 0
    reconfigure
end

if (@prevAdvancedOptions = 0)
begin
    exec sp_configure 'show advanced options', 0
    reconfigure
end

Note that this relies on SQL Server version 2005 or later (original question was for 2008).

Difference between numpy.array shape (R, 1) and (R,)

The shape is a tuple. If there is only 1 dimension the shape will be one number and just blank after a comma. For 2+ dimensions, there will be a number after all the commas.

# 1 dimension with 2 elements, shape = (2,). 
# Note there's nothing after the comma.
z=np.array([  # start dimension
    10,       # not a dimension
    20        # not a dimension
])            # end dimension
print(z.shape)

(2,)

# 2 dimensions, each with 1 element, shape = (2,1)
w=np.array([  # start outer dimension 
    [10],     # element is in an inner dimension
    [20]      # element is in an inner dimension
])            # end outer dimension
print(w.shape)

(2,1)

How to navigate to a section of a page

Use an call thru section, it works

<div id="content">
     <section id="home">
               ...
     </section>

Call the above the thru

 <a href="#home">page1</a>

Scrolling needs jquery paste this.. on above to ending body closing tag..

<script>
  $(function() {
      $('a[href*=#]:not([href=#])').click(function() {
          if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
              var target = $(this.hash);
              target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
              if (target.length) {
                  $('html,body').animate({
                      scrollTop: target.offset().top
                  }, 1000);
                  return false;
              }
          }
      });
  });
</script>

Parse String to Date with Different Format in Java

Simple way to format a date and convert into string

    Date date= new Date();

    String dateStr=String.format("%td/%tm/%tY", date,date,date);

    System.out.println("Date with format of dd/mm/dd: "+dateStr);

output:Date with format of dd/mm/dd: 21/10/2015

Swift addsubview and remove it

Tested this code using XCode 8 and Swift 3

To Add Custom View to SuperView use:

self.view.addSubview(myView)

To Remove Custom View from Superview use:

self.view.willRemoveSubview(myView)

How to get the path of the batch script in Windows?

%~dp0 will be the directory. Here's some documentation on all of the path modifiers. Fun stuff :-)

To remove the final backslash, you can use the :n,m substring syntax, like so:

SET mypath=%~dp0
echo %mypath:~0,-1%

I don't believe there's a way to combine the %0 syntax with the :~n,m syntax, unfortunately.

What is and how to fix System.TypeInitializationException error?

Had a simular issue getting the same exception. Took some time locating. In my case I had a static utility class with a constructor that threw the exception (wrapping it). So my issue was in the static constructor.

Best way to format multiple 'or' conditions in an if statement (Java)

With Java 8, you could use a primitive stream:

if (IntStream.of(12, 16, 19).anyMatch(i -> i == x))

but this may have a slight overhead (or not), depending on the number of comparisons.

How do I use System.getProperty("line.separator").toString()?

On Windows, line.separator is a CR/LF combination (reference here).

The Java String.split() method takes a regular expression. So I think there's some confusion here.

How to check sbt version?

In SBT 0.13 and above, you can use the sbtVersion task (as pointed out by @steffen) or about command (as pointed out by @mark-harrah)

There's a difference how the sbtVersion task works in and outside a SBT project. When in a SBT project, sbtVersion displays the version of SBT used by the project and its subprojects.

$ sbt sbtVersion
[info] Loading global plugins from /Users/jacek/.sbt/0.13/plugins
[info] Updating {file:/Users/jacek/.sbt/0.13/plugins/}global-plugins...
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.
[info] Loading project definition from /Users/jacek/oss/scalania/project
[info] Set current project to scalania (in build file:/Users/jacek/oss/scalania/)
[info] exercises/*:sbtVersion
[info]  0.13.1-RC5
[info] scalania/*:sbtVersion
[info]  0.13.1-RC5

It's set in project/build.properties:

jacek:~/oss/scalania
$ cat project/build.properties
sbt.version=0.13.1-RC5

The same task executed outside a SBT project shows the current version of the executable itself.

jacek:~
$ sbt sbtVersion
[info] Loading global plugins from /Users/jacek/.sbt/0.13/plugins
[info] Updating {file:/Users/jacek/.sbt/0.13/plugins/}global-plugins...
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.
[info] Set current project to jacek (in build file:/Users/jacek/)
[info] 0.13.0

When you're outside, the about command seems to be a better fit as it shows the sbt version as well as Scala's and available plugins.

jacek:~
$ sbt about
[info] Loading global plugins from /Users/jacek/.sbt/0.13/plugins
[info] Set current project to jacek (in build file:/Users/jacek/)
[info] This is sbt 0.13.0
[info] The current project is {file:/Users/jacek/}jacek 0.1-SNAPSHOT
[info] The current project is built against Scala 2.10.2
[info] Available Plugins: com.typesafe.sbt.SbtGit, com.typesafe.sbt.SbtProguard, growl.GrowlingTests, org.sbtidea.SbtIdeaPlugin, com.timushev.sbt.updates.UpdatesPlugin
[info] sbt, sbt plugins, and build definitions are using Scala 2.10.2

You may want to run 'help about' to read its documentation:

jacek:~
$ sbt 'help about'
[info] Loading global plugins from /Users/jacek/.sbt/0.13/plugins
[info] Set current project to jacek (in build file:/Users/jacek/)
Displays basic information about sbt and the build.

For the sbtVersion setting, the inspect command can help.

$ sbt 'inspect sbtVersion'
[info] Loading global plugins from /Users/jacek/.sbt/0.13/plugins
[info] Set current project to jacek (in build file:/Users/jacek/)
[info] Setting: java.lang.String = 0.13.0
[info] Description:
[info]  Provides the version of sbt.  This setting should be not be modified.
[info] Provided by:
[info]  */*:sbtVersion
[info] Defined at:
[info]  (sbt.Defaults) Defaults.scala:67
[info] Delegates:
[info]  *:sbtVersion
[info]  {.}/*:sbtVersion
[info]  */*:sbtVersion
[info] Related:
[info]  */*:sbtVersion

The version setting that people seem to expect to inspect to know the SBT version is to set The version/revision of the current module.

$ sbt 'inspect version'
[info] Loading global plugins from /Users/jacek/.sbt/0.13/plugins
[info] Set current project to jacek (in build file:/Users/jacek/)
[info] Setting: java.lang.String = 0.1-SNAPSHOT
[info] Description:
[info]  The version/revision of the current module.
[info] Provided by:
[info]  */*:version
[info] Defined at:
[info]  (sbt.Defaults) Defaults.scala:102
[info] Reverse dependencies:
[info]  *:projectId
[info]  *:isSnapshot
[info] Delegates:
[info]  *:version
[info]  {.}/*:version
[info]  */*:version
[info] Related:
[info]  */*:version

When used in a SBT project the tasks/settings may show different outputs.

What are the differences between Visual Studio Code and Visual Studio?

Visual Studio (full version) is a "full-featured" and "convenient" development environment.

Visual Studio (free "Express" versions - only until 2017) are feature-centered and simplified versions of the full version. Feature-centered meaning that there are different versions (Visual Studio Web Developer, Visual Studio C#, etc.) depending on your goal.

Visual Studio (free Community edition - since 2015) is a simplified version of the full version and replaces the separated express editions used before 2015.

Visual Studio Code (VSCode) is a cross-platform (Linux, Mac OS, Windows) editor that can be extended with plugins to your needs.

For example, if you want to create an ASP.NET application using Visual Studio Code you need to perform several steps on your own to setup the project. There is a separate tutorial for each OS.

laravel 5.4 upload image

This code will store the image in database.

$('#image').change(function(){
        // FileReader function for read the file.
        let reader = new FileReader();
        var base64;
        reader.readAsDataURL(this.files[0]); 

        //Read File
        let filereader = new FileReader();
        var selectedFile = this.files[0];

        // Onload of file read the file content
        filereader.onload = function(fileLoadedEvent) {
            base64 = fileLoadedEvent.target.result;
            $("#pimage").val(JSON.stringify(base64));
        };

        filereader.readAsDataURL(selectedFile); 
 });

HTML content should be like this.

<div class="col-xs-12 col-sm-4 col-md-4 user_frm form-group">
        <input id="image" type="file" class="inputMaterial" name="image">        
        <input type="hidden" id="pimage" name="pimage" value="">
        <span class="bar"></span>
    </div>

Store image data in database like this:

//property_image longtext(database field type)

 $data= array(
      'property_image' => trim($request->get('pimage'),'"')
 );

Display image:

<img src="{{$result->property_image}}" >

how to insert value into DataGridView Cell?

You can access any DGV cell as follows :

dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;

But usually it's better to use databinding : you bind the DGV to a data source (DataTable, collection...) through the DataSource property, and only work on the data source itself. The DataGridView will automatically reflect the changes, and changes made on the DataGridView will be reflected on the data source

‘ant’ is not recognized as an internal or external command

When Environment variables are changed log off and log in again so that it will be applied.

Generate a random number in the range 1 - 10

If you are using SQL Server then correct way to get integer is

SELECT Cast(RAND()*(b-a)+a as int);

Where

  • 'b' is the upper limit
  • 'a' is lower limit

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Get the element triggering an onclick event in jquery?

You can pass the inline handler the this keyword, obtaining the element which fired the event.

like,

onclick="confirmSubmit(this);"

"relocation R_X86_64_32S against " linking Error

Relocation R_X86_64_PC32 against undefined symbol , usually happens when LDFLAGS are set with hardening and CFLAGS not .
Maybe just user error:
If you are using -specs=/usr/lib/rpm/redhat/redhat-hardened-ld at link time, you also need to use -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 at compile time, and as you are compiling and linking at the same time, you need either both, or drop the -specs=/usr/lib/rpm/redhat/redhat-hardened-ld . Common fixes :
https://bugzilla.redhat.com/show_bug.cgi?id=1304277#c3
https://github.com/rpmfusion/lxdream/blob/master/lxdream-0.9.1-implicit.patch

How to represent a DateTime in Excel

Excel expects dates and times to be stored as a floating point number whose value depends on the Date1904 setting of the workbook, plus a number format such as "mm/dd/yyyy" or "hh:mm:ss" or "mm/dd/yyyy hh:mm:ss" so that the number is displayed to the user as a date / time.

Using SpreadsheetGear for .NET you can do this: worksheet.Cells["A1"].Value = DateTime.Now;

This will convert the DateTime to a double which is the underlying type which Excel uses for a Date / Time, and then format the cell with a default date and / or time number format automatically depending on the value.

SpreadsheetGear also has IWorkbook.DateTimeToNumber(DateTime) and NumberToDateTime(double) methods which convert from .NET DateTime objects to a double which Excel can use.

I would expect XlsIO to have something similar.

Disclaimer: I own SpreadsheetGear LLC

How to use pip with python 3.4 on windows?

From the same page

Note: To avoid conflicts between parallel Python 2 and Python 3 installations, only the versioned pip3 and pip3.4 commands are bootstrapped by default when ensurepip is invoked directly - the --default-pip option is needed to also request the unversioned pip command. pyvenv and the Windows installer ensure that the unqualified pip command is made available in those environments, and pip can always be invoked via the -m switch rather than directly to avoid ambiguity on systems with multiple Python installations.

So try pip3 or pip3.4 in Command Prompt.

Also, ensure that environment variable are set for pip command, if you missed to opt-in for automatic PATH configuration.

Amazon Interview Question: Design an OO parking lot

In an Object Oriented parking lot, there will be no need for attendants because the cars will "know how to park".

Finding a usable car on the lot will be difficult; the most common models will either have all their moving parts exposed as public member variables, or they will be "fully encapsulated" cars with no windows or doors.

The parking spaces in our OO parking lot will not match the size and shape of the cars (an "impediance mismatch" between the spaces and the cars)

License tags on our lot will have a dot between each letter and digit. Handicaped parking will only be available for licenses beginning with "_", and licenses beginning with "m_" will be towed.

Login to website, via C#

You can simplify things quite a bit by creating a class that derives from WebClient, overriding its GetWebRequest method and setting a CookieContainer object on it. If you always set the same CookieContainer instance, then cookie management will be handled automatically for you.

But the only way to get at the HttpWebRequest before it is sent is to inherit from WebClient and override that method.

public class CookieAwareWebClient : WebClient
{
    private CookieContainer cookie = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = cookie;
        }
        return request;
    }
}

var client = new CookieAwareWebClient();
client.BaseAddress = @"https://www.site.com/any/base/url/";
var loginData = new NameValueCollection();
loginData.Add("login", "YourLogin");
loginData.Add("password", "YourPassword");
client.UploadValues("login.php", "POST", loginData);

//Now you are logged in and can request pages    
string htmlSource = client.DownloadString("index.php");

How to add /usr/local/bin in $PATH on Mac

To make the edited value of path persists in the next sessions

cd ~/
touch .bash_profile
open .bash_profile

That will open the .bash_profile in editor, write inside the following after adding what you want to the path separating each value by column.

export PATH=$PATH:/usr/local/git/bin:/usr/local/bin:

Save, exit, restart your terminal and enjoy

How to set and reference a variable in a Jenkinsfile

A complete example for scripted pipepline:

       stage('Build'){
            withEnv(["GOPATH=/ws","PATH=/ws/bin:${env.PATH}"]) {
                sh 'bash build.sh'
            }
        }

How to change Angular CLI favicon

An editor (in my case IDEA 2020.2) can sometimes add src/ prefix to icon location in href. I mean

 <link rel="icon" ... href="src/favicon.ico">

instead of

  <link rel="icon" ... href="favicon.ico">

So in this case you should remove this src/ part in href. This solved the problem for me.

Animate background image change with jQuery

Have a look at this jQuery plugin from OvalPixels.

It may do the trick.

How to get enum value by string or int

No, you don't want a generic method. This is much easier:

MyEnum myEnum = (MyEnum)myInt;

MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), myString);

I think it will also be faster.

No space left on device

Such difference between the output of du -sh and df -h may happen if some large file has been deleted, but is still opened by some process. Check with the command lsof | grep deleted to see which processes have opened descriptors to deleted files. You can restart the process and the space will be freed.

OSError [Errno 22] invalid argument when use open() in Python

import pandas as pd
df = pd.read_excel ('C:/Users/yourlogin/new folder/file.xlsx')
print (df)

Store multiple values in single key in json

Use arrays:

{
    "number": ["1", "2", "3"],
    "alphabet": ["a", "b", "c"]
}

You can the access the different values from their position in the array. Counting starts at left of array at 0. myJsonObject["number"][0] == 1 or myJsonObject["alphabet"][2] == 'c'

Convert datetime value into string

Try this:

concat(left(datefield,10),left(timefield,8))
  • 10 char on date field based on full date yyyy-MM-dd.

  • 8 char on time field based on full time hh:mm:ss.

It depends on the format you want it. normally you can use script above and you can concat another field or string as you want it.

Because actually date and time field tread as string if you read it. But of course you will got error while update or insert it.

POST string to ASP.NET Web Api application - returns null

i meet this problem, and find this article. http://www.jasonwatmore.com/post/2014/04/18/Post-a-simple-string-value-from-AngularJS-to-NET-Web-API.aspx

The solution I found was to simply wrap the string value in double quotes in your js post

works like a charm! FYI

jQuery detect if string contains something

You could use String.prototype.indexOf to accomplish that. Try something like this:

_x000D_
_x000D_
$('.type').keyup(function() {_x000D_
  var v = $(this).val();_x000D_
  if (v.indexOf('> <') !== -1) {_x000D_
    console.log('contains > <');_x000D_
  }_x000D_
  console.log(v);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea class="type"></textarea>
_x000D_
_x000D_
_x000D_

Update

Modern browsers also have a String.prototype.includes method.

How to run a makefile in Windows?

You can install GNU make with chocolatey, a well-maintained package manager, which will add make to the global path and runs on all CLIs (powershell, git bash, cmd, etc…) saving you a ton of time in both maintenance and initial setup to get make running.

  1. Install the chocolatey package manager for Windows
    compatible to Windows 7+ / Windows Server 2003+

  2. Run choco install make

I am not affiliated with choco, but I highly recommend it, so far it has never let me down and I do have a talent for breaking software unintentionally.

Recommendation for compressing JPG files with ImageMagick

Just saying for those who using Imagick class in PHP:

$im -> gaussianBlurImage(0.8, 10);      //blur
$im -> setImageCompressionQuality(85);  //set compress quality to 85

How do I vertically align something inside a span tag?

Use line-height:50px; instead of height. That should do the trick ;)