Programs & Examples On #Line

The shortest distance between two points. Or, a row of characters in text output.

Line Break in XML formatting?

Use \n for a line break and \t if you want to insert a tab.

You can also use some XML tags for basic formatting: <b> for bold text, <i> for italics, and <u> for underlined text.

Other formatting options are shown in this article on the Android Developers' site:
https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling

How do you run a command for each line of a file?

I see that you tagged bash, but Perl would also be a good way to do this:

perl -p -e '`chmod 755 $_`' file.txt

You could also apply a regex to make sure you're getting the right files, e.g. to only process .txt files:

perl -p -e 'if(/\.txt$/) `chmod 755 $_`' file.txt

To "preview" what's happening, just replace the backticks with double quotes and prepend print:

perl -p -e 'if(/\.txt$/) print "chmod 755 $_"' file.txt

C read file line by line

If your task is not to invent the line-by-line reading function, but just to read the file line-by-line, you may use a typical code snippet involving the getline() function (see the manual page here):

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;

    fp = fopen("/etc/motd", "r");
    if (fp == NULL)
        exit(EXIT_FAILURE);

    while ((read = getline(&line, &len, fp)) != -1) {
        printf("Retrieved line of length %zu:\n", read);
        printf("%s", line);
    }

    fclose(fp);
    if (line)
        free(line);
    exit(EXIT_SUCCESS);
}

How can I format a list to print each element on a separate line in python?

Use str.join:

In [27]: mylist = ['10', '12', '14']

In [28]: print '\n'.join(mylist)
10
12
14

How to make a new line or tab in <string> XML (eclipse/android)?

\n didn't work for me. So I used <br></br> HTML tag

    <string name="message_register_success">
Sign up is complete. <br></br>
 Enjoy a new shopping life at MageMobile!!
</string>

How do you make div elements display inline?

Just use a wrapper div with "float: left" and put boxes inside also containing float: left:

CSS:

wrapperline{
width: 300px;
float: left;
height: 60px;
background-color:#CCCCCC;}

.boxinside{
width: 50px;
float: left;
height: 50px;
margin: 5px;
background-color:#9C0;
float:left;}

HTML:

<div class="wrapperline">
<div class="boxinside">Box 1</div>
<div class="boxinside">Box 1</div>
<div class="boxinside">Box 1</div>
<div class="boxinside">Box 1</div>
<div class="boxinside">Box 1</div>
</div>

draw diagonal lines in div background with CSS

You can do it something like this:

<style>
    .background {
        background-color: #BCBCBC;
        width: 100px;
        height: 50px;
        padding: 0; 
        margin: 0
    }
    .line1 {
        width: 112px;
        height: 47px;
        border-bottom: 1px solid red;
        -webkit-transform:
            translateY(-20px)
            translateX(5px)
            rotate(27deg); 
        position: absolute;
        /* top: -20px; */
    }
    .line2 {
        width: 112px;
        height: 47px;
        border-bottom: 1px solid green;
        -webkit-transform:
            translateY(20px)
            translateX(5px)
            rotate(-26deg);
        position: absolute;
        top: -33px;
        left: -13px;
    }
</style>
<div class="background">
    <div class="line1"></div>
    <div class="line2"></div>
</div>

Here is a jsfiddle.

Improved version of answer for your purpose.

How do I compute the intersection point of two lines?

Using formula from: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection

 def findIntersection(x1,y1,x2,y2,x3,y3,x4,y4):
        px= ( (x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4) ) / ( (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4) ) 
        py= ( (x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4) ) / ( (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4) )
        return [px, py]

Add centered text to the middle of a <hr/>-like line

Responsive, transparent background, variable height and style of divider, variable position of text, adjustable distance between divider and text. Can also be applied multiple times with different selectors for multiple divider styles in same project.
SCSS below.

Markup (HTML):

<div class="divider" text-position="right">Divider</div>

CSS:

.divider {
  display: flex;
  align-items: center;
  padding: 0 1rem;
}

.divider:before,
.divider:after {
  content: '';
  flex: 0 1 100%;
  border-bottom: 5px dotted #ccc;
  margin: 0 1rem;
}

.divider:before {
  margin-left: 0;
}

.divider:after {
  margin-right: 0;
}

.divider[text-position="right"]:after,
.divider[text-position="left"]:before {
  content: none;
}

Without text-position it defaults to center.

Demo:

_x000D_
_x000D_
.divider {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  padding: 0 1rem;_x000D_
}_x000D_
_x000D_
.divider:before,_x000D_
.divider:after {_x000D_
  content: '';_x000D_
  flex: 0 1 100%;_x000D_
  border-bottom: 5px dotted #ccc;_x000D_
  margin: 0 1rem;_x000D_
}_x000D_
_x000D_
.divider:before {_x000D_
  margin-left: 0;_x000D_
}_x000D_
_x000D_
.divider:after {_x000D_
  margin-right: 0;_x000D_
}_x000D_
_x000D_
.divider[text-position="right"]:after,_x000D_
.divider[text-position="left"]:before {_x000D_
  content: none;_x000D_
}
_x000D_
<span class="divider" text-position="left">Divider</span>_x000D_
<h2 class="divider">Divider</h2>_x000D_
<div class="divider" text-position="right">Divider</div>
_x000D_
_x000D_
_x000D_

And SCSS, to modify it quickly:

$divider-selector    : ".divider";
$divider-border-color: rgba(0,0,0,.21);
$divider-padding     : 1rem;
$divider-border-width: 1px;
$divider-border-style: solid;
$divider-max-width   : 100%;

#{$divider-selector} {
    display: flex;
    align-items: center;
    padding: 0 $divider-padding;
    max-width: $divider-max-width;
    margin-left: auto;
    margin-right: auto;

    &:before,
    &:after {
        content: '';
        flex: 0 1 100%;
        border-bottom: $divider-border-width $divider-border-style $divider-border-color;
        margin: 0 $divider-padding;
        transform: translateY(#{$divider-border-width} / 2)
    }

    &:before {
        margin-left: 0;
    }

    &:after {
        margin-right: 0;
    }

    &[text-position="right"]:after,
    &[text-position="left"]:before {
        content: none;
    }
}

fiddle here.

Remove lines that contain certain string

to_skip = ("bad", "naughty")
out_handle = open("testout", "w")

with open("testin", "r") as handle:
    for line in handle:
        if set(line.split(" ")).intersection(to_skip):
            continue
        out_handle.write(line)
out_handle.close()

Search and get a line in Python

you mentioned "entire line" , so i assumed mystring is the entire line.

if "token" in mystring:
    print(mystring)

however if you want to just get "token qwerty",

>>> mystring="""
...     qwertyuiop
...     asdfghjkl
...
...     zxcvbnm
...     token qwerty
...
...     asdfghjklñ
... """
>>> for item in mystring.split("\n"):
...  if "token" in item:
...     print (item.strip())
...
token qwerty

Making PHP var_dump() values display one line per value

Personally I like the replacement function provided by Symfony's var dumper component

Install with composer require symfony/var-dumper and just use dump($var)

It takes care of the rest. I believe there's also a bit of JS injected there to allow you to interact with the output a bit.

Reading a file line by line in Go

Example from this gist

func readLine(path string) {
  inFile, err := os.Open(path)
  if err != nil {
     fmt.Println(err.Error() + `: ` + path)
     return
  }
  defer inFile.Close()

  scanner := bufio.NewScanner(inFile)
  for scanner.Scan() {
    fmt.Println(scanner.Text()) // the line
  }
}

but this gives an error when there is a line that larger than Scanner's buffer.

When that happened, what I do is use reader := bufio.NewReader(inFile) create and concat my own buffer either using ch, err := reader.ReadByte() or len, err := reader.Read(myBuffer)

Another way that I use (replace os.Stdin with file like above), this one concats when lines are long (isPrefix) and ignores empty lines:


func readLines() []string {
  r := bufio.NewReader(os.Stdin)
  bytes := []byte{}
  lines := []string{}
  for {
    line, isPrefix, err := r.ReadLine()
    if err != nil {
      break
    }
    bytes = append(bytes, line...)
    if !isPrefix {
      str := strings.TrimSpace(string(bytes))
      if len(str) > 0 {
        lines = append(lines, str)
        bytes = []byte{}
      }
    }
  }
  if len(bytes) > 0 {
    lines = append(lines, string(bytes))
  }
  return lines
}

Line Break in XML?

<description><![CDATA[first line<br/>second line<br/>]]></description>

Go to first line in a file in vim?

If you are using gvim, you could just hit Ctrl + Home to go the first line. Similarly, Ctrl + End goes to the last line.

HTML5 canvas ctx.fillText won't do line breaks?

I just extended the CanvasRenderingContext2D adding two functions: mlFillText and mlStrokeText.

You can find the last version in GitHub:

With this functions you can fill / stroke miltiline text in a box. You can align the text verticaly and horizontaly. (It takes in account \n's and can also justify the text).

The prototypes are:

function mlFillText(text,x,y,w,h,vAlign,hAlign,lineheight); function mlStrokeText(text,x,y,w,h,vAlign,hAlign,lineheight);

Where vAlign can be: "top", "center" or "button" And hAlign can be: "left", "center", "right" or "justify"

You can test the lib here: http://jsfiddle.net/4WRZj/1/

enter image description here

Here is the code of the library:

// Library: mltext.js
// Desciption: Extends the CanvasRenderingContext2D that adds two functions: mlFillText and mlStrokeText.
//
// The prototypes are: 
//
// function mlFillText(text,x,y,w,h,vAlign,hAlign,lineheight);
// function mlStrokeText(text,x,y,w,h,vAlign,hAlign,lineheight);
// 
// Where vAlign can be: "top", "center" or "button"
// And hAlign can be: "left", "center", "right" or "justify"
// Author: Jordi Baylina. (baylina at uniclau.com)
// License: GPL
// Date: 2013-02-21

function mlFunction(text, x, y, w, h, hAlign, vAlign, lineheight, fn) {
    text = text.replace(/[\n]/g, " \n ");
    text = text.replace(/\r/g, "");
    var words = text.split(/[ ]+/);
    var sp = this.measureText(' ').width;
    var lines = [];
    var actualline = 0;
    var actualsize = 0;
    var wo;
    lines[actualline] = {};
    lines[actualline].Words = [];
    i = 0;
    while (i < words.length) {
        var word = words[i];
        if (word == "\n") {
            lines[actualline].EndParagraph = true;
            actualline++;
            actualsize = 0;
            lines[actualline] = {};
            lines[actualline].Words = [];
            i++;
        } else {
            wo = {};
            wo.l = this.measureText(word).width;
            if (actualsize === 0) {
                while (wo.l > w) {
                    word = word.slice(0, word.length - 1);
                    wo.l = this.measureText(word).width;
                }
                if (word === "") return; // I can't fill a single character
                wo.word = word;
                lines[actualline].Words.push(wo);
                actualsize = wo.l;
                if (word != words[i]) {
                    words[i] = words[i].slice(word.length, words[i].length);
                } else {
                    i++;
                }
            } else {
                if (actualsize + sp + wo.l > w) {
                    lines[actualline].EndParagraph = false;
                    actualline++;
                    actualsize = 0;
                    lines[actualline] = {};
                    lines[actualline].Words = [];
                } else {
                    wo.word = word;
                    lines[actualline].Words.push(wo);
                    actualsize += sp + wo.l;
                    i++;
                }
            }
        }
    }
    if (actualsize === 0) lines[actualline].pop();
    lines[actualline].EndParagraph = true;

    var totalH = lineheight * lines.length;
    while (totalH > h) {
        lines.pop();
        totalH = lineheight * lines.length;
    }

    var yy;
    if (vAlign == "bottom") {
        yy = y + h - totalH + lineheight;
    } else if (vAlign == "center") {
        yy = y + h / 2 - totalH / 2 + lineheight;
    } else {
        yy = y + lineheight;
    }

    var oldTextAlign = this.textAlign;
    this.textAlign = "left";

    for (var li in lines) {
        var totallen = 0;
        var xx, usp;
        for (wo in lines[li].Words) totallen += lines[li].Words[wo].l;
        if (hAlign == "center") {
            usp = sp;
            xx = x + w / 2 - (totallen + sp * (lines[li].Words.length - 1)) / 2;
        } else if ((hAlign == "justify") && (!lines[li].EndParagraph)) {
            xx = x;
            usp = (w - totallen) / (lines[li].Words.length - 1);
        } else if (hAlign == "right") {
            xx = x + w - (totallen + sp * (lines[li].Words.length - 1));
            usp = sp;
        } else { // left
            xx = x;
            usp = sp;
        }
        for (wo in lines[li].Words) {
            if (fn == "fillText") {
                this.fillText(lines[li].Words[wo].word, xx, yy);
            } else if (fn == "strokeText") {
                this.strokeText(lines[li].Words[wo].word, xx, yy);
            }
            xx += lines[li].Words[wo].l + usp;
        }
        yy += lineheight;
    }
    this.textAlign = oldTextAlign;
}

(function mlInit() {
    CanvasRenderingContext2D.prototype.mlFunction = mlFunction;

    CanvasRenderingContext2D.prototype.mlFillText = function (text, x, y, w, h, vAlign, hAlign, lineheight) {
        this.mlFunction(text, x, y, w, h, hAlign, vAlign, lineheight, "fillText");
    };

    CanvasRenderingContext2D.prototype.mlStrokeText = function (text, x, y, w, h, vAlign, hAlign, lineheight) {
        this.mlFunction(text, x, y, w, h, hAlign, vAlign, lineheight, "strokeText");
    };
})();

And here is the use example:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

var T = "This is a very long line line with a CR at the end.\n This is the second line.\nAnd this is the last line.";
var lh = 12;

ctx.lineWidth = 1;

ctx.mlFillText(T, 10, 10, 100, 100, 'top', 'left', lh);
ctx.strokeRect(10, 10, 100, 100);

ctx.mlFillText(T, 110, 10, 100, 100, 'top', 'center', lh);
ctx.strokeRect(110, 10, 100, 100);

ctx.mlFillText(T, 210, 10, 100, 100, 'top', 'right', lh);
ctx.strokeRect(210, 10, 100, 100);

ctx.mlFillText(T, 310, 10, 100, 100, 'top', 'justify', lh);
ctx.strokeRect(310, 10, 100, 100);

ctx.mlFillText(T, 10, 110, 100, 100, 'center', 'left', lh);
ctx.strokeRect(10, 110, 100, 100);

ctx.mlFillText(T, 110, 110, 100, 100, 'center', 'center', lh);
ctx.strokeRect(110, 110, 100, 100);

ctx.mlFillText(T, 210, 110, 100, 100, 'center', 'right', lh);
ctx.strokeRect(210, 110, 100, 100);

ctx.mlFillText(T, 310, 110, 100, 100, 'center', 'justify', lh);
ctx.strokeRect(310, 110, 100, 100);

ctx.mlFillText(T, 10, 210, 100, 100, 'bottom', 'left', lh);
ctx.strokeRect(10, 210, 100, 100);

ctx.mlFillText(T, 110, 210, 100, 100, 'bottom', 'center', lh);
ctx.strokeRect(110, 210, 100, 100);

ctx.mlFillText(T, 210, 210, 100, 100, 'bottom', 'right', lh);
ctx.strokeRect(210, 210, 100, 100);

ctx.mlFillText(T, 310, 210, 100, 100, 'bottom', 'justify', lh);
ctx.strokeRect(310, 210, 100, 100);

ctx.mlStrokeText("Yo can also use mlStrokeText!", 0 , 310 , 420, 30, 'center', 'center', lh);

Draw a connecting line between two elements

js-graph.it supports this use case, as seen by its getting started guide, supporting dragging elements without connection overlaps. Doesn't seem like it supports editing/creating connections. Doesn't seem it is maintained anymore.

How to add a line break in an Android TextView?

Try to double-check your localizations. Possible, you trying to edit one file (localization), but actually program using another, just like in my case. The default system language is russian, while I trying to edit english localization.

In my case, working solution is to use "\n" as line separator:

    <string name="string_one">line one.
    \nline two;
    \nline three.</string>

Get line number while using grep

grep -nr "search string" directory

This gives you the line with the line number.

Java Replace Line In Text File

Well you would need to get a file with JFileChooser and then read through the lines of the file using a scanner and the hasNext() function

http://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html

once you do that you can save the line into a variable and manipulate the contents.

Circle line-segment collision detection algorithm?

Here is a solution written in golang. The method is similar to some other answers posted here, but not quite the same. It is easy to implement, and has been tested. Here are the steps:

  1. Translate coordinates so that the circle is at the origin.
  2. Express the line segment as parametrized functions of t for both the x and y coordinates. If t is 0, the function's values are one end point of the segment, and if t is 1, the function's values are the other end point.
  3. Solve, if possible, the quadratic equation resulting from constraining values of t that produce x, y coordinates with distances from the origin equal to the circle's radius.
  4. Throw out solutions where t is < 0 or > 1 ( <= 0 or >= 1 for an open segment). Those points are not contained in the segment.
  5. Translate back to original coordinates.

The values for A, B, and C for the quadratic are derived here, where (n-et) and (m-dt) are the equations for the line's x and y coordinates, respectively. r is the radius of the circle.

(n-et)(n-et) + (m-dt)(m-dt) = rr
nn - 2etn + etet + mm - 2mdt + dtdt = rr
(ee+dd)tt - 2(en + dm)t + nn + mm - rr = 0

Therefore A = ee+dd, B = - 2(en + dm), and C = nn + mm - rr.

Here is the golang code for the function:

package geom

import (
    "math"
)

// SegmentCircleIntersection return points of intersection between a circle and
// a line segment. The Boolean intersects returns true if one or
// more solutions exist. If only one solution exists, 
// x1 == x2 and y1 == y2.
// s1x and s1y are coordinates for one end point of the segment, and
// s2x and s2y are coordinates for the other end of the segment.
// cx and cy are the coordinates of the center of the circle and
// r is the radius of the circle.
func SegmentCircleIntersection(s1x, s1y, s2x, s2y, cx, cy, r float64) (x1, y1, x2, y2 float64, intersects bool) {
    // (n-et) and (m-dt) are expressions for the x and y coordinates
    // of a parameterized line in coordinates whose origin is the
    // center of the circle.
    // When t = 0, (n-et) == s1x - cx and (m-dt) == s1y - cy
    // When t = 1, (n-et) == s2x - cx and (m-dt) == s2y - cy.
    n := s2x - cx
    m := s2y - cy

    e := s2x - s1x
    d := s2y - s1y

    // lineFunc checks if the  t parameter is in the segment and if so
    // calculates the line point in the unshifted coordinates (adds back
    // cx and cy.
    lineFunc := func(t float64) (x, y float64, inBounds bool) {
        inBounds = t >= 0 && t <= 1 // Check bounds on closed segment
        // To check bounds for an open segment use t > 0 && t < 1
        if inBounds { // Calc coords for point in segment
            x = n - e*t + cx
            y = m - d*t + cy
        }
        return
    }

    // Since we want the points on the line distance r from the origin,
    // (n-et)(n-et) + (m-dt)(m-dt) = rr.
    // Expanding and collecting terms yeilds the following quadratic equation:
    A, B, C := e*e+d*d, -2*(e*n+m*d), n*n+m*m-r*r

    D := B*B - 4*A*C // discriminant of quadratic
    if D < 0 {
        return // No solution
    }
    D = math.Sqrt(D)

    var p1In, p2In bool
    x1, y1, p1In = lineFunc((-B + D) / (2 * A)) // First root
    if D == 0.0 {
        intersects = p1In
        x2, y2 = x1, y1
        return // Only possible solution, quadratic has one root.
    }

    x2, y2, p2In = lineFunc((-B - D) / (2 * A)) // Second root

    intersects = p1In || p2In
    if p1In == false { // Only x2, y2 may be valid solutions
        x1, y1 = x2, y2
    } else if p2In == false { // Only x1, y1 are valid solutions
        x2, y2 = x1, y1
    }
    return
}

I tested it with this function, which confirms that solution points are within the line segment and on the circle. It makes a test segment and sweeps it around the given circle:

package geom_test

import (
    "testing"

    . "**put your package path here**"
)

func CheckEpsilon(t *testing.T, v, epsilon float64, message string) {
    if v > epsilon || v < -epsilon {
        t.Error(message, v, epsilon)
        t.FailNow()
    }
}

func TestSegmentCircleIntersection(t *testing.T) {
    epsilon := 1e-10      // Something smallish
    x1, y1 := 5.0, 2.0    // segment end point 1
    x2, y2 := 50.0, 30.0  // segment end point 2
    cx, cy := 100.0, 90.0 // center of circle
    r := 80.0

    segx, segy := x2-x1, y2-y1

    testCntr, solutionCntr := 0, 0

    for i := -100; i < 100; i++ {
        for j := -100; j < 100; j++ {
            testCntr++
            s1x, s2x := x1+float64(i), x2+float64(i)
            s1y, s2y := y1+float64(j), y2+float64(j)

            sc1x, sc1y := s1x-cx, s1y-cy
            seg1Inside := sc1x*sc1x+sc1y*sc1y < r*r
            sc2x, sc2y := s2x-cx, s2y-cy
            seg2Inside := sc2x*sc2x+sc2y*sc2y < r*r

            p1x, p1y, p2x, p2y, intersects := SegmentCircleIntersection(s1x, s1y, s2x, s2y, cx, cy, r)

            if intersects {
                solutionCntr++
                //Check if points are on circle
                c1x, c1y := p1x-cx, p1y-cy
                deltaLen1 := (c1x*c1x + c1y*c1y) - r*r
                CheckEpsilon(t, deltaLen1, epsilon, "p1 not on circle")

                c2x, c2y := p2x-cx, p2y-cy
                deltaLen2 := (c2x*c2x + c2y*c2y) - r*r
                CheckEpsilon(t, deltaLen2, epsilon, "p2 not on circle")

                // Check if points are on the line through the line segment
                // "cross product" of vector from a segment point to the point
                // and the vector for the segment should be near zero
                vp1x, vp1y := p1x-s1x, p1y-s1y
                crossProd1 := vp1x*segy - vp1y*segx
                CheckEpsilon(t, crossProd1, epsilon, "p1 not on line ")

                vp2x, vp2y := p2x-s1x, p2y-s1y
                crossProd2 := vp2x*segy - vp2y*segx
                CheckEpsilon(t, crossProd2, epsilon, "p2 not on line ")

                // Check if point is between points s1 and s2 on line
                // This means the sign of the dot prod of the segment vector
                // and point to segment end point vectors are opposite for
                // either end.
                wp1x, wp1y := p1x-s2x, p1y-s2y
                dp1v := vp1x*segx + vp1y*segy
                dp1w := wp1x*segx + wp1y*segy
                if (dp1v < 0 && dp1w < 0) || (dp1v > 0 && dp1w > 0) {
                    t.Error("point not contained in segment ", dp1v, dp1w)
                    t.FailNow()
                }

                wp2x, wp2y := p2x-s2x, p2y-s2y
                dp2v := vp2x*segx + vp2y*segy
                dp2w := wp2x*segx + wp2y*segy
                if (dp2v < 0 && dp2w < 0) || (dp2v > 0 && dp2w > 0) {
                    t.Error("point not contained in segment ", dp2v, dp2w)
                    t.FailNow()
                }

                if s1x == s2x && s2y == s1y { //Only one solution
                    // Test that one end of the segment is withing the radius of the circle
                    // and one is not
                    if seg1Inside && seg2Inside {
                        t.Error("Only one solution but both line segment ends inside")
                        t.FailNow()
                    }
                    if !seg1Inside && !seg2Inside {
                        t.Error("Only one solution but both line segment ends outside")
                        t.FailNow()
                    }

                }
            } else { // No intersection, check if both points outside or inside
                if (seg1Inside && !seg2Inside) || (!seg1Inside && seg2Inside) {
                    t.Error("No solution but only one point in radius of circle")
                    t.FailNow()
                }
            }
        }
    }
    t.Log("Tested ", testCntr, " examples and found ", solutionCntr, " solutions.")
}

Here is the output of the test:

=== RUN   TestSegmentCircleIntersection
--- PASS: TestSegmentCircleIntersection (0.00s)
    geom_test.go:105: Tested  40000  examples and found  7343  solutions.

Finally, the method is easily extendable to the case of a ray starting at one point, going through the other and extending to infinity, by only testing if t > 0 or t < 1 but not both.

Read int values from a text file in C

How about this?

fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2); 

In this case spaces in fscanf match multiple occurrences of any whitespace until the next token in found.

Get each line from textarea

You could use PHP constant:

$array = explode(PHP_EOL, $text);

additional notes:
1. For me this is the easiest and the safest way because it is cross platform compatible (Windows/Linux etc.)
2. It is better to use PHP CONSTANT whenever you can for faster execution

Set line spacing

Yup, as everyone's saying, line-height is the thing. Any font you are using, a mid-height character (such as a or ¦, not going through the upper or lower) should go with the same height-length at line-height: 0.6 to 0.65.

_x000D_
_x000D_
<div style="line-height: 0.65; font-family: 'Fira Code', monospace, sans-serif">_x000D_
aaaaa<br>_x000D_
aaaaa<br>_x000D_
aaaaa<br>_x000D_
aaaaa<br>_x000D_
aaaaa_x000D_
</div>_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div style="line-height: 0.6; font-family: 'Fira Code', monospace, sans-serif">_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦_x000D_
</div>_x000D_
<br>_x000D_
<br>_x000D_
<strong>BUT</strong>_x000D_
<br>_x000D_
<br>_x000D_
<div style="line-height: 0.65; font-family: 'Fira Code', monospace, sans-serif">_x000D_
ddd<br>_x000D_
ƒƒƒ<br>_x000D_
ggg_x000D_
</div>
_x000D_
_x000D_
_x000D_

PHP: Read Specific Line From File

I searched for a one line solution to read specific line from a file. Here my solution:

echo file('dayInt.txt')[1]

Vertical line using XML drawable

I think this is the simplest solution:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:gravity="center">
        <shape android:shape="rectangle">
            <size android:width="1dp" />
            <solid android:color="#0000FF" />
        </shape>
    </item>

</layer-list>

How to split strings over multiple lines in Bash?

Line continuations also can be achieved through clever use of syntax.

In the case of echo:

# echo '-n' flag prevents trailing <CR> 
echo -n "This is my one-line statement" ;
echo -n " that I would like to make."
This is my one-line statement that I would like to make.

In the case of vars:

outp="This is my one-line statement" ; 
outp+=" that I would like to make." ; 
echo -n "${outp}"
This is my one-line statement that I would like to make.

Another approach in the case of vars:

outp="This is my one-line statement" ; 
outp="${outp} that I would like to make." ; 
echo -n "${outp}"
This is my one-line statement that I would like to make.

Voila!

How to paste text to end of every line? Sublime 2

Let's say you have these lines of code:

test line one
test line two
test line three
test line four

Using Search and Replace Ctrl+H with Regex let's find this: ^ and replace it with ", we'll have this:

"test line one
"test line two
"test line three
"test line four

Now let's search this: $ and replace it with ", now we'll have this:

"test line one"
"test line two"
"test line three"
"test line four"

How to read specific lines from a file (by line number)?

file = '/path/to/file_to_be_read.txt'
with open(file) as f:
    print f.readlines()[26]
    print f.readlines()[30]

Using the with statement, this opens the file, prints lines 26 and 30, then closes the file. Simple!

What is the difference between Left, Right, Outer and Inner Joins?

LEFT JOIN and RIGHT JOIN are types of OUTER JOINs.

INNER JOIN is the default -- rows from both tables must match the join condition.

Docker: "no matching manifest for windows/amd64 in the manifest list entries"

I had the same problem to run Windows IIS image using docker for Windows. Reading the Mohammad Trabelsi response above I realised that to solve my problem I needed to switch my containers (on docker) for Windows containers.

To do this:

  1. Right click Docker instance
  2. Select "Switch to Windows containers..."

Node.js: Difference between req.query[] and req.params

Given this route

app.get('/hi/:param1', function(req,res){} );

and given this URL http://www.google.com/hi/there?qs1=you&qs2=tube

You will have:

req.query

{
  qs1: 'you',
  qs2: 'tube'
}

req.params

{
  param1: 'there'
}

Express req.params >>

How do I open port 22 in OS X 10.6.7

I'm using OSX 10.11.6 and this article works for me.

enter image description here

Install tkinter for Python

If you are using Python 3 it might be because you are typing Tkinter not tkinter

How to get datetime in JavaScript?

Semantically, you're probably looking for the one-liner

new Date().toLocaleString()

which formats the date in the locale of the user.

If you're really looking for a specific way to format dates, I recommend the moment.js library.

Enabling WiFi on Android Emulator

Apparently it does not and I didn't quite expect it would. HOWEVER Ivan brings up a good possibility that has escaped Android people.

What is the purpose of an emulator? to EMULATE, right? I don't see why for testing purposes -provided the tester understands the limitations- the emulator might not add a Wifi emulator.

It could for example emulate WiFi access by using the underlying internet connection of the host. Obviously testing WPA/WEP differencess would not make sense but at least it could toggle access via WiFi.

Or some sort of emulator plugin where there would be a base WiFi emulator that would emulate WiFi access via the underlying connection but then via configuration it could emulate WPA/WEP by providing a list of fake WiFi networks and their corresponding fake passwords that would be matched against a configurable list of credentials.

After all the idea is to do initial testing on the emulator and then move on to the actual device.

How do you setLayoutParams() for an ImageView?

An ImageView gets setLayoutParams from View which uses ViewGroup.LayoutParams. If you use that, it will crash in most cases so you should use getLayoutParams() which is in View.class. This will inherit the parent View of the ImageView and will work always. You can confirm this here: ImageView extends view

Assuming you have an ImageView defined as 'image_view' and the width/height int defined as 'thumb_size'

The best way to do this:

ViewGroup.LayoutParams iv_params_b = image_view.getLayoutParams();
iv_params_b.height = thumb_size;
iv_params_b.width = thumb_size;
image_view.setLayoutParams(iv_params_b);

Cache busting via params

Another similar approach is to use htaccess mod_rewrite to ignore part of the path when serving the files. Your never-cached index page references the latest path to the files.

From a development perspective it's as easy as using params for the version number, but it's as robust as the filename approach.

Use the ignored part of the path for the version number, and the server just ignores it and serves the uncached file.

1.2.3/css/styles.css serves the same file as css/styles.css since the first directory is stripped and ignored by the htaccess file

Including versioned files

<?php
  $version = "1.2.3";
?>

<html>
  <head>
    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="0" />
    <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
    <meta http-equiv="pragma" content="no-cache" />
    <link rel="stylesheet" type="text/css" href="<?php echo $version ?>/css/styles.css">
  </head>
  <body>
    <script src="<?php echo $version ?>/js/main.js"></script>
  </body>
</html>

Note that this approach means you need to disable caching of your index page - Using <meta> tags to turn off caching in all browsers?

.htaccess file

RewriteEngine On

# if you're requesting a file that exists, do nothing
RewriteCond %{REQUEST_FILENAME} !-f 
# likewise if a directory that exists, do nothing
RewriteCond %{REQUEST_FILENAME} !-d 

# otherwise, rewrite foo/bar/baz to bar/baz - ignore the first directory
RewriteRule ^[^/]+/(.+)$ $1 [L] 

You could take the same approach on any server platform that allows url rewriting

(rewrite condition adapted from mod_rewrite - rewrite directory to query string except /#!/)

... and if you need cache busting for your index page / site entry point, you could always use JavaSript to refresh it.

How to set a default value with Html.TextBoxFor?

This should work for MVC3 & MVC4

 @Html.TextBoxFor(m => m.Age, new { @Value = "12" }) 

If you want it to be a hidden field

 @Html.TextBoxFor(m => m.Age, new { @Value = "12",@type="hidden" }) 

Python: TypeError: object of type 'NoneType' has no len()

You don't need to assign names to list or [] or anything else until you wish to use it.

It's neater to use a list comprehension to make the list of names.

shuffle modifies the list you pass to it. It always returns None

If you are using a context manager (with ...) you don't need to close the file explicitly

from random import shuffle

with open('names') as f:
    names = [name.rstrip() for name in f if not name.isspace()]
    shuffle(names)

assert len(names) > 100

How to delete columns in pyspark dataframe

You can delete column like this:

df.drop("column Name).columns

In your case :

df.drop("id").columns

If you want to drop more than one column you can do:

dfWithLongColName.drop("ORIGIN_COUNTRY_NAME", "DEST_COUNTRY_NAME")

Read data from a text file using Java

If you want to read line-by-line, use a BufferedReader. It has a readLine() method which returns the line as a String, or null if the end of the file has been reached. So you can do something like:

BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
 // Do something with line
}

(Note that this code doesn't handle exceptions or close the stream, etc)

How do I pass a value from a child back to the parent form?

If you are displaying child form as a modal dialog box, you can set DialogResult property of child form with a value from the DialogResult enumeration which in turn hides the modal dialog box, and returns control to the calling form. At this time parent can access child form's data to get the info that it need.

For more info check this link: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.dialogresult(v=vs.110).aspx

Remove xticks in a matplotlib plot?

The tick_params method is very useful for stuff like this. This code turns off major and minor ticks and removes the labels from the x-axis.

from matplotlib import pyplot as plt
plt.plot(range(10))
plt.tick_params(
    axis='x',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    bottom=False,      # ticks along the bottom edge are off
    top=False,         # ticks along the top edge are off
    labelbottom=False) # labels along the bottom edge are off
plt.show()
plt.savefig('plot')
plt.clf()

enter image description here

401 Unauthorized: Access is denied due to invalid credentials

I realize this is an older post but I had the same error on IIS 8.5. Hopefully this can help another experiencing the same issue (I didn't see my issue outlined in other questions with a similar title).

Everything seemed set up correctly with the Application Pool Identity, but I continued to receive the error. After much digging, there is a setting for the anonymous user to use the credentials of the application pool identity or a specific user. For whatever reason, mine was defaulted to a specific user. Altering the setting to the App Pool Identity fixed the issue for me.

  1. IIS Manager ? Sites ? Website
  2. Double click "Authentication"
  3. Select Anonymous Authentication
  4. From the Actions panel, select Edit
  5. Select Application pool Identity and click ok

Hopefully this saves someone else some time!

jQuery UI Alert Dialog as a replacement for alert()

There is an issue that if you close the dialog it will execute the onCloseCallback function. This is a better design.

function jAlert2(outputMsg, titleMsg, onCloseCallback) {
    if (!titleMsg)
        titleMsg = 'Alert';

    if (!outputMsg)
        outputMsg = 'No Message to Display.';

    $("<div></div>").html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": onCloseCallback,
            "Cancel": function() {
          $( this ).dialog( "destroy" );
            }

        },
    });

C# ASP.NET Send Email via TLS

I was almost using the same technology as you did, however I was using my app to connect an Exchange Server via Office 365 platform on WinForms. I too had the same issue as you did, but was able to accomplish by using code which has slight modification of what others have given above.

SmtpClient client = new SmtpClient(exchangeServer, 587);
client.Credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.Send(msg);

I had to use the Port 587, which is of course the default port over TSL and the did the authentication.

What are .dex files in Android?

dex file is a file that is executed on the Dalvik VM.

Dalvik VM includes several features for performance optimization, verification, and monitoring, one of which is Dalvik Executable (DEX).

Java source code is compiled by the Java compiler into .class files. Then the dx (dexer) tool, part of the Android SDK processes the .class files into a file format called DEX that contains Dalvik byte code. The dx tool eliminates all the redundant information that is present in the classes. In DEX all the classes of the application are packed into one file. The following table provides comparison between code sizes for JVM jar files and the files processed by the dex tool.

The table compares code sizes for system libraries, web browser applications, and a general purpose application (alarm clock app). In all cases dex tool reduced size of the code by more than 50%.

enter image description here

In standard Java environments each class in Java code results in one .class file. That means, if the Java source code file has one public class and two anonymous classes, let’s say for event handling, then the java compiler will create total three .class files.

The compilation step is same on the Android platform, thus resulting in multiple .class files. But after .class files are generated, the “dx” tool is used to convert all .class files into a single .dex, or Dalvik Executable, file. It is the .dex file that is executed on the Dalvik VM. The .dex file has been optimized for memory usage and the design is primarily driven by sharing of data.

What is the @Html.DisplayFor syntax for?

After looking for an answer for myself for some time, i could find something. in general if we are using it for just one property it appears same even if we do a "View Source" of generated HTML Below is generated HTML for example, when i want to display only Name property for my class

    <td>
    myClassNameProperty
    </td>
   <td>
    myClassNameProperty, This is direct from Item
    </td>

This is the generated HTML from below code

<td>
@Html.DisplayFor(modelItem=>item.Genre.Name)            
</td>

<td>
@item.Genre.Name, This is direct from Item
</td>

At the same time now if i want to display all properties in one statement for my class "Genre" in this case, i can use @Html.DisplayFor() to save on my typing, for least

i can write @Html.DisplayFor(modelItem=>item.Genre) in place of writing a separate statement for each property of Genre as below

@item.Genre.Name
@item.Genre.Id
@item.Genre.Description

and so on depending on number of properties.

How can I combine hashes in Perl?

For hash references. You should use curly braces like the following:

$hash_ref1 = {%$hash_ref1, %$hash_ref2};

and not the suggested answer above using parenthesis:

$hash_ref1 = ($hash_ref1, $hash_ref2);

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Assgining a value that starts with a "=" will kick in formula evaluation and gave in my case the above mentioned error #1004. Prepending it with a space was the ticket for me.

DynamoDB vs MongoDB NoSQL

Bear in mind, I've only experimented with MongoDB...

From what I've read, DynamoDB has come a long way in terms of features. It used to be a super-basic key-value store with extremely limited storage and querying capabilities. It has since grown, now supporting bigger document sizes + JSON support and global secondary indices. The gap between what DynamoDB and MongoDB offers in terms of features grows smaller with every month. The new features of DynamoDB are expanded on here.

Much of the MongoDB vs. DynamoDB comparisons are out of date due to the recent addition of DynamoDB features. However, this post offers some other convincing points to choose DynamoDB, namely that it's simple, low maintenance, and often low cost. Another discussion here of database choices was interesting to read, though slightly old.

My takeaway: if you're doing serious database queries or working in languages not supported by DynamoDB, use MongoDB. Otherwise, stick with DynamoDB.

How do I check that a Java String is not all whitespaces?

This answer focusses more on the sidenote "i.e. has at least one alphanumeric character". Besides that, it doesn't add too much to the other (earlier) solution, except that it doesn't hurt you with NPE in case the String is null.

We want false if (1) s is null or (2) s is empty or (3) s only contains whitechars.

public static boolean containsNonWhitespaceChar(String s) {
  return !((s == null) || "".equals(s.trim()));
}

What's a good, free serial port monitor for reverse-engineering?

I hear a lot of good things about com0com, which is a software port emulator. You can "connect" a physical serial port through it, so that your software uses the (monitored) virtual port, and forwards all traffic to/from a physical port. I haven't used it myself, but I've seen it recommended here on SO a lot.

Computing cross-correlation function?

For 1D array, numpy.correlate is faster than scipy.signal.correlate, under different sizes, I see a consistent 5x peformance gain using numpy.correlate. When two arrays are of similar size (the bright line connecting the diagonal), the performance difference is even more outstanding (50x +).

# a simple benchmark
res = []
for x in range(1, 1000):
    list_x = []
    for y in range(1, 1000): 

        # generate different sizes of series to compare
        l1 = np.random.choice(range(1, 100), size=x)
        l2 = np.random.choice(range(1, 100), size=y)

        time_start = datetime.now()
        np.correlate(a=l1, v=l2)
        t_np = datetime.now() - time_start

        time_start = datetime.now()
        scipy.signal.correlate(in1=l1, in2=l2)
        t_scipy = datetime.now() - time_start

        list_x.append(t_scipy / t_np)
    res.append(list_x)
plt.imshow(np.matrix(res))

enter image description here

As default, scipy.signal.correlate calculates a few extra numbers by padding and that might explained the performance difference.

>> l1 = [1,2,3,2,1,2,3]
>> l2 = [1,2,3]
>> print(numpy.correlate(a=l1, v=l2))
>> print(scipy.signal.correlate(in1=l1, in2=l2))

[14 14 10 10 14]
[ 3  8 14 14 10 10 14  8  3]  # the first 3 is [0,0,1]dot[1,2,3]

How do you uninstall a python package that was installed using distutils?

If this is for testing and/or development purposes, setuptools has a develop command that updates every time you make a change (so you don't have to uninstall and reinstall every time you make a change). And you can uninstall the package using this command as well.

If you do use this, anything that you declare as a script will be left behind as a lingering file.

Why do we need C Unions?

Low level system programming is a reasonable example.

IIRC, I've used unions to breakdown hardware registers into the component bits. So, you can access an 8-bit register (as it was, in the day I did this ;-) into the component bits.

(I forget the exact syntax but...) This structure would allow a control register to be accessed as a control_byte or via the individual bits. It would be important to ensure the bits map on to the correct register bits for a given endianness.

typedef union {
    unsigned char control_byte;
    struct {
        unsigned int nibble  : 4;
        unsigned int nmi     : 1;
        unsigned int enabled : 1;
        unsigned int fired   : 1;
        unsigned int control : 1;
    };
} ControlRegister;

Starting Docker as Daemon on Ubuntu

This problem really cost me some hours.

My system is Ubuntu 14.04, I installed docker by sudo apt-get install docker, and typed some other commands that caused the problem.

  1. I google "unknown job: docker.io", answers did not take effect.

  2. I looked for reasons of "unknown job" in /etc/init.d/, found no proper answer .

  3. I looked for way to debug script in /etc/init.d/, found no proper answer.

  4. Then, I did a clean:

    1. sudo apt-get remove docker.io
    2. rm every suspicious file by find / -name "*docker*", such as /etc/init/docker.io.conf, /etc/init.d/docker.io .
  5. Follow the latest official document: https://docs.docker.com/installation/, there is a lot of outdated documentation which can be misleading.

Finally, it fixed the problem.

Note: If you are in China, because of the GFW, you may need to set the https_proxy to install docker from https://get.docker.com/ .

A formula to copy the values from a formula to another column

Copy the cell. Paste special as link. Will update with original. No formula though.

How to do a SQL NOT NULL with a DateTime?

SELECT * FROM Table where codtable not in (Select codtable from Table where fecha is null)

Order by descending date - month, day and year

You have the field in a string, so you'll need to convert it to datetime

order by CONVERT(datetime, EventDate ) desc

combining two data frames of different lengths

Refering to Andrie's answer, suggesting to use plyr::rbind.fill(): Combined with t() you have something like cbind.fill() (which is not part of plyr) that will construct your data frame with consideration of identical case numbers.

did you register the component correctly? For recursive components, make sure to provide the "name" option

The high votes answer is right. You can checkout that you have applied different name for the components. But if the question is still not resolved, you can make sure that you have register the component only once.

_x000D_
_x000D_
components: {_x000D_
    IMContainer,_x000D_
    RightPanel_x000D_
},_x000D_
methods: {},_x000D_
components: {_x000D_
    IMContainer,_x000D_
    RightPanel_x000D_
}_x000D_
  
_x000D_
_x000D_
_x000D_

we always forget that we have register the component before

Angular 2 optional route parameter

Angular 4 - Solution to address the ordering of the optional parameter:

DO THIS:

const appRoutes: Routes = [
  {path: '', component: HomeComponent},
  {path: 'products', component: ProductsComponent},
  {path: 'products/:id', component: ProductsComponent}
]

Note that the products and products/:id routes are named exactly the same. Angular 4 will correctly follow products for routes with no parameter, and if a parameter it will follow products/:id.

However, the path for the non-parameter route products must not have a trailing slash, otherwise angular will incorrectly treat it as a parameter-path. So in my case, I had the trailing slash for products and it wasn't working.

DON'T DO THIS:

...
{path: 'products/', component: ProductsComponent},
{path: 'products/:id', component: ProductsComponent},
...

Programmatically select a row in JTable

You can do it calling setRowSelectionInterval :

table.setRowSelectionInterval(0, 0);

to select the first row.

How can I do DNS lookups in Python, including referring to /etc/hosts?

Sounds like you don't want to resolve dns yourself (this might be the wrong nomenclature) dnspython appears to be a standalone dns client that will understandably ignore your operating system because its bypassing the operating system's utillities.

We can look at a shell utility named getent to understand how the (debian 11 alike) operating system resolves dns for programs, this is likely the standard for all *nix like systems that use a socket implementation.

see man getent's "hosts" section, which mentions the use of getaddrinfo, which we can see as man getaddrinfo

and to use it in python, we have to extract some info from the data structures

.

import socket

def get_ipv4_by_hostname(hostname):
    # see `man getent` `/ hosts `
    # see `man getaddrinfo`

    return list(
        i        # raw socket structure
            [4]  # internet protocol info
            [0]  # address
        for i in 
        socket.getaddrinfo(
            hostname,
            0  # port, required
        )
        if i[0] is socket.AddressFamily.AF_INET  # ipv4

        # ignore duplicate addresses with other socket types
        and i[1] is socket.SocketKind.SOCK_RAW  
    )

print(get_ipv4_by_hostname('localhost'))
print(get_ipv4_by_hostname('google.com'))

Working with select using AngularJS's ng-options

The question is already answered (BTW, really good and comprehensive answer provided by Ben), but I would like to add another element for completeness, which may be also very handy.

In the example suggested by Ben:

<select ng-model="blah" ng-options="item.ID as item.Title for item in items"></select>

the following ngOptions form has been used: select as label for value in array.

Label is an expression, which result will be the label for <option> element. In that case you can perform certain string concatenations, in order to have more complex option labels.

Examples:

  • ng-options="item.ID as item.Title + ' - ' + item.ID for item in items" gives you labels like Title - ID
  • ng-options="item.ID as item.Title + ' (' + item.Title.length + ')' for item in items" gives you labels like Title (X), where X is length of Title string.

You can also use filters, for example,

  • ng-options="item.ID as item.Title + ' (' + (item.Title | uppercase) + ')' for item in items" gives you labels like Title (TITLE), where Title value of Title property and TITLE is the same value but converted to uppercase characters.
  • ng-options="item.ID as item.Title + ' (' + (item.SomeDate | date) + ')' for item in items" gives you labels like Title (27 Sep 2015), if your model has a property SomeDate

Checking whether a variable is an integer or not

val=3
>>> isinstance(val,int ) 
True

will work.

How to display an image from a path in asp.net MVC 4 and Razor view?

you can also try with this answer :

 <img src="~/Content/img/@Html.DisplayFor(model =>model.ImagePath)" style="height:200px;width:200px;"/>

How to include NA in ifelse?

So, I hear this works:

Data$X1<-as.character(Data$X1)
Data$GEOID<-as.character(Data$BLKIDFP00)
Data<-within(Data,X1<-ifelse(is.na(Data$X1),GEOID,Data$X2)) 

But I admit I have only intermittent luck with it.

Get user location by IP address

Use http://ipinfo.io , You need to pay them if you make more than 1000 requests per day.

The code below requires the Json.NET package.

public static string GetUserCountryByIp(string ip)
{
    IpInfo ipInfo = new IpInfo();
    try
    {
        string info = new WebClient().DownloadString("http://ipinfo.io/" + ip);
        ipInfo = JsonConvert.DeserializeObject<IpInfo>(info);
        RegionInfo myRI1 = new RegionInfo(ipInfo.Country);
        ipInfo.Country = myRI1.EnglishName;
    }
    catch (Exception)
    {
        ipInfo.Country = null;
    }
    
    return ipInfo.Country;
}

And the IpInfo Class I used:

public class IpInfo
{
    [JsonProperty("ip")]
    public string Ip { get; set; }

    [JsonProperty("hostname")]
    public string Hostname { get; set; }

    [JsonProperty("city")]
    public string City { get; set; }

    [JsonProperty("region")]
    public string Region { get; set; }

    [JsonProperty("country")]
    public string Country { get; set; }

    [JsonProperty("loc")]
    public string Loc { get; set; }

    [JsonProperty("org")]
    public string Org { get; set; }

    [JsonProperty("postal")]
    public string Postal { get; set; }
}

Angular: How to download a file from HttpClient?

Try something like this:

type: application/ms-excel

/**
 *  used to get file from server
 */

this.http.get(`${environment.apiUrl}`,{
          responseType: 'arraybuffer',headers:headers} 
         ).subscribe(response => this.downLoadFile(response, "application/ms-excel"));


    /**
     * Method is use to download file.
     * @param data - Array Buffer data
     * @param type - type of the document.
     */
    downLoadFile(data: any, type: string) {
        let blob = new Blob([data], { type: type});
        let url = window.URL.createObjectURL(blob);
        let pwa = window.open(url);
        if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
            alert( 'Please disable your Pop-up blocker and try again.');
        }
    }

Update data on a page without refreshing

In general, if you don't know how something works, look for an example which you can learn from.

For this problem, consider this DEMO

You can see loading content with AJAX is very easily accomplished with jQuery:

$(function(){
    // don't cache ajax or content won't be fresh
    $.ajaxSetup ({
        cache: false
    });
    var ajax_load = "<img src='http://automobiles.honda.com/images/current-offers/small-loading.gif' alt='loading...' />";

    // load() functions
    var loadUrl = "http://fiddle.jshell.net/deborah/pkmvD/show/";
    $("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

// end  
});

Try to understand how this works and then try replicating it. Good luck.

You can find the corresponding tutorial HERE

Update

Right now the following event starts the ajax load function:

$("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

You can also do this periodically: How to fire AJAX request Periodically?

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

I made a demo of this implementation for you HERE. In this demo, every 2 seconds (setTimeout(worker, 2000);) the content is updated.

You can also just load the data immediately:

$("#result").html(ajax_load).load(loadUrl);

Which has THIS corresponding demo.

JavaScript OR (||) variable assignment explanation

See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.

What is a "thread" (really)?

I am going to use a lot of text from the book Operating Systems Concepts by ABRAHAM SILBERSCHATZ, PETER BAER GALVIN and GREG GAGNE along with my own understanding of things.

Process

Any application resides in the computer in the form of text (or code).

We emphasize that a program by itself is not a process. A program is a passive entity, such as a file containing a list of instructions stored on disk (often called an executable file).

When we start an application, we create an instance of execution. This instance of execution is called a process. EDIT:(As per my interpretation, analogous to a class and an instance of a class, the instance of a class being a process. )

An example of processes is that of Google Chrome. When we start Google Chrome, 3 processes are spawned:

• The browser process is responsible for managing the user interface as well as disk and network I/O. A new browser process is created when Chrome is started. Only one browser process is created.

Renderer processes contain logic for rendering web pages. Thus, they contain the logic for handling HTML, Javascript, images, and so forth. As a general rule, a new renderer process is created for each website opened in a new tab, and so several renderer processes may be active at the same time.

• A plug-in process is created for each type of plug-in (such as Flash or QuickTime) in use. Plug-in processes contain the code for the plug-in as well as additional code that enables the plug-in to communicate with associated renderer processes and the browser process.

Thread

To answer this I think you should first know what a processor is. A Processor is the piece of hardware that actually performs the computations. EDIT: (Computations like adding two numbers, sorting an array, basically executing the code that has been written)

Now moving on to the definition of a thread.

A thread is a basic unit of CPU utilization; it comprises a thread ID, a program counter, a register set, and a stack.

EDIT: Definition of a thread from intel's website:

A Thread, or thread of execution, is a software term for the basic ordered sequence of instructions that can be passed through or processed by a single CPU core.

So, if the Renderer process from the Chrome application sorts an array of numbers, the sorting will take place on a thread/thread of execution. (The grammar regarding threads seems confusing to me)

My Interpretation of Things

A process is an execution instance. Threads are the actual workers that perform the computations via CPU access. When there are multiple threads running for a process, the process provides common memory.

EDIT: Other Information that I found useful to give more context

All modern day computer have more than one threads. The number of threads in a computer depends on the number of cores in a computer.

Concurrent Computing:

From Wikipedia:

Concurrent computing is a form of computing in which several computations are executed during overlapping time periods—concurrently—instead of sequentially (one completing before the next starts). This is a property of a system—this may be an individual program, a computer, or a network—and there is a separate execution point or "thread of control" for each computation ("process").

So, I could write a program which calculates the sum of 4 numbers:

(1 + 3) + (4 + 5)

In the program to compute this sum (which will be one process running on a thread of execution) I can fork another process which can run on a different thread to compute (4 + 5) and return the result to the original process, while the original process calculates the sum of (1 + 3).

Android WSDL/SOAP service client

i founded this tool to auto generate wsdl to android code,

http://www.wsdl2code.com/Example.aspx

public void callWebService(){
    SampleService srv1 = new SampleService();
    Request req = new Request();
    req.companyId = "1";
    req.userName = "userName";
    req.password = "pas";
    Response response =  srv1.ServiceSample(req);
}

Convert Float to Int in Swift

You can get an integer representation of your float by passing the float into the Integer initializer method.

Example:

Int(myFloat)

Keep in mind, that any numbers after the decimal point will be loss. Meaning, 3.9 is an Int of 3 and 8.99999 is an integer of 8.

How to split a string by spaces in a Windows batch file?

The following code will split a string with an arbitrary number of substrings:

@echo off
setlocal ENABLEDELAYEDEXPANSION

REM Set a string with an arbitrary number of substrings separated by semi colons
set teststring=The;rain;in;spain

REM Do something with each substring
:stringLOOP
    REM Stop when the string is empty
    if "!teststring!" EQU "" goto END

    for /f "delims=;" %%a in ("!teststring!") do set substring=%%a

        REM Do something with the substring - 
        REM we just echo it for the purposes of demo
        echo !substring!

REM Now strip off the leading substring
:striploop
    set stripchar=!teststring:~0,1!
    set teststring=!teststring:~1!

    if "!teststring!" EQU "" goto stringloop

    if "!stripchar!" NEQ ";" goto striploop

    goto stringloop
)

:END
endlocal

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

Python 3.3 and later now uses the 2010 compiler. To best way to solve the issue is to just install Visual C++ Express 2010 for free.

Now comes the harder part for 64 bit users and to be honest I just moved to 32 bit but 2010 express doesn't come with a 64 bit compiler (you get a new error, ValueError: ['path'] ) so you have to install Microsoft SDK 7.1 and follow the directions here to get the 64 bit compiler working with python: Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7

It may just be easier for you to use the 32 bit version for now. In addition to getting the compiler working, you can bypass the need to compile many modules by getting the binary wheel file from this locaiton http://www.lfd.uci.edu/~gohlke/pythonlibs/

Just download the .whl file you need, shift + right click the download folder and select "open command window here" and run

pip install module-name.whl 

I used that method on 64 bit 3.4.3 before I broke down and decided to just get a working compiler for pip compiles modules from source by default, which is why the binary wheel files work and having pip build from source doesn't.

People getting this (vcvarsall.bat) error on Python 2.7 can instead install "Microsoft Visual C++ Compiler for Python 2.7"

CodeIgniter - How to return Json response from controller

For CodeIgniter 4, you can use the built-in API Response Trait

Here's sample code for reference:

<?php namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;

class Home extends BaseController
{
    use ResponseTrait;

    public function index()
    {
        $data = [
            'data' => 'value1',
            'data2' => 'value2',
        ];

        return $this->respond($data);
    }
}

findAll() in yii

Another simple way get by using findall in yii

$id =101; 
$comments = EmailArchive::model()->findAll(array("condition"=>"':email_id'=$id"));
foreach($comments as $comments_1) 
{ 
echo  "email:".$comments_1['email_id'];
}

new DateTime() vs default(DateTime)

The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min

Therefore there is no difference between default(DateTime) and new DateTime() and DateTime.Min

Inserting string at position x of another string

You can add this function to string class

String.prototype.insert_at=function(index, string)
{   
  return this.substr(0, index) + string + this.substr(index);
}

so that you can use it on any string object:

var my_string = "abcd";
my_string.insertAt(1, "XX");

Should I use int or Int32

int is the C# language's shortcut for System.Int32

Whilst this does mean that Microsoft could change this mapping, a post on FogCreek's discussions stated [source]

"On the 64 bit issue -- Microsoft is indeed working on a 64-bit version of the .NET Framework but I'm pretty sure int will NOT map to 64 bit on that system.

Reasons:

1. The C# ECMA standard specifically says that int is 32 bit and long is 64 bit.

2. Microsoft introduced additional properties & methods in Framework version 1.1 that return long values instead of int values, such as Array.GetLongLength in addition to Array.GetLength.

So I think it's safe to say that all built-in C# types will keep their current mapping."

Inserting into Oracle and retrieving the generated sequence ID

You can do this with a single statement - assuming you are calling it from a JDBC-like connector with in/out parameters functionality:

insert into batch(batchid, batchname) 
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;

or, as a pl-sql script:

variable l_batchid number;

insert into batch(batchid, batchname) 
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;

select :l_batchid from dual;

Selecting empty text input using jQuery

Since creating an JQuery object for every comparison is not efficient, just use:

$.expr[":"].blank = function(element) {
    return element.value == "";
};

Then you can do:

$(":input:blank")

How do I pass multiple parameter in URL?

You can pass multiple parameters as "?param1=value1&param2=value2"

But it's not secure. It's vulnerable to Cross Site Scripting (XSS) Attack.

Your parameter can be simply replaced with a script.

Have a look at this article and article

You can make it secure by using API of StringEscapeUtils

static String   escapeHtml(String str) 
          Escapes the characters in a String using HTML entities.

Even using https url for security without above precautions is not a good practice.

Have a look at related SE question:

Is URLEncoder.encode(string, "UTF-8") a poor validation?

SQL Server convert string to datetime

For instance you can use

update tablename set datetimefield='19980223 14:23:05'
update tablename set datetimefield='02/23/1998 14:23:05'
update tablename set datetimefield='1998-12-23 14:23:05'
update tablename set datetimefield='23 February 1998 14:23:05'
update tablename set datetimefield='1998-02-23T14:23:05'

You need to be careful of day/month order since this will be language dependent when the year is not specified first. If you specify the year first then there is no problem; date order will always be year-month-day.

How do I pass JavaScript values to Scriptlet in JSP?

Your javascript values are client-side, your scriptlet is running server-side. So if you want to use your javascript variables in a scriptlet, you will need to submit them.

To achieve this, either store them in input fields and submit a form, or perform an ajax request. I suggest you look into JQuery for this.

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

There is a Powershell script buried in the msdb forums that will script all the tables and related objects:

# Script all tables in a database
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") 
    | out-null

$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') '<Servername>'
$db = $s.Databases['<Database>']

$scrp = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($s)
$scrp.Options.AppendToFile = $True
$scrp.Options.ClusteredIndexes = $True
$scrp.Options.DriAll = $True
$scrp.Options.ScriptDrops = $False
$scrp.Options.IncludeHeaders = $False
$scrp.Options.ToFileOnly = $True
$scrp.Options.Indexes = $True
$scrp.Options.WithDependencies = $True
$scrp.Options.FileName = 'C:\Temp\<Database>.SQL'

foreach($item in $db.Tables) { $tablearray+=@($item) }
$scrp.Script($tablearray)

Write-Host "Scripting complete"

Set "Homepage" in Asp.Net MVC

I tried the answer but it didn't worked for me. This is what i ended up doing:

Create a new controller DefaultController. In index action, i wrote one line redirect:

return Redirect("~/Default.aspx")

In RouteConfig.cs, change controller="Default" for the route.

 routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
        );

UIGestureRecognizer on UIImageView

Swift 2.0 Solution

You create a tap, pinch or swipe gesture recognizer in the same manor. Below I'll walk you through 4 steps to getting your recognizer up and running.

4 Steps

1.) Inherit from UIGestureRecognizerDelegate by adding it to your class signature.

class ViewController: UIViewController, UIGestureRecognizerDelegate {...}

2.) Control drag from your image to your viewController to create an IBOutlet:

@IBOutlet weak var tapView: UIImageView!

3.) In your viewDidLoad add the following code:

// create an instance of UITapGestureRecognizer and tell it to run 
// an action we'll call "handleTap:"
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
// we use our delegate
tap.delegate = self
// allow for user interaction
tapView.userInteractionEnabled = true
// add tap as a gestureRecognizer to tapView
tapView.addGestureRecognizer(tap)

4.) Create the function that will be called when your gesture recognizer is tapped. (You can exclude the = nil if you choose).

func handleTap(sender: UITapGestureRecognizer? = nil) {
    // just creating an alert to prove our tap worked!
    let tapAlert = UIAlertController(title: "hmmm...", message: "this actually worked?", preferredStyle: UIAlertControllerStyle.Alert)
    tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
    self.presentViewController(tapAlert, animated: true, completion: nil)
}

Your final code should look something like this:

class ViewController: UIViewController, UIGestureRecognizerDelegate {

    @IBOutlet weak var tapView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
        tap.delegate = self
        tapView.userInteractionEnabled = true
        tapView.addGestureRecognizer(tap)
    }

    func handleTap(sender: UITapGestureRecognizer? = nil) {
        let tapAlert = UIAlertController(title: "hmmm...", message: "this actually worked?", preferredStyle: UIAlertControllerStyle.Alert)
        tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
        self.presentViewController(tapAlert, animated: true, completion: nil)
    }
}

Does Java SE 8 have Pairs or Tuples?

Eclipse Collections has Pair and all combinations of primitive/object Pairs (for all eight primitives).

The Tuples factory can create instances of Pair, and the PrimitiveTuples factory can be used to create all combinations of primitive/object pairs.

We added these before Java 8 was released. They were useful to implement key/value Iterators for our primitive maps, which we also support in all primitive/object combinations.

If you're willing to add the extra library overhead, you can use Stuart's accepted solution and collect the results into a primitive IntList to avoid boxing. We added new methods in Eclipse Collections 9.0 to allow for Int/Long/Double collections to be created from Int/Long/Double Streams.

IntList list = IntLists.mutable.withAll(intStream);

Note: I am a committer for Eclipse Collections.

What is the significance of load factor in HashMap?

For HashMap DEFAULT_INITIAL_CAPACITY = 16 and DEFAULT_LOAD_FACTOR = 0.75f it means that MAX number of ALL Entries in the HashMap = 16 * 0.75 = 12. When the thirteenth element will be added capacity (array size) of HashMap will be doubled! Perfect illustration answered this question: enter image description here image is taken from here:

https://javabypatel.blogspot.com/2015/10/what-is-load-factor-and-rehashing-in-hashmap.html

Unzip files programmatically in .net

I use this to either zip or unzip multiple files. The Regex stuff is not required, but I use it to change the date stamp and remove unwanted underscores. I use the empty string in the Compress >> zipPath string to prefix something to all files if required. Also, I usually comment out either Compress() or Decompress() based on what I am doing.

using System;
using System.IO.Compression;
using System.IO;
using System.Text.RegularExpressions;

namespace ZipAndUnzip
{
    class Program
    {
        static void Main(string[] args)
        {
            var directoryPath = new DirectoryInfo(@"C:\your_path\");

            Compress(directoryPath);
            Decompress(directoryPath);
        }

        public static void Compress(DirectoryInfo directoryPath)
        {
            foreach (DirectoryInfo directory in directoryPath.GetDirectories())
            {
                var path = directoryPath.FullName;
                var newArchiveName = Regex.Replace(directory.Name, "[0-9]{8}", "20130913");
                newArchiveName = Regex.Replace(newArchiveName, "[_]+", "_");
                string startPath = path + directory.Name;
                string zipPath = path + "" + newArchiveName + ".zip";

                ZipFile.CreateFromDirectory(startPath, zipPath);
            }

        }

        public static void Decompress(DirectoryInfo directoryPath)
        {
            foreach (FileInfo file in directoryPath.GetFiles())
            {
                var path = directoryPath.FullName;
                string zipPath = path + file.Name;
                string extractPath = Regex.Replace(path + file.Name, ".zip", "");

                ZipFile.ExtractToDirectory(zipPath, extractPath);
            }
        }


    }
}

How to comment/uncomment in HTML code

/* (opener) */ (closer)

for example,

<html>
 /*<p>Commented P Tag </p>*/
<html>

How to give a pandas/matplotlib bar graph custom colors

You can specify the color option as a list directly to the plot function.

from matplotlib import pyplot as plt
from itertools import cycle, islice
import pandas, numpy as np  # I find np.random.randint to be better

# Make the data
x = [{i:np.random.randint(1,5)} for i in range(10)]
df = pandas.DataFrame(x)

# Make a list by cycling through the colors you care about
# to match the length of your data.
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, len(df)))

# Specify this list of colors as the `color` option to `plot`.
df.plot(kind='bar', stacked=True, color=my_colors)

To define your own custom list, you can do a few of the following, or just look up the Matplotlib techniques for defining a color item by its RGB values, etc. You can get as complicated as you want with this.

my_colors = ['g', 'b']*5 # <-- this concatenates the list to itself 5 times.
my_colors = [(0.5,0.4,0.5), (0.75, 0.75, 0.25)]*5 # <-- make two custom RGBs and repeat/alternate them over all the bar elements.
my_colors = [(x/10.0, x/20.0, 0.75) for x in range(len(df))] # <-- Quick gradient example along the Red/Green dimensions.

The last example yields the follow simple gradient of colors for me:

enter image description here

I didn't play with it long enough to figure out how to force the legend to pick up the defined colors, but I'm sure you can do it.

In general, though, a big piece of advice is to just use the functions from Matplotlib directly. Calling them from Pandas is OK, but I find you get better options and performance calling them straight from Matplotlib.

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

Sounds like you're calling sp_executesql with a VARCHAR statement, when it needs to be NVARCHAR.

e.g. This will give the error because @SQL needs to be NVARCHAR

DECLARE @SQL VARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

So:

DECLARE @SQL NVARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

"Cannot start compilation: the output path is not specified for module..."

I get this error too when creating a project in IntelliJ without using a template.

I have 2 SDKs installed: Amazon Corretto and java version 11.0.4 and so, what I do when I have this error is "change the SDK" it usually works fine with Corretto

to do that you need to click on File (in IntelliJ)/ Project Structure / Project / Project SDK: select corretto from the dropdown list (or check the option in your computer) as shown here

hope this will work for you too

Best, Constantin

Drawing circles with System.Drawing

     private void DrawEllipseRectangle(PaintEventArgs e)
        {
            Pen p = new Pen(Color.Black, 3);
            Rectangle r = new Rectangle(100, 100, 100, 100);
            e.Graphics.DrawEllipse(p, r);
        }
     private void Form1_Paint(object sender, PaintEventArgs e)
        {
            DrawEllipseRectangle(e);
        }

Adding click event listener to elements with the same class

You have to use querySelectorAll as you need to select all elements with the said class, again since querySelectorAll is an array you need to iterate it and add the event handlers

var deleteLinks = document.querySelectorAll('.delete');
for (var i = 0; i < deleteLinks.length; i++) {
    deleteLinks[i].addEventListener('click', function (event) {
        event.preventDefault();

        var choice = confirm("sure u want to delete?");
        if (choice) {
            return true;
        }
    });
}

jQuery addClass onClick

$(document).ready(function() {
    $('#Button').click(function() {
        $(this).addClass('active');
    });
});

should do the trick. unless you're loading the button with ajax. In which case you could do:

$('#Button').live('click', function() {...

Also remember not to use the same id more than once in your html code.

How to output in CLI during execution of PHP Unit tests?

It is possible to use Symfony\Component\Console\Output\TrimmedBufferOutput and then test the buffered output string like this:

use Symfony\Component\Console\Output\TrimmedBufferOutput;

//...
public function testSomething()
{
   $output = new TrimmedBufferOutput(999);
   $output->writeln('Do something in your code with the output class...');
   
   //test the output:
   $this->assertStringContainsString('expected string...', $output->fetch());   
}

Java socket API: How to tell if a connection has been closed?

Thats how I handle it

 while(true) {
        if((receiveMessage = receiveRead.readLine()) != null ) {  

        System.out.println("first message same :"+receiveMessage);
        System.out.println(receiveMessage);      

        }
        else if(receiveRead.readLine()==null)
        {

        System.out.println("Client has disconected: "+sock.isClosed()); 
        System.exit(1);
         }    } 

if the result.code == null

How to force DNS refresh for a website?

So if the issue is you just created a website and your clients or any given ISP DNS is cached and doesn't show new site yet. Yes all the other stuff applies ipconfig reset browser etc. BUT here's an Idea and something I do from time to time. You can set an alternate network ISP's DNS in the tcpip properties on the NIC properties. So if your ISP is say telstra and it hasn't propagated or updated you can specify an alternate service providers dns there. if that isp dns is updated before your native one hey presto you will see new site.But there is lots of other tricks you can do to determine propagation and get mail to work prior to the DNS updating. drop me a line if any one wants to chat.

Conversion failed when converting date and/or time from character string in SQL SERVER 2008

DECLARE @FromDate DATETIME

SET @FromDate =  'Jan 10 2016 12:00AM'

DECLARE @ToDate DATETIME
SET @ToDate = 'Jan 10 2017 12:00AM'

DECLARE @Dynamic_Qry nvarchar(Max) =''

SET @Dynamic_Qry='SELECT

(CONVERT(DATETIME,(SELECT 
     CASE WHEN (  ''IssueDate''   =''IssueDate'') THEN 
               EMP_DOCUMENT.ISSUE_DATE 
          WHEN (''IssueDate'' =''ExpiryDate'' ) THEN       
               EMP_DOCUMENT.EXPIRY_DATE ELSE EMP_DOCUMENT.APPROVED_ON END   
          CHEKDATE ), 101)  

)FROM CR.EMP_DOCUMENT  as EMP_DOCUMENT WHERE 1=1 

AND  (
      CONVERT(DATETIME,(SELECT 
        CASE WHEN (  ''IssueDate''   =''IssueDate'') THEN
                 EMP_DOCUMENT.ISSUE_DATE 
             WHEN (''IssueDate'' =''ExpiryDate'' ) THEN EMP_DOCUMENT.EXPIRY_DATE 
             ELSE EMP_DOCUMENT.APPROVED_ON END 
             CHEKDATE ), 101)  
) BETWEEN  '''+ CONVERT(CHAR(10), @FromDate, 126) +'''  AND '''+CONVERT(CHAR(10),  @ToDate , 126
)
+'''  
'

print @Dynamic_Qry

EXEC(@Dynamic_Qry) 

Update Multiple Rows in Entity Framework from a list of ids

something like below

var idList=new int[]{1, 2, 3, 4};
using (var db=new SomeDatabaseContext())
{
    var friends= db.Friends.Where(f=>idList.Contains(f.ID)).ToList();
    friends.ForEach(a=>a.msgSentBy='1234');
    db.SaveChanges();
}

UPDATE:

you can update multiple fields as below

friends.ForEach(a =>
                      {
                         a.property1 = value1;
                         a.property2 = value2;
                      });

How to compare only date in moment.js

In my case i did following code for compare 2 dates may it will help you ...

_x000D_
_x000D_
var date1 = "2010-10-20";_x000D_
var date2 = "2010-10-20";_x000D_
var time1 = moment(date1).format('YYYY-MM-DD');_x000D_
var time2 = moment(date2).format('YYYY-MM-DD');_x000D_
if(time2 > time1){_x000D_
 console.log('date2 is Greter than date1');_x000D_
}else if(time2 > time1){_x000D_
 console.log('date2 is Less than date1');_x000D_
}else{_x000D_
 console.log('Both date are same');_x000D_
}
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

How to make grep only match if the entire line matches?

Here is what I do, though using anchors is the best way:

grep -w "ABB.log " a.tmp

How to match a substring in a string, ignoring case

a = "MandY"
alow = a.lower()
if "mandy" in alow:
    print "true"

work around

Get current URL path in PHP

it should be :

$_SERVER['REQUEST_URI'];

Take a look at : Get the full URL in PHP

plot.new has not been called yet

If someone is using print function (for example, with mtext), then firstly depict a null plot:

plot(0,type='n',axes=FALSE,ann=FALSE)

and then print with newpage = F

print(data, newpage = F)

Target class controller does not exist - Laravel 8

In this issue, I just do add namespace like below and it works

enter image description here

How to put a jpg or png image into a button in HTML

<a href="#">
        <img src="p.png"></img>
    </a>

Is there a combination of "LIKE" and "IN" in SQL?

If you want to make your statement easily readable, then you can use REGEXP_LIKE (available from Oracle version 10 onwards).

An example table:

SQL> create table mytable (something)
  2  as
  3  select 'blabla' from dual union all
  4  select 'notbla' from dual union all
  5  select 'ofooof' from dual union all
  6  select 'ofofof' from dual union all
  7  select 'batzzz' from dual
  8  /

Table created.

The original syntax:

SQL> select something
  2    from mytable
  3   where something like 'bla%'
  4      or something like '%foo%'
  5      or something like 'batz%'
  6  /

SOMETH
------
blabla
ofooof
batzzz

3 rows selected.

And a simple looking query with REGEXP_LIKE

SQL> select something
  2    from mytable
  3   where regexp_like (something,'^bla|foo|^batz')
  4  /

SOMETH
------
blabla
ofooof
batzzz

3 rows selected.

BUT ...

I would not recommend it myself due to the not-so-good performance. I'd stick with the several LIKE predicates. So the examples were just for fun.

C function that counts lines in file

You're opening a file, then passing the file pointer to a function that only wants a file name to open the file itself. You can simplify your call to;

void main(void)
{
  printf("LINES: %d\n",countlines("Test.txt"));
}

EDIT: You're changing the question around so it's very hard to answer; at first you got your change to main() wrong, you forgot that the first parameter is argc, so it crashed. Now you have the problem of;

if (fp == NULL);   // <-- note the extra semicolon that is the only thing 
                   //     that runs conditionally on the if 
  return 0;        // Always runs and returns 0

which will always return 0. Remove that extra semicolon, and you should get a reasonable count.

Email address validation using ASP.NET MVC data type attributes

Try Html.EditorFor helper method instead of Html.TextBoxFor.

How to preserve insertion order in HashMap?

HashMap is unordered per the second line of the documentation:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Perhaps you can do as aix suggests and use a LinkedHashMap, or another ordered collection. This link can help you find the most appropriate collection to use.

Array of Matrices in MATLAB

Use cell arrays. This has an advantage over 3D arrays in that it does not require a contiguous memory space to store all the matrices. In fact, each matrix can be stored in a different space in memory, which will save you from Out-of-Memory errors if your free memory is fragmented. Here is a sample function to create your matrices in a cell array:

function result = createArrays(nArrays, arraySize)
    result = cell(1, nArrays);
    for i = 1 : nArrays
        result{i} = zeros(arraySize);
    end
end

To use it:

myArray = createArrays(requiredNumberOfArrays, [500 800]);

And to access your elements:

myArray{1}(2,3) = 10;

If you can't know the number of matrices in advance, you could simply use MATLAB's dynamic indexing to make the array as large as you need. The performance overhead will be proportional to the size of the cell array, and is not affected by the size of the matrices themselves. For example:

myArray{1} = zeros(500, 800);
if twoRequired, myArray{2} = zeros(500, 800); end

Javascript - removing undefined fields from an object

Here's a plain javascript (no library required) solution:

function removeUndefinedProps(obj) {
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop) && obj[prop] === undefined) {
            delete obj[prop];
        }
    }
}

Working demo: http://jsfiddle.net/jfriend00/djj5g5fu/

Extract specific columns from delimited file using Awk

I don't know if it's possible to do ranges in awk. You could do a for loop, but you would have to add handling to filter out the columns you don't want. It's probably easier to do this:

awk -F, '{OFS=",";print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$20,$21,$22,$23,$24,$25,$30,$33}' infile.csv > outfile.csv

something else to consider - and this faster and more concise:

cut -d "," -f1-10,20-25,30-33 infile.csv > outfile.csv

As to the second part of your question, I would probably write a script in perl that knows how to handle header rows, parsing the columns names from stdin or a file and then doing the filtering. It's probably a tool I would want to have for other things. I am not sure about doing in a one liner, although I am sure it can be done.

What is the difference between prefix and postfix operators?

i++ is post increment. The increment takes place after the value is returned.

Convert SQL Server result set into string

The following is a solution for MySQL (not SQL Server), i couldn't easily find a solution to this on stackoverflow for mysql, so i figured maybe this could help someone...

ref: https://forums.mysql.com/read.php?10,285268,285286#msg-285286

original query...

SELECT StudentId FROM Student WHERE condition = xyz

original result set...

StudentId
1236
7656
8990

new query w/ concat...

SELECT group_concat(concat_ws(',', StudentId) separator '; ') 
FROM Student 
WHERE condition = xyz

concat string result set...

StudentId
1236; 7656; 8990

note: change the 'separator' to whatever you would like

GLHF!

Checking if a folder exists using a .bat file

For a file:

if exist yourfilename (
  echo Yes 
) else (
  echo No
)

Replace yourfilename with the name of your file.

For a directory:

if exist yourfoldername\ (
  echo Yes 
) else (
  echo No
)

Replace yourfoldername with the name of your folder.

A trailing backslash (\) seems to be enough to distinguish between directories and ordinary files.

How to fade changing background image

Can I offer an alternative solution?

I had this same issue, and fade didn't work because it faded the entire element, not just the background. In my case the element was body, so I only wanted to fade the background.

An elegant way to tackle this is to class the element and use CSS3 transition for the background.

transition: background 0.5s linear;

When you change the background, either with toggleClass or with your code, $("#large-img").css('background-image', 'url('+$img+')'); it will fade as defined by the class.

Ruby on Rails: Where to define global constants?

As of Rails 4.2, you can use the config.x property:

# config/application.rb (or config/custom.rb if you prefer)
config.x.colours.options = %w[white blue black red green]
config.x.colours.default = 'white'

Which will be available as:

Rails.configuration.x.colours.options
# => ["white", "blue", "black", "red", "green"]
Rails.configuration.x.colours.default
# => "white"

Another method of loading custom config:

# config/colours.yml
default: &default
  options:
    - white
    - blue
    - black
    - red
    - green
  default: white
development:
  *default
production:
  *default
# config/application.rb
config.colours = config_for(:colours)
Rails.configuration.colours
# => {"options"=>["white", "blue", "black", "red", "green"], "default"=>"white"}
Rails.configuration.colours['default']
# => "white"

In Rails 5 & 6, you can use the configuration object directly for custom configuration, in addition to config.x. However, it can only be used for non-nested configuration:

# config/application.rb
config.colours = %w[white blue black red green]

It will be available as:

Rails.configuration.colours
# => ["white", "blue", "black", "red", "green"]

PHP - Getting the index of a element from a array

function Index($index) {
    $Count = count($YOUR_ARRAY);
    if ($index <= $Count) {
        $Keys = array_keys($YOUR_ARRAY);
        $Value = array_values($YOUR_ARRAY);
        return $Keys[$index] . ' = ' . $Value[$index];
    } else {
        return "Out of the ring";
    }
}

echo 'Index : ' . Index(0);

Replace the ( $YOUR_ARRAY )

How to make a new line or tab in <string> XML (eclipse/android)?

You can use \n for new line and \t for tabs. Also, extra spaces/tabs are just copied the way you write them in Strings.xml so just give a couple of spaces where ever you want them.

A better way to reach this would probably be using padding/margin in your view xml and splitting up your long text in different strings in your string.xml

Jquery function BEFORE form submission

Based on Wakas Bukhary answer, you could make it async by puting the last line in the response scope.

$('#myform').submit(function(event) {

  event.preventDefault(); //this will prevent the default submit
  var _this = $(this); //store form so it can be accessed later

  $.ajax('GET', 'url').then(function(resp) {

    // your code here 

   _this.unbind('submit').submit(); // continue the submit unbind preventDefault
  })  
}

Using Node.js require vs. ES6 import/export

The main advantages are syntactic:

  • More declarative/compact syntax
  • ES6 modules will basically make UMD (Universal Module Definition) obsolete - essentially removes the schism between CommonJS and AMD (server vs browser).

You are unlikely to see any performance benefits with ES6 modules. You will still need an extra library to bundle the modules, even when there is full support for ES6 features in the browser.

Groovy - How to compare the string?

This should be an answer

str2.equals( str )

If you want to ignore case

str2.equalsIgnoreCase( str )

Angular 2: Get Values of Multiple Checked Checkboxes

In Angular 2+ to 9 using Typescript

Source Link

enter image description here

we can use an object to bind multiple Checkbox

  checkboxesDataList = [
    {
      id: 'C001',
      label: 'Photography',
      isChecked: true
    },
    {
      id: 'C002',
      label: 'Writing',
      isChecked: true
    },
    {
      id: 'C003',
      label: 'Painting',
      isChecked: true
    },
    {
      id: 'C004',
      label: 'Knitting',
      isChecked: false
    },
    {
      id: 'C004',
      label: 'Dancing',
      isChecked: false
    },
    {
      id: 'C005',
      label: 'Gardening',
      isChecked: true
    },
    {
      id: 'C006',
      label: 'Drawing',
      isChecked: true
    },
    {
      id: 'C007',
      label: 'Gyming',
      isChecked: false
    },
    {
      id: 'C008',
      label: 'Cooking',
      isChecked: true
    },
    {
      id: 'C009',
      label: 'Scrapbooking',
      isChecked: false
    },
    {
      id: 'C010',
      label: 'Origami',
      isChecked: false
    }
  ]

In HTML Template use

  <ul class="checkbox-items">
    <li *ngFor="let item of checkboxesDataList">
      <input type="checkbox" [(ngModel)]="item.isChecked" (change)="changeSelection()">{{item.label}}
    </li>
  </ul>

To get selected checkboxes, add the following method in class

  // Selected item
  fetchSelectedItems() {
    this.selectedItemsList = this.checkboxesDataList.filter((value, index) => {
      return value.isChecked
    });
  }

  // IDs of selected item
  fetchCheckedIDs() {
    this.checkedIDs = []
    this.checkboxesDataList.forEach((value, index) => {
      if (value.isChecked) {
        this.checkedIDs.push(value.id);
      }
    });
  }

Why the switch statement cannot be applied on strings?

Late to the party, here's a solution I came up with some time ago, which completely abides to the requested syntax.

#include <uberswitch/uberswitch.hpp>

int main()
{
    uberswitch (std::string("raj"))
    {
        case ("sda"): /* ... */ break;  //notice the parenthesis around the value.
    }
}

Here's the code: https://github.com/falemagn/uberswitch

How do I initialize an empty array in C#?

In .NET 4.6 the preferred way is to use a new method, Array.Empty:

String[] a = Array.Empty<string>();

The implementation is succinct, using how static members in generic classes behave in .Net:

public static T[] Empty<T>()
{
    return EmptyArray<T>.Value;
}

// Useful in number of places that return an empty byte array to avoid
// unnecessary memory allocation.
internal static class EmptyArray<T>
{
    public static readonly T[] Value = new T[0];
}

(code contract related code removed for clarity)

See also:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)

128M == 134217728, the number you are seeing.

The memory limit is working fine. When it says it tried to allocate 32 bytes, that the amount requested by the last operation before failing.

Are you building any huge arrays or reading large text files? If so, remember to free any memory you don't need anymore, or break the task down into smaller steps.

How to create two columns on a web page?

I agree with @haha on this one, for the most part. But there are several cross-browser related issues with using the "float:right" and could ultimately give you more of a headache than you want. If you know what the widths are going to be for each column use a float:left on both and save yourself the trouble. Another thing you can incorporate into your methodology is build column classes into your CSS.

So try something like this:

CSS

.col-wrapper{width:960px; margin:0 auto;}
.col{margin:0 10px; float:left; display:inline;}
.col-670{width:670px;}
.col-250{width:250px;}

HTML

<div class="col-wrapper">
    <div class="col col-670">[Page Content]</div>
    <div class="col col-250">[Page Sidebar]</div>
</div>

Posting JSON Data to ASP.NET MVC

BeRecursive's answer is the one I used, so that we could standardize on Json.Net (we have MVC5 and WebApi 5 -- WebApi 5 already uses Json.Net), but I found an issue. When you have parameters in your route to which you're POSTing, MVC tries to call the model binder for the URI values, and this code will attempt to bind the posted JSON to those values.

Example:

[HttpPost]
[Route("Customer/{customerId:int}/Vehicle/{vehicleId:int}/Policy/Create"]
public async Task<JsonNetResult> Create(int customerId, int vehicleId, PolicyRequest policyRequest)

The BindModel function gets called three times, bombing on the first, as it tries to bind the JSON to customerId with the error: Error reading integer. Unexpected token: StartObject. Path '', line 1, position 1.

I added this block of code to the top of BindModel:

if (bindingContext.ValueProvider.GetValue(bindingContext.ModelName) != null) {
    return base.BindModel(controllerContext, bindingContext);
}

The ValueProvider, fortunately, has route values figured out by the time it gets to this method.

How to get a variable from a file to another file in Node.js

File FileOne.js:

module.exports = { ClientIDUnsplash : 'SuperSecretKey' };

File FileTwo.js:

var { ClientIDUnsplash } = require('./FileOne');

This example works best for React.

How do you push just a single Git branch (and no other branches)?

yes, just do the following

git checkout feature_x
git push origin feature_x

How to disable or enable viewpager swiping in android

If you want to extend it just because you need Not-Swipeable behaviour, you dont need to do it. ViewPager2 provides nice property called : isUserInputEnabled

How to remove array element in mongodb?

In Mongoose: from the document:

To remove a document from a subdocument array we may pass an object with a matching _id.

contact.phone.pull({ _id: itemId }) // remove
contact.phone.pull(itemId); // this also works

See Leonid Beschastny's answer for the correct answer.

Handling the TAB character in Java

Or you could just perform a trim() on the string to handle the case when people use spaces instead of tabs (unless you are reading makefiles)

Date format in dd/MM/yyyy hh:mm:ss

CREATE FUNCTION DBO.ConvertDateToVarchar
(
@DATE DATETIME
)

RETURNS VARCHAR(24) 
BEGIN
RETURN (SELECT CONVERT(VARCHAR(19),@DATE, 121))
END

An example of how to use getopts in bash

The problem with the original code is that:

  • h: expects parameter where it shouldn't, so change it into just h (without colon)
  • to expect -p any_string, you need to add p: to the argument list

Basically : after the option means it requires the argument.


The basic syntax of getopts is (see: man bash):

getopts OPTSTRING VARNAME [ARGS...]

where:

  • OPTSTRING is string with list of expected arguments,

    • h - check for option -h without parameters; gives error on unsupported options;
    • h: - check for option -h with parameter; gives errors on unsupported options;
    • abc - check for options -a, -b, -c; gives errors on unsupported options;
    • :abc - check for options -a, -b, -c; silences errors on unsupported options;

      Notes: In other words, colon in front of options allows you handle the errors in your code. Variable will contain ? in the case of unsupported option, : in the case of missing value.

  • OPTARG - is set to current argument value,

  • OPTERR - indicates if Bash should display error messages.

So the code can be:

#!/usr/bin/env bash
usage() { echo "$0 usage:" && grep " .)\ #" $0; exit 0; }
[ $# -eq 0 ] && usage
while getopts ":hs:p:" arg; do
  case $arg in
    p) # Specify p value.
      echo "p is ${OPTARG}"
      ;;
    s) # Specify strength, either 45 or 90.
      strength=${OPTARG}
      [ $strength -eq 45 -o $strength -eq 90 ] \
        && echo "Strength is $strength." \
        || echo "Strength needs to be either 45 or 90, $strength found instead."
      ;;
    h | *) # Display help.
      usage
      exit 0
      ;;
  esac
done

Example usage:

$ ./foo.sh 
./foo.sh usage:
    p) # Specify p value.
    s) # Specify strength, either 45 or 90.
    h | *) # Display help.
$ ./foo.sh -s 123 -p any_string
Strength needs to be either 45 or 90, 123 found instead.
p is any_string
$ ./foo.sh -s 90 -p any_string
Strength is 90.
p is any_string

See: Small getopts tutorial at Bash Hackers Wiki

How to use an arraylist as a prepared statement parameter

You may want to use setArray method as mentioned in the javadoc below:

http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setArray(int, java.sql.Array)

Sample Code:

PreparedStatement pstmt = 
                conn.prepareStatement("select * from employee where id in (?)");
Array array = conn.createArrayOf("VARCHAR", new Object[]{"1", "2","3"});
pstmt.setArray(1, array);
ResultSet rs = pstmt.executeQuery();

Shortcut key for commenting out lines of Python code in Spyder

Yes, there is a shortcut for commenting out lines in Python 3.6 (Spyder).

For Single Line Comment, you can use Ctrl+1. It will look like this #This is a sample piece of code

For multi-line comments, you can use Ctrl+4. It will look like this

#============= \#your piece of code \#some more code \#=============

Note : \ represents that the code is carried to another line.

How to stop line breaking in vim

Use :set nowrap .. works like a charm!

Remote debugging Tomcat with Eclipse

Many of the above answers are correct, but remember that by default the debugger will listen on localhost, which means you can debug only if you're running the debugging client (for example, the IDE) on the same machine.

If you are debugging a remote server you will need to specify the correct IP address on that server to listen on, for example

JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=10.1.1.33:8000,server=y,suspend=n"

catalina.sh jpda start

Note that the address is now 10.1.1.33:8000

Of course, you can also check which IP is actually being used, by running

netstat -an

This command is valid on both windows and Linux - you just need to filter out the port with find (Windows) or grep (Linux).

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Find the folder containing the shared library libopencv_core.so.2.4 using the following command line.

sudo find / -name "libopencv_core.so.2.4*"

Then I got the result:

 /usr/local/lib/libopencv_core.so.2.4.

Create a file called /etc/ld.so.conf.d/opencv.conf and write to it the path to the folder where the binary is stored.For example, I wrote /usr/local/lib/ to my opencv.conf file. Run the command line as follows.

sudo ldconfig -v

Try to run the command again.

Unable to make the session state request to the session state server

One of my clients was facing the same issue. Following steps are taken to fix this.

 (1) Open Run. 

 (2) Type Services.msc

 (3) Select ASP.NET State Service

 (4) Right Click and Start it.

converting string to long in python

Well, longs can't hold anything but integers.

One option is to use a float: float('234.89')

The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))

>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L

How to convert binary string value to decimal

int i = Integer.parseInt(c, 2);

Display date/time in user's locale format and time offset

Once you have your date object constructed, here's a snippet for the conversion:

The function takes a UTC formatted Date object and format string.
You will need a Date.strftime prototype.

function UTCToLocalTimeString(d, format) {
    if (timeOffsetInHours == null) {
        timeOffsetInHours = (new Date().getTimezoneOffset()/60) * (-1);
    }
    d.setHours(d.getHours() + timeOffsetInHours);

    return d.strftime(format);
}

"dd/mm/yyyy" date format in excel through vba

Your issue is with attempting to change your month by adding 1. 1 in date serials in Excel is equal to 1 day. Try changing your month by using the following:

NewDate = Format(DateAdd("m",1,StartDate),"dd/mm/yyyy")

Mongoose's find method with $or condition does not work properly

async() => {
let body = await model.find().or([
  { name: 'something'},
  { nickname: 'somethang'}
]).exec();
console.log(body);
}
/* Gives an array of the searched query!
returns [] if not found */

Setting unique Constraint with fluent API?

modelBuilder.Property(x => x.FirstName).IsUnicode().IsRequired().HasMaxLength(50);

How to get tf.exe (TFS command line client)?

You need to install Team Explorer, it's best to install the version of Team Explorer that matches the version of TFS you are using e.g. if you're using TFS 2010 then install Team Explorer 2010.

2012 version http://www.microsoft.com/en-gb/download/details.aspx?id=30656

2013 version http://www.microsoft.com/en-us/download/details.aspx?id=40776

2019 version https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=TeamExplorer&rel=16

You also might be interested in the TFS power tools. They add some extra command line features (using tfpt.exe) and also add some extra IDE features.

How to get the separate digits of an int number?

simple solution

public static void main(String[] args) {
    int v = 12345;
    while (v > 0){
        System.out.println(v % 10);
        v /= 10;
    }
}

What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

Format with Currency format string

=Format(Fields!Price.Value, "C")

It will give you 2 decimal places with "$" prefixed.

You can find other format strings on MSDN: Adding Style and Formatting to a ReportViewer Report

Note: The MSDN article has been archived to the "VS2005_General" document, which is no longer directly accessible online. Here is the excerpt of the formatting strings referenced:

Formatting Numbers

The following table lists common .NET Framework number formatting strings.

Format string, Name

C or c Currency

D or d Decimal

E or e Scientific

F or f Fixed-point

G or g General

N or n Number

P or p Percentage

R or r Round-trip

X or x Hexadecimal

You can modify many of the format strings to include a precision specifier that defines the number of digits to the right of the

decimal point. For example, a formatting string of D0 formats the number so that it has no digits after the decimal point. You

can also use custom formatting strings, for example, #,###.

Formatting Dates

The following table lists common .NET Framework date formatting strings.

Format string, Name

d Short date

D Long date

t Short time

T Long time

f Full date/time (short time)

F Full date/time (long time)

g General date/time (short time)

G General date/time (long time)

M or m Month day

R or r RFC1123 pattern

Y or y Year month

You can also a use custom formatting strings; for example, dd/MM/yy. For more information about .NET Framework formatting strings, see Formatting Types.

Disable / Check for Mock Location (prevent gps spoofing)

try this code its very simple and usefull

  public boolean isMockLocationEnabled() {
        boolean isMockLocation = false;
        try {
            //if marshmallow
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                AppOpsManager opsManager = (AppOpsManager) getApplicationContext().getSystemService(Context.APP_OPS_SERVICE);
                isMockLocation = (opsManager.checkOp(AppOpsManager.OPSTR_MOCK_LOCATION, android.os.Process.myUid(), BuildConfig.APPLICATION_ID)== AppOpsManager.MODE_ALLOWED);
            } else {
                // in marshmallow this will always return true
                isMockLocation = !android.provider.Settings.Secure.getString(getApplicationContext().getContentResolver(), "mock_location").equals("0");
            }
        } catch (Exception e) {
            return isMockLocation;
        }
        return isMockLocation;
    }

You need to use a Theme.AppCompat theme (or descendant) with this activity

You have came to this because you want to apply Material Design in your theme style in previous sdk versions to 21. ActionBarActivity requires AppThemeso if you also want to prevent your own customization about your AppTheme, only you have to change in your styles.xml (previous to sdk 21) so this way, can inherit for an App Compat theme.

<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">

for this:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

display data from SQL database into php/ html table

Here's a simple function I wrote to display tabular data without having to input each column name: (Also, be aware: Nested looping)

function display_data($data) {
    $output = '<table>';
    foreach($data as $key => $var) {
        $output .= '<tr>';
        foreach($var as $k => $v) {
            if ($key === 0) {
                $output .= '<td><strong>' . $k . '</strong></td>';
            } else {
                $output .= '<td>' . $v . '</td>';
            }
        }
        $output .= '</tr>';
    }
    $output .= '</table>';
    echo $output;
}

UPDATED FUNCTION BELOW

Hi Jack,

your function design is fine, but this function always misses the first dataset in the array. I tested that.

Your function is so fine, that many people will use it, but they will always miss the first dataset. That is why I wrote this amendment.

The missing dataset results from the condition if key === 0. If key = 0 only the columnheaders are written, but not the data which contains $key 0 too. So there is always missing the first dataset of the array.

You can avoid that by moving the if condition above the second foreach loop like this:

function display_data($data) {
    $output = "<table>";
    foreach($data as $key => $var) {
        //$output .= '<tr>';
        if($key===0) {
            $output .= '<tr>';
            foreach($var as $col => $val) {
                $output .= "<td>" . $col . '</td>';
            }
            $output .= '</tr>';
            foreach($var as $col => $val) {
                $output .= '<td>' . $val . '</td>';
            }
            $output .= '</tr>';
        }
        else {
            $output .= '<tr>';
            foreach($var as $col => $val) {
                $output .= '<td>' . $val . '</td>';
            }
            $output .= '</tr>';
        }
    }
    $output .= '</table>';
    echo $output;
}

Best regards and thanks - Axel Arnold Bangert - Herzogenrath 2016

and another update that removes redundant code blocks that hurt maintainability of the code.

function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
    $output .= '<tr>';
    foreach($var as $k => $v) {
        if ($key === 0) {
            $output .= '<td><strong>' . $k . '</strong></td>';
        } else {
            $output .= '<td>' . $v . '</td>';
        }
    }
    $output .= '</tr>';
}
$output .= '</table>';
echo $output;

}

Create unique constraint with null columns

I think there is a semantic problem here. In my view, a user can have a (but only one) favourite recipe to prepare a specific menu. (The OP has menu and recipe mixed up; if I am wrong: please interchange MenuId and RecipeId below) That implies that {user,menu} should be a unique key in this table. And it should point to exactly one recipe. If the user has no favourite recipe for this specific menu no row should exist for this {user,menu} key pair. Also: the surrogate key (FaVouRiteId) is superfluous: composite primary keys are perfectly valid for relational-mapping tables.

That would lead to the reduced table definition:

CREATE TABLE Favorites
( UserId uuid NOT NULL REFERENCES users(id)
, MenuId uuid NOT NULL REFERENCES menus(id)
, RecipeId uuid NOT NULL REFERENCES recipes(id)
, PRIMARY KEY (UserId, MenuId)
);

Python for and if on one line

Found this one:

[x for (i,x) in enumerate(my_list) if my_list[i] == "two"]

Will print:

["two"]

Change IPython/Jupyter notebook working directory

%pwd  #look at the current work dir
%cd   #change to the dir you want 

You have not accepted the license agreements of the following SDK components

Go to your $ANDROID_HOME/tools/bin and fire the cmd

./sdkmanager --licenses

Accept All licenses listed there.

After this just go to the licenses folder in sdk and check that it's having these five files:

android-sdk-license, android-googletv-license, android-sdk-preview-license, google-gdk-license, mips-android-sysimage-license

Give a retry and build again, still jenkins giving 'licenses not accepted' then you have to give full permission to your 'sdk' directory and all it's parent directories. Here is the command:

sudo chmod -R 777 /opt/

If you having sdk in /opt/ directory.

How to add "required" attribute to mvc razor viewmodel text input editor

A newer way to do this in .NET Core is with TagHelpers.

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro

Building on these examples (MaxLength, Label), you can extend the existing TagHelper to suit your needs.

RequiredTagHelper.cs

using Microsoft.AspNetCore.Razor.TagHelpers;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.Linq;

namespace ProjectName.TagHelpers
{
    [HtmlTargetElement("input", Attributes = "asp-for")]
    public class RequiredTagHelper : TagHelper
    {
        public override int Order
        {
            get { return int.MaxValue; }
        }

        [HtmlAttributeName("asp-for")]
        public ModelExpression For { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output); 

            if (context.AllAttributes["required"] == null)
            {
                var isRequired = For.ModelExplorer.Metadata.ValidatorMetadata.Any(a => a is RequiredAttribute);
                if (isRequired)
                {
                    var requiredAttribute = new TagHelperAttribute("required");
                    output.Attributes.Add(requiredAttribute);
                }
            }
        }
    }
}

You'll then need to add it to be used in your views:

_ViewImports.cshtml

@using ProjectName
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "*, ProjectName"

Given the following model:

Foo.cs

using System;
using System.ComponentModel.DataAnnotations;

namespace ProjectName.Models
{
    public class Foo
    {
        public int Id { get; set; }

        [Required]
        [Display(Name = "Full Name")]
        public string Name { get; set; }
    }
}

and view (snippet):

New.cshtml

<label asp-for="Name"></label>
<input asp-for="Name"/>

Will result in this HTML:

<label for="Name">Full Name</label>
<input required type="text" data-val="true" data-val-required="The Full Name field is required." id="Name" name="Name" value=""/>

I hope this is helpful to anyone with same question but using .NET Core.

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

Although Simon Cross's answer is accepted and correct, I thought I would beef it up a bit with an example (Android) of what needs to be done. I'll keep it as general as I can and focus on just the question. Personally I wound up storing things in a database so the loading was smooth, but that requires a CursorAdapter and ContentProvider which is a bit out of scope here.

I came here myself and then thought, now what?!

The Issue

Just like user3594351, I was noticing the friend data was blank. I found this out by using the FriendPickerFragment. What worked three months ago, no longer works. Even Facebook's examples broke. So my issue was 'How Do I create FriendPickerFragment by hand?

What Did Not Work

Option #1 from Simon Cross was not strong enough to invite friends to the app. Simon Cross also recommended the Requests Dialog, but that would only allow five requests at a time. The requests dialog also showed the same friends during any given Facebook logged in session. Not useful.

What Worked (Summary)

Option #2 with some hard work. You must make sure you fulfill Facebook's new rules: 1.) You're a game 2.) You have a Canvas app (Web Presence) 3.) Your app is registered with Facebook. It is all done on the Facebook developer website under Settings.

To emulate the friend picker by hand inside my app I did the following:

  1. Create a tab activity that shows two fragments. Each fragment shows a list. One fragment for available friend (/me/friends) and another for invitable friends (/me/invitable_friends). Use the same fragment code to render both tabs.
  2. Create an AsyncTask that will get the friend data from Facebook. Once that data is loaded, toss it to the adapter which will render the values to the screen.

Details

The AsynchTask

private class DownloadFacebookFriendsTask extends AsyncTask<FacebookFriend.Type, Boolean, Boolean> {

    private final String TAG = DownloadFacebookFriendsTask.class.getSimpleName();
    GraphObject graphObject;
    ArrayList<FacebookFriend> myList = new ArrayList<FacebookFriend>();

    @Override
    protected Boolean doInBackground(FacebookFriend.Type... pickType) {
        //
        // Determine Type
        //
        String facebookRequest;
        if (pickType[0] == FacebookFriend.Type.AVAILABLE) {
            facebookRequest = "/me/friends";
        } else {
            facebookRequest = "/me/invitable_friends";
        }

        //
        // Launch Facebook request and WAIT.
        //
        new Request(
            Session.getActiveSession(),
            facebookRequest,
            null,
            HttpMethod.GET,
            new Request.Callback() {
                public void onCompleted(Response response) {
                    FacebookRequestError error = response.getError();
                    if (error != null && response != null) {
                        Log.e(TAG, error.toString());
                    } else {
                        graphObject = response.getGraphObject();
                    }
                }
            }
        ).executeAndWait();

        //
        // Process Facebook response
        //
        //
        if (graphObject == null) {
            return false;
        }

        int numberOfRecords = 0;
        JSONArray dataArray = (JSONArray) graphObject.getProperty("data");
        if (dataArray.length() > 0) {

            // Ensure the user has at least one friend ...
            for (int i = 0; i < dataArray.length(); i++) {

                JSONObject jsonObject = dataArray.optJSONObject(i);
                FacebookFriend facebookFriend = new FacebookFriend(jsonObject, pickType[0]);

                if (facebookFriend.isValid()) {
                    numberOfRecords++;

                    myList.add(facebookFriend);
                }
            }
        }

        // Make sure there are records to process
        if (numberOfRecords > 0){
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected void onProgressUpdate(Boolean... booleans) {
        // No need to update this, wait until the whole thread finishes.
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (result) {
            /*
            User the array "myList" to create the adapter which will control showing items in the list.
             */

        } else {
            Log.i(TAG, "Facebook Thread unable to Get/Parse friend data. Type = " + pickType);
        }
    }
}

The FacebookFriend class I created

public class FacebookFriend {

    String facebookId;
    String name;
    String pictureUrl;
    boolean invitable;
    boolean available;
    boolean isValid;
    public enum Type {AVAILABLE, INVITABLE};

    public FacebookFriend(JSONObject jsonObject, Type type) {
        //
        //Parse the Facebook Data from the JSON object.
        //
        try {
            if (type == Type.INVITABLE) {
                //parse /me/invitable_friend
                this.facebookId =  jsonObject.getString("id");
                this.name = jsonObject.getString("name");

                // Handle the picture data.
                JSONObject pictureJsonObject = jsonObject.getJSONObject("picture").getJSONObject("data");
                boolean isSilhouette = pictureJsonObject.getBoolean("is_silhouette");
                if (!isSilhouette) {
                    this.pictureUrl = pictureJsonObject.getString("url");

                } else {
                    this.pictureUrl = "";
                }

                this.invitable = true;
            } else {
                // Parse /me/friends
                this.facebookId =  jsonObject.getString("id");
                this.name = jsonObject.getString("name");
                this.available = true;
                this.pictureUrl = "";
            }

            isValid = true;
        } catch (JSONException e) {
            Log.w("#", "Warnings - unable to process Facebook JSON: " + e.getLocalizedMessage());
        }
    }
}

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

Observe if the view has the model required:

View

@model IEnumerable<WFAccess.Models.ViewModels.SiteViewModel>

<div class="row">
    <table class="table table-striped table-hover table-width-custom">
        <thead>
            <tr>
....

Controller

[HttpGet]
public ActionResult ListItems()
{
    SiteStore site = new SiteStore();
    site.GetSites();

    IEnumerable<SiteViewModel> sites =
        site.SitesList.Select(s => new SiteViewModel
        {
            Id = s.Id,
            Type = s.Type
        });

    return PartialView("_ListItems", sites);
}

In my case I Use a partial view but runs in normal views

Create an empty data.frame

Just initialize it with empty vectors:

df <- data.frame(Date=as.Date(character()),
                 File=character(), 
                 User=character(), 
                 stringsAsFactors=FALSE) 

Here's an other example with different column types :

df <- data.frame(Doubles=double(),
                 Ints=integer(),
                 Factors=factor(),
                 Logicals=logical(),
                 Characters=character(),
                 stringsAsFactors=FALSE)

str(df)
> str(df)
'data.frame':   0 obs. of  5 variables:
 $ Doubles   : num 
 $ Ints      : int 
 $ Factors   : Factor w/ 0 levels: 
 $ Logicals  : logi 
 $ Characters: chr 

N.B. :

Initializing a data.frame with an empty column of the wrong type does not prevent further additions of rows having columns of different types.
This method is just a bit safer in the sense that you'll have the correct column types from the beginning, hence if your code relies on some column type checking, it will work even with a data.frame with zero rows.

ASP.NET MVC Ajax Error handling

For handling errors from ajax calls on the client side, you assign a function to the error option of the ajax call.

To set a default globally, you can use the function described here: http://api.jquery.com/jQuery.ajaxSetup.

Combining two lists and removing duplicates, without removing duplicates in original list

resulting_list = first_list + [i for i in second_list if i not in first_list]

How many concurrent requests does a single Flask process receive?

Flask will process one request per thread at the same time. If you have 2 processes with 4 threads each, that's 8 concurrent requests.

Flask doesn't spawn or manage threads or processes. That's the responsability of the WSGI gateway (eg. gunicorn).

Java: parse int value from a char

Try the following:

str1="2345";
int x=str1.charAt(2)-'0';
//here x=4;

if u subtract by char '0', the ASCII value needs not to be known.

Get div tag scroll position using JavaScript

you use the scrollTop attribute

var position = document.getElementById('id').scrollTop;

Error: Module not specified (IntelliJ IDEA)

This happened to me when I started to work with a colleque's project.

He was using jdk 12.0.2 .

If you are suspicious jdk difference might be the case (Your IDE complains about SDK, JDK etc.):

  1. Download the appropriate jdk
  2. Move new jdk to the folder of your choice. (I use C:\Program Files\Java)
  3. On Intellij, click to the dropdown on top middle bar. Click Edit Configurations. Change jdk.
  4. File -> Invalidate Caches and Restart.

Calling Javascript function from server side

This works for me. Hope it will work for you too.

ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "Test();", true);

I have edited the html page which you have provided. The updated page is as below

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>My Page</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function Test() {
                alert("Hello Test!!!!");
                $('#ButtonRow').css("display", "block");
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <table>
            <tr>
                <td>
                    <asp:RadioButtonList ID="SearchCategory" runat="server" RepeatDirection="Horizontal"
                        BorderStyle="Solid">
                        <asp:ListItem>Merchant</asp:ListItem>
                        <asp:ListItem>Store</asp:ListItem>
                        <asp:ListItem>Terminal</asp:ListItem>
                    </asp:RadioButtonList>
                </td>
            </tr>
            <tr id="ButtonRow" style="display: none">
                <td>
                    <asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
                </td>
            </tr>
        </table>
        </form>
    </body>
    </html>

    <script type="text/javascript">

        $("#<%=SearchCategory.ClientID%> input").change(function () {
            alert("hi");
            $("#ButtonRow").show();
        });
    </script>

A method to count occurrences in a list

Your outer loop is looping over all the words in the list. It's unnecessary and will cause you problems. Remove it and it should work properly.

Android app unable to start activity componentinfo

Your null pointer exception seems to be on this line:

String url = intent.getExtras().getString("userurl");

because intent.getExtras() returns null when the intent doesn't have any extras.

You have to realize that this piece of code:

Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);

doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass and if that doesn't exist, your app crashes.

Also, there is no such thing as "android.intent.action.start" so the manifest should look more like:

<activity android:name=".start" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name= ".Main">
</activity>

I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

There is also

which aims

  • To encode entire script in a proprietary PHP application
  • To encode some classes and/or functions in a proprietary PHP application
  • To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe.
  • To do the feasibility study for a PHP to C converter

The extension is available from PECL.

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

Check all of the places where you are assigning something to sonEntities. The link you referenced distinctly points out creating a new HashSet but you can have this error anytime you reassign the set. For example:

public void setChildren(Set<SonEntity> aSet)
{
    this.sonEntities = aSet; //This will override the set that Hibernate is tracking.
}

Usually you want to only "new" the set once in a constructor. Any time you want to add or delete something to the list you have to modify the contents of the list instead of assigning a new list.

To add children:

public void addChild(SonEntity aSon)
{
    this.sonEntities.add(aSon);
}

To remove children:

public void removeChild(SonEntity aSon)
{
    this.sonEntities.remove(aSon);
}

Releasing memory in Python

eryksun has answered question #1, and I've answered question #3 (the original #4), but now let's answer question #2:

Why does it release 50.5mb in particular - what is the amount that is released based on?

What it's based on is, ultimately, a whole series of coincidences inside Python and malloc that are very hard to predict.

First, depending on how you're measuring memory, you may only be measuring pages actually mapped into memory. In that case, any time a page gets swapped out by the pager, memory will show up as "freed", even though it hasn't been freed.

Or you may be measuring in-use pages, which may or may not count allocated-but-never-touched pages (on systems that optimistically over-allocate, like linux), pages that are allocated but tagged MADV_FREE, etc.

If you really are measuring allocated pages (which is actually not a very useful thing to do, but it seems to be what you're asking about), and pages have really been deallocated, two circumstances in which this can happen: Either you've used brk or equivalent to shrink the data segment (very rare nowadays), or you've used munmap or similar to release a mapped segment. (There's also theoretically a minor variant to the latter, in that there are ways to release part of a mapped segment—e.g., steal it with MAP_FIXED for a MADV_FREE segment that you immediately unmap.)

But most programs don't directly allocate things out of memory pages; they use a malloc-style allocator. When you call free, the allocator can only release pages to the OS if you just happen to be freeing the last live object in a mapping (or in the last N pages of the data segment). There's no way your application can reasonably predict this, or even detect that it happened in advance.

CPython makes this even more complicated—it has a custom 2-level object allocator on top of a custom memory allocator on top of malloc. (See the source comments for a more detailed explanation.) And on top of that, even at the C API level, much less Python, you don't even directly control when the top-level objects are deallocated.

So, when you release an object, how do you know whether it's going to release memory to the OS? Well, first you have to know that you've released the last reference (including any internal references you didn't know about), allowing the GC to deallocate it. (Unlike other implementations, at least CPython will deallocate an object as soon as it's allowed to.) This usually deallocates at least two things at the next level down (e.g., for a string, you're releasing the PyString object, and the string buffer).

If you do deallocate an object, to know whether this causes the next level down to deallocate a block of object storage, you have to know the internal state of the object allocator, as well as how it's implemented. (It obviously can't happen unless you're deallocating the last thing in the block, and even then, it may not happen.)

If you do deallocate a block of object storage, to know whether this causes a free call, you have to know the internal state of the PyMem allocator, as well as how it's implemented. (Again, you have to be deallocating the last in-use block within a malloced region, and even then, it may not happen.)

If you do free a malloced region, to know whether this causes an munmap or equivalent (or brk), you have to know the internal state of the malloc, as well as how it's implemented. And this one, unlike the others, is highly platform-specific. (And again, you generally have to be deallocating the last in-use malloc within an mmap segment, and even then, it may not happen.)

So, if you want to understand why it happened to release exactly 50.5mb, you're going to have to trace it from the bottom up. Why did malloc unmap 50.5mb worth of pages when you did those one or more free calls (for probably a bit more than 50.5mb)? You'd have to read your platform's malloc, and then walk the various tables and lists to see its current state. (On some platforms, it may even make use of system-level information, which is pretty much impossible to capture without making a snapshot of the system to inspect offline, but luckily this isn't usually a problem.) And then you have to do the same thing at the 3 levels above that.

So, the only useful answer to the question is "Because."

Unless you're doing resource-limited (e.g., embedded) development, you have no reason to care about these details.

And if you are doing resource-limited development, knowing these details is useless; you pretty much have to do an end-run around all those levels and specifically mmap the memory you need at the application level (possibly with one simple, well-understood, application-specific zone allocator in between).

Avoid line break between html elements

nobr is too unreliable, use tables

<table>
      <tr>
          <td> something </td>
          <td> something </td>
      </tr>
</table>

It all goes on the same line, everything is level with eachother, and you have much more freedom if you want to change something later.

Java JTable getting the data of the selected row

using from ListSelectionModel:

ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
  public void valueChanged(ListSelectionEvent e) {
    String selectedData = null;

    int[] selectedRow = table.getSelectedRows();
    int[] selectedColumns = table.getSelectedColumns();

    for (int i = 0; i < selectedRow.length; i++) {
      for (int j = 0; j < selectedColumns.length; j++) {
        selectedData = (String) table.getValueAt(selectedRow[i], selectedColumns[j]);
      }
    }
    System.out.println("Selected: " + selectedData);
  }

});

see here.

jQuery - how to write 'if not equal to' (opposite of ==)

== => !=

=== => !==

Equal and its opposite

How to set the java.library.path from Eclipse

I think there is another reason for wanting to set java.library.path. Subversion comes with many libraries and Eclipse won't see these unless java.library.path can be appended. For example I'm on OS-X, so the libraries are under \opt\subversion\lib. There are a lot of them and I'd like to keep them where they are (not copy them into a standard lib directory).

Project settings won't fix this.

Can't find/install libXtst.so.6?

EDIT: As mentioned by Stephen Niedzielski in his comment, the issue seems to come from the 32-bit being of the JRE, which is de facto, looking for the 32-bit version of libXtst6. To install the required version of the library:

$ sudo apt-get install libxtst6:i386

Type:

$ sudo apt-get update
$ sudo apt-get install libxtst6

If this isn’t OK, type:

$ sudo updatedb
$ locate libXtst

it should return something like:

/usr/lib/x86_64-linux-gnu/libXtst.so.6       # Mine is OK
/usr/lib/x86_64-linux-gnu/libXtst.so.6.1.0

If you do not have libXtst.so.6 but do have libXtst.so.6.X.X create a symbolic link:

$ cd /usr/lib/x86_64-linux-gnu/
$ ln -s libXtst.so.6 libXtst.so.6.X.X

Hope this helps.

How to make an Android device vibrate? with different frequency?

Try:

import android.os.Vibrator;
...
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
    //deprecated in API 26 
    v.vibrate(500);
}

Note:

Don't forget to include permission in AndroidManifest.xml file:

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

Stop form refreshing page on submit

Personally I like to validate the form on submit and if there are errors, just return false.

$('form').submit(function() {

    var error;

   if ( !$('input').val() ) {
        error = true
    }

    if (error) {
         alert('there are errors')
         return false
    }

});

http://jsfiddle.net/dfyXY/

Get top n records for each group of grouped results

Snuffin solution seems quite slow to execute when you've got plenty of rows and Mark Byers/Rick James and Bluefeet solutions doesn't work on my environnement (MySQL 5.6) because order by is applied after execution of select, so here is a variant of Marc Byers/Rick James solutions to fix this issue (with an extra imbricated select):

select person, groupname, age
from
(
    select person, groupname, age,
    (@rn:=if(@prev = groupname, @rn +1, 1)) as rownumb,
    @prev:= groupname 
    from 
    (
        select person, groupname, age
        from persons 
        order by groupname ,  age desc, person
    )   as sortedlist
    JOIN (select @prev:=NULL, @rn :=0) as vars
) as groupedlist 
where rownumb<=2
order by groupname ,  age desc, person;

I tried similar query on a table having 5 millions rows and it returns result in less than 3 seconds

How to hide a View programmatically?

Try this:

linearLayout.setVisibility(View.GONE);

How to change language settings in R

type this first: system("defaults write org.R-project.R force.LANG en_US.UTF-8") then you will get a index number(in my case is 127)

then type: Sys.setenv(LANG = "en") then type the number and ENTER 127

How to add a "open git-bash here..." context menu to the windows explorer?

When you install git-scm found in "https://git-scm.com/downloads" uncheck the "Only show new options" located at the very bottom of the installation window

Make sure you check

  • Windows Explorer integration
    • Git Bash Here
    • Git GUI Here

Click Next and you're good to go!

How to write a UTF-8 file with Java?

Try using FileUtils.write from Apache Commons.

You should be able to do something like:

File f = new File("output.txt"); 
FileUtils.writeStringToFile(f, document.outerHtml(), "UTF-8");

This will create the file if it does not exist.

Free XML Formatting tool

If you use Notepad++, I would suggest installing the XML Tools plugin. You can beautify any XML content (indentation and line breaks) or linarize it. Also you can (auto-)validate your file and apply XSL transformation to it.

Download the latest zip and copy the extracted DLL to the plugins directory of your Notepad++ installation. Also, download the External libs and copy them to your %SystemRoot%\system32\ directory.

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

This issue will be fixed by adding the postinstall script below in your package.json.

It will be run after a npm install.

"scripts": {
   "postinstall": "ngcc"
}

Post adding the above code, run npm install

This works for me when upgrading to Angular 9+

How to check Django version

Basically the same as bcoughlan's answer, but here it is as an executable command:

$ python -c "import django; print(django.get_version())"
2.0

_csv.Error: field larger than field limit (131072)

The csv file might contain very huge fields, therefore increase the field_size_limit:

import sys
import csv

csv.field_size_limit(sys.maxsize)

sys.maxsize works for Python 2.x and 3.x. sys.maxint would only work with Python 2.x (SO: what-is-sys-maxint-in-python-3)

Update

As Geoff pointed out, the code above might result in the following error: OverflowError: Python int too large to convert to C long. To circumvent this, you could use the following quick and dirty code (which should work on every system with Python 2 and Python 3):

import sys
import csv
maxInt = sys.maxsize

while True:
    # decrease the maxInt value by factor 10 
    # as long as the OverflowError occurs.

    try:
        csv.field_size_limit(maxInt)
        break
    except OverflowError:
        maxInt = int(maxInt/10)

How to know the git username and email saved during configuration?

List all variables set in the config file, along with their values.

git config --list

If you are new to git then use the following commands to set a user name and email address.

Set user name

git config --global user.name "your Name"

Set user email

git config --global user.email "[email protected]"

Check user name

git config user.name

Check user email

git config user.email

File to import not found or unreadable: compass

Compass adjusts the way partials are imported. It allows importing components based solely on their name, without specifying the path.

Before you can do @import 'compass';, you should:

Install Compass as a Ruby gem:

gem install compass

After that, you should use Compass's own command line tool to compile your SASS code:

cd path/to/your/project/
compass compile

Note that Compass reqiures a configuration file called config.rb. You should create it for Compass to work.

The minimal config.rb can be as simple as this:

css_dir =   "css"
sass_dir =  "sass"

And your SASS code should reside in sass/.

Instead of creating a configuration file manually, you can create an empty Compass project with compass create <project-name> and then copy your SASS code inside it.

Note that if you want to use Compass extensions, you will have to:

  1. require them from the config.rb;
  2. import them from your SASS file.

More info here: http://compass-style.org/help/

Always pass weak reference of self into block in ARC?

You don't have to always use a weak reference. If your block is not retained, but executed and then discarded, you can capture self strongly, as it will not create a retain cycle. In some cases, you even want the block to hold the self until the completion of the block so it does not deallocate prematurely. If, however, you capture the block strongly, and inside capture self, it will create a retain cycle.

Get height and width of a layout programmatically

I had same issue but didn't want to draw on screen before measuring so I used this method of measuring the view before trying to get the height and width.

Example of use:

layoutView(view);
int height = view.getHeight();

//...

void layoutView(View view) {
    view.setDrawingCacheEnabled(true);
    int wrapContentSpec = 
        MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    view.measure(wrapContentSpec, wrapContentSpec);
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
}

How to get URI from an asset File?

Try this out, it works:

InputStream in_s = 
    getClass().getClassLoader().getResourceAsStream("TopBrands.xml");

If you get a Null Value Exception, try this (with class TopBrandData):

InputStream in_s1 =
    TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml");

What is the simplest SQL Query to find the second largest value?

SELECT MAX(Salary) FROM Employee WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )

This query will return the maximum salary, from the result - which not contains maximum salary from overall table.

how to delete installed library form react native project

From react-native --help

uninstall [options] uninstall and unlink native dependencies

Ex: react-native uninstall react-native-vector-icons

It will uninstall and unlink its dependencies.

Psexec "run as (remote) admin"

Simply add a -h after adding your credentials using a -u -p, and it will run with elevated privileges.

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

You must use LEFT JOIN instead of INNER JOIN

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

WampServer orange icon

Adding to what @Hitesh-sahu said you need all the VC++ redistribution packages for it to turn green. I referred to this thread from wampserver forum. You can install this little tool (check_vcredist) from the tools section here which will check if all the needed dependencies are installed (see attached image) and it will also provide links to missing ones. If you are using x64 version of Windows like I do and your wampserver does not turn green even after installing all the packages then uninstall and do a fresh installation again. Hope it helps.

enter image description here

How can I remove a style added with .css() function?

Use my Plugin :

$.fn.removeCss=function(all){
        if(all===true){
            $(this).removeAttr('class');
        }
        return $(this).removeAttr('style')
    }

For your case ,Use it as following :

$(<mySelector>).removeCss();

or

$(<mySelector>).removeCss(false);

if you want to remove also CSS defined in its classes :

$(<mySelector>).removeCss(true);

Use xml.etree.ElementTree to print nicely formatted xml files

You can use the function toprettyxml() from xml.dom.minidom in order to do that:

def prettify(elem):
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ElementTree.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="\t")

The idea is to print your Element in a string, parse it using minidom and convert it again in XML using the toprettyxml function.

Source: http://pymotw.com/2/xml/etree/ElementTree/create.html

What's the correct way to convert bytes to a hex string in Python 3?

If you want to convert b'\x61' to 97 or '0x61', you can try this:

[python3.5]
>>>from struct import *
>>>temp=unpack('B',b'\x61')[0] ## convert bytes to unsigned int
97
>>>hex(temp) ##convert int to string which is hexadecimal expression
'0x61'

Reference:https://docs.python.org/3.5/library/struct.html

How to get Activity's content view?

How about

View view = Activity.getCurrentFocus();

How to percent-encode URL parameters in Python?

In Python 3, urllib.quote has been moved to urllib.parse.quote and it does handle unicode by default.

>>> from urllib.parse import quote
>>> quote('/test')
'/test'
>>> quote('/test', safe='')
'%2Ftest'
>>> quote('/El Niño/')
'/El%20Ni%C3%B1o/'

Order a MySQL table by two columns

ORDER BY article_rating ASC , article_time DESC

DESC at the end will sort by both columns descending. You have to specify ASC if you want it otherwise

How to set text size in a button in html

Try this

<input type="submit" 
       value="HOME" 
       onclick="goHome()" 
       style="font-size : 20px; width: 100%; height: 100px;" /> 

How to select element using XPATH syntax on Selenium for Python?

HTML

<div id='a'>
  <div>
    <a class='click'>abc</a>
  </div>
</div>

You could use the XPATH as :

//div[@id='a']//a[@class='click']

output

<a class="click">abc</a>

That said your Python code should be as :

driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")

How do I select an element in jQuery by using a variable for the ID?

row = $("body").find('#' + row_id);

More importantly doing the additional body.find has no impact on performance. The proper way to do this is simply:

row = $('#' + row_id);

WCF Service, the type provided as the service attribute values…could not be found

I just hit this issue myself, and neither this nor any of the other answers on the net solved my issue. For me it was a strange one whereby the virtual directory had been created on a different branch in another source control server (basically, we upgraded from TFS 2010 to 2013) and the solution somehow remembered it's mapping.

Anyway, I clicked the "Create Virtual Directory" button again, in the Properties of the Service project. It gave me a message about being mapped to a different folder and would I like to update it. I clicked yes, and that fixed the issue.

How to minify php page html output?

All of the preg_replace() solutions above have issues of single line comments, conditional comments and other pitfalls. I'd recommend taking advantage of the well-tested Minify project rather than creating your own regex from scratch.

In my case I place the following code at the top of a PHP page to minify it:

function sanitize_output($buffer) {
    require_once('min/lib/Minify/HTML.php');
    require_once('min/lib/Minify/CSS.php');
    require_once('min/lib/JSMin.php');
    $buffer = Minify_HTML::minify($buffer, array(
        'cssMinifier' => array('Minify_CSS', 'minify'),
        'jsMinifier' => array('JSMin', 'minify')
    ));
    return $buffer;
}
ob_start('sanitize_output');

How to get a table creation script in MySQL Workbench?

1 use command

show create table test.location

enter image description here

  1. right click on selected row and choose Open Value In Viewer

  2. select tab Text enter image description here

Get width in pixels from element with style set with %?

Not a single answer does what was asked in vanilla JS, and I want a vanilla answer so I made it myself.

clientWidth includes padding and offsetWidth includes everything else (jsfiddle link). What you want is to get the computed style (jsfiddle link).

function getInnerWidth(elem) {
    return parseFloat(window.getComputedStyle(elem).width);
}

EDIT: getComputedStyle is non-standard, and can return values in units other than pixels. Some browsers also return a value which takes the scrollbar into account if the element has one (which in turn gives a different value than the width set in CSS). If the element has a scrollbar, you would have to manually calculate the width by removing the margins and paddings from the offsetWidth.

function getInnerWidth(elem) {
    var style = window.getComputedStyle(elem);
    return elem.offsetWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight) - parseFloat(style.borderLeft) - parseFloat(style.borderRight) - parseFloat(style.marginLeft) - parseFloat(style.marginRight);
}

With all that said, this is probably not an answer I would recommend following with my current experience, and I would resort to using methods that don't rely on JavaScript as much.

How to resolve "must be an instance of string, string given" prior to PHP 7?

As others have already said, type hinting currently only works for object types. But I think the particular error you've triggered might be in preparation of the upcoming string type SplString.

In theory it behaves like a string, but since it is an object would pass the object type verification. Unfortunately it's not yet in PHP 5.3, might come in 5.4, so haven't tested this.

Cannot connect to repo with TortoiseSVN

You need to determine whether this is a problem with TortoiseSVN, your Subversion repository, or your network connection.

  • First of all, check your URL. I never used User-Friendly SVN, so I don't know what it does to the Apache httpd configuration. However, the standard Apache configuration for multiple repositories is usually http://<server>/svn/<module> and not http://<server>/svn/usvn/<module>. Is that /usvn/ directory suppose to be there?
    • By the way, how was Apache configured? Does User-Friendly SVN do that too, or does it merely allow you to configure the repositories? Are you using Visual-SVN, or did someone manually configure Apache httpd?
  • If the URL is correct, try pinging your Subversion server. Can you ping it from your Windows box? If not, you have a network issue. For some reason that IP address isn't even reachable from your client box.
  • Try opening a browser, and putting the URL of the Subversion repository into the window. This should work. If it does, the issue is probably with TortoiseSVN. Download a command line Subversion client, and see if you can checkout with that.
  • Try using the same URL on another box. Can you checkout from there? If so, it points to a problem with the network.

Change multiple files

Those commands won't work in the default sed that comes with Mac OS X.

From man 1 sed:

-i extension
             Edit files in-place, saving backups with the specified
             extension.  If a zero-length extension is given, no backup 
             will be saved.  It is not recommended to give a zero-length
             extension when in-place editing files, as you risk corruption
             or partial content in situations where disk space is exhausted, etc.

Tried

sed -i '.bak' 's/old/new/g' logfile*

and

for i in logfile*; do sed -i '.bak' 's/old/new/g' $i; done

Both work fine.