text:
Q: Get certificate information after connection error I'm writing a simple SSL client using the OpenSSL library. I'd like to be able to print the certificate chain presented by the server after the connection completes. When the connection completes successfully, this isn't a problem. However, if the connection fails for some reason, I'm unable to get the failing certificate the server presented. Here's a SSCCE that demonstrates this.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>

#include <openssl/ssl.h>
#include <openssl/x509_vfy.h>
#include <openssl/err.h>

#define CIPHER_LIST "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"
// #define HOST "google.com" // works
#define HOST "expired.badssl.com" // does not print presented certificate

void print_certificates(SSL *ssl){
    STACK_OF(X509) * sk = SSL_get_peer_cert_chain(ssl);
    X509* cert = NULL;
    char sbuf[1024];
    char ibuf[1024];

    if(sk == NULL){
        printf("Cert chain is null!\n");
    }

    for (int i = 0; i < sk_X509_num(sk); i++) {
        cert = sk_X509_value(sk, i);
        fprintf(stdout, "Subject: %s\n", X509_NAME_oneline(X509_get_subject_name(cert), sbuf, 1024));
        fprintf(stdout, "Issuer: %s\n", X509_NAME_oneline(X509_get_issuer_name(cert), ibuf, 1024));
        PEM_write_X509(stdout, cert);
    }
}

void verify_cert(SSL *ssl, char* host){
    print_certificates(ssl);
    X509* cert = SSL_get_peer_certificate(ssl);
    if(cert) { X509_free(cert); }

    int res = SSL_get_verify_result(ssl);

    if(!(X509_V_OK == res)){
        printf("ERROR (NOT VERIFIED - %s): %s\n", X509_verify_cert_error_string(res), host);
        return;
    }

    printf("SUCCESS: %s\n", host);
    fflush(stdout);

}

int main(int argc, char **argv){
    SSL * ssl = NULL;
    SSL_CTX *ctx = NULL;
    BIO *bio = NULL;
    int res;

    SSL_library_init();
    SSL_load_error_strings();

    const SSL_METHOD* method = SSLv23_method();
    if(method == NULL)
        goto End;

    ctx = SSL_CTX_new(method);
    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
    if (ctx == NULL)
        goto End;
    SSL_CTX_set_options(ctx, SSL_OP_ALL | SSL_OP_NO_SSLv2 |
        SSL_OP_NO_SSLv3);

    res = SSL_CTX_set_default_verify_paths(ctx);
    if (res != 1)
        goto End;

    bio = BIO_new_ssl_connect(ctx);
    if (bio == NULL)
        return 0;

    BIO_set_conn_hostname(bio, HOST);
    BIO_set_conn_port(bio, "443");
    BIO_set_nbio(bio, 1);

    BIO_get_ssl(bio, &ssl);
    if(ssl == NULL)
        goto End;

    SSL_set_cipher_list(ssl, CIPHER_LIST);
    res = SSL_set_tlsext_host_name(ssl, HOST);

    int still_connecting = 1;
    while(still_connecting){
        int res = SSL_connect(ssl);
        if (res <= 0){
            unsigned long error = SSL_get_error(ssl, res);
            if ( (error != SSL_ERROR_WANT_CONNECT) &&
                 (error != SSL_ERROR_WANT_READ) && (error != SSL_ERROR_WANT_WRITE) )
            {
                printf("Connection encountered fatal error\n");
                ERR_print_errors_fp(stdout);
                still_connecting = 0;
            }
        }
        else{
            printf("Connection completed succesfully\n");
            still_connecting = 0;
        }
    }

    verify_cert(ssl, HOST);

End:
return 0;
}

(Fastest way to compile this is gcc sscce.c -lcrypto -lssl -o sscce).
Whenever SSL_connect(ssl) returns 1 (whenever the connection is successful), print_certificates(ssl) works as expected. However, if SSL_connect(ssl) returns anything other than 1 (the connection failed), print_certificates(ssl) does not print anything, because SSL_get_peer_cert_chain(ssl) returns null. While this is a logical behavior for servers that don't present a certificate, on servers that present an invalid certificate, not having access to the certificate makes it difficult to debug server configuration issues.
Interestingly, SSL_get_verify_result(ssl) returns the correct error code when the connection fails, despite the fact that I can't get the certificate chain myself.* I've looked through the OpenSSL codebase a little bit to try and figure out why this is, and while I'm still struggling to understand how everything fits together, it looks like there's some code in the ssl_verify_cert_chain function that frees the certificates after performing the error checking. I'm guessing that in the example code above, SSL_connect, once it has the complete certificate chain, runs some built-in validation code that frees the certificate before it gets to print_certificates. This confuses me, because I don't understand why the certificates would be freed when validation fails, but not when it succeeds. Perhaps someone who knows more about OpenSSL's internal behavior can shed some light on this.
I've noted that the stock s_client provided by the openssl utility, when run with the showcerts option (openssl s_client -showcerts -connect expired.badssl.com:443) does not exhibit this behavior. Regardless of whether the connection succeeds or fails, the certificates are printed. The print_certificates function in my SSCCE is just a modified version of the s_client cert printing code, but s_client doesn't use SSL_connect, so it's unsurprising that it exhibits different behavior. I note that s_client sets a custom certificate verify callback (defined here), but I'm reluctant to use anything but the default** verify function.
tl;dr SSL_get_peer_cert_chain(ssl) returns null if the server presents an invalid certificate chain. How can I get around this to print the failing certificate chain?
Edit: I've confirmed that this problem still occurs when I set the BIO state to blocking, and also, (for what it's worth), when the above code is compiled using LibreSSL.
Edit 2: I found that creating a function that just returns 1 and passing that to SSL_CTX_set_verify as the callback function (instead of NULL) causes SSL_get_peer_cert_chain(ssl) to return the certificate chain as expected, despite invalid certs in the chain. However, I'm reluctant to call this a solution to the problem, since I pretty clearly must be overriding one of OpenSSL's built-in functions here.
* - The obvious response to this is that since OpenSSL tells me why the connection failed, I don't need to access the raw cert in order to debug my issues. In any other situation, this would be true, but since I'm using this client as part of a research project involving invalid certificate use on the internet, I need to be able to save the failing certificates to a file.
** - As far as I can tell, passing NULL as the verify_callback parameter of SSL_CTX_set_verify tells OpenSSL to use a builtin default function for certificate validation. The documentation isn't tremendously clear on this.

A: TLDR: use the callback.
All session parameters including the cert chain are available only if the connection (handshake) succeeded; this is because if the handshake did not succeed there is no way to have confidence any of the results are valid. In theory the received certs could be a special case, but a special case would be more complicated and as you may have noticed the OpenSSL API is already complicated enough people routinely screw up using it.
As you saw s_client sets a verify callback that forces acceptance of any cert chain, even an invalid one; this causes the handshake to succeed and parameters including the cert chain to be available. s_client is intended as a test tool where it doesn't matter if the data is really secure or not.
If you want to connect only to verified servers, use the default verify logic. If you want to connect to unverified servers and handle risk (possibly minimal in your case) of data being intercepted and/or tampered, use the callback. The reason it is a callback is to allow applications control.
The fact s_client uses SSL_set_connect_state to cause handshake before the first data transfer, rather than explicitly calling SSL_connect, is irrelevant and makes no difference.
ADDED: you can detect an error after using the callback -- or even without!
First to be clear, the callback we are talking about here (the 'verify' callback) is used in addition to the builtin chain verification logic. There is a different callback, with a very similar name, the 'cert verify' callback, which you do NOT want. Quoting the man page

The actual verification procedure is performed either using the built-in verification procedure or using another application provided verification function set with SSL_CTX_set_cert_verify_callback. The following descriptions apply in the case of the built-in procedure. An application provided procedure also has access to the verify depth information and the verify_callback() function, but the way this information is used may be different.

As the (conveniently hyperlinked) SSL_[CTX_]set_cert_verify_callback man page says

[by default] the built-in verification function is used. If a verification callback callback [that's clearly a typo] is specified via SSL_CTX_set_cert_verify_callback(), the supplied callback function is called instead. [...]
Providing a complete verification procedure including certificate purpose settings etc is a complex task. The built-in procedure is quite powerful and in most cases it should be sufficient to modify its behaviour using the verify_callback function.

Where 'the verify_callback function' means the set_verify one not the set_verify_callback one. Actually this is not exact; part of the builtin logic is always used and only part of it is replaced by the cert verify callback. But you still don't want to do that, only the verify callback.
The SSL_[CTX_]set_verify[_depth] page continues to describe the builtin logic:

SSL_CTX_set_verify_depth() and SSL_set_verify_depth() set the limit up to which depth certificates in a chain are used during the verification procedure. [...]
The certificate chain is checked starting with the deepest nesting level (the root CA certificate) and worked upward to the peer's certificate. At each level signatures and issuer attributes are checked. Whenever a verification error is found, the error number is stored in x509_ctx and verify_callback is called with preverify_ok=0. [...] If no error is found for a certificate, verify_callback is called with preverify_ok=1 before advancing to the next level.
The return value of verify_callback controls the strategy of the further verification process. If verify_callback returns 0, the verification process is immediately stopped with "verification failed" state. [,,,] If verify_callback returns 1, the verification process is continued. If verify_callback always returns 1, the TLS/SSL handshake will not be terminated with respect to verification failures and the connection will be established. The calling process can however retrieve the error code of the last verification error using SSL_get_verify_result or by maintaining its own error storage managed by verify_callback.
If no verify_callback is specified, the default callback will be used. Its return value is identical to preverify_ok, so that any verification failure will lead to a termination of the TLS/SSL handshake with an alert message, if SSL_VERIFY_PEER is set.

So a callback has the option to force acceptance after the builtin logic has found an error (call with 0, return 1) or force failure even if the builtin logic considers the cert chain okay (call with 1, return 0) but if it doesn't the builtin logic controls.
The special callback used by s_client (and by s_server when client authentication is used, but that is relatively rare) prints the subject name of each cert with the status (labelled 'verify return') from the builtin logic, but always returns 1 thereby forcing the (rest of the verification and) connection to continue regardless of any error found.
Notice in the second paragraph "Whenever a verification error is found, the error number is stored in x509_ctx and [then] verify_callback is called with preverify_ok=0" and in the third paragraph "The calling process can however retrieve the error code of the last verification error using SSL_get_verify_result" -- this is true even if the callback forced ok=1.
But in checking the references for this I found an even better solution I had missed right on that page: if you just default (or set) mode SSL_VERIFY_NONE (emphasis and clarifications added):

Client mode: if not using an anonymous cipher (by default disabled), the server will send a certificate which will be checked [by the builtin logic, even though NONE would make you think it isn't checked]. The result of the certificate verification process can be checked after the TLS/SSL handshake [is completed] using the SSL_get_verify_result function. The handshake will be continued regardless of the verification result.

This is effectively the same as a callback that forces ok=1 and does what you want.

A: It's possible to use SSL_CTX_set_cert_verify_callback(ctx, own_cert_verify_callback, &cert) to use own verification callback with given pointer to STACK_OF(X509)*. Callback then looks like this:
static int own_cert_verify_callback(X509_STORE_CTX * ctx, void * arg) {
   int result = 0;
   STACK_OF(X509) ** untrusted_chain = (STACK_OF(X509) **) (arg);

   result = X509_verify_cert(ctx);
   if (result != 1) {
      *untrusted_chain = X509_chain_up_ref(X509_STORE_CTX_get0_untrusted(ctx));
   }

   return result;
}

So default function for certificate verification is used and when certificate is invalid, shallow copy is placed to the arg so it can be used later.


text:
Q: How to convert large Object to input stream in java I am trying to convert an object to inputstream using the below code.
 try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
        ObjectOutputStream dataOutput = new ObjectOutputStream(byteArrayOutputStream);
        dataOutput.writeObject(dummyObject);
        return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    } catch (Exception exception) {
    }

since the size of the object can be slightly greater than 2gb, ByteArrayOutputStream is throwing OutOfMemory.
Any way to convert a big object to input stream in java?

A: No, at least for the SUN java runtime, ObjectOutputStream works with a ByteArrayOutputStream internally, probably for a two-pass processing, where the second pass optimizes the encoding of references.
So, there is no way to serialize Objects of arbitrary size with this ObjectOutputStream implementation.
What you can do is re-implement the ObjectOutputStream from an open-source-version, where you replace the nested ByteArrayOutputStream e.g. by a temporary RandomAccessFile or an implementation of ByteArrayOutputStream, that does not have that artificial limit of 2GB.
Note In case you decide to define an independent implementation: Well consider the asynchronous instatiation of nested classes!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to load a sparse matrix in Python from an MMF file How can I load data of a sparse matrix form (MMF) file, and then carry out a linear algebra operation on that matrix?
The MMF file is in the following form:
1 1 8.530175905456780E+008
7 1 1.257919566068602E+008
12 1 3.841933299769016E+002
13 1 1.257919566068601E+008
18 1 -3.841933299769017E+002
67 1 -1.214247928031784E+008
68 1 3.613935214862212E+007
72 1 9.604833249423183E+001
73 1 -3.094511662733424E+008
79 1 -1.214247928031783E+008
80 1 -3.613935214862211E+007
84 1 -9.604833249423186E+001
2 2 8.530175905456780E+008
8 2 -3.094511662733424E+008
14 2 -3.094511662733426E+008
67 2 3.613935214862212E+007
68 2 -1.214247928031784E+008
72 2 9.604833249423183E+001
74 2 1.257919566068602E+008
78 2 3.841933299769016E+002
79 2 -3.613935214862212E+007
80 2 -1.214247928031783E+008
84 2 9.604833249423183E+001
........

It is of size up to 6500.

A: From the documentation of mmread in SciPy:

scipy.io.mmread(source)[source]
Reads the contents of a Matrix Market file-like 'source' into a matrix.
Parameters sourcestr or file-like Matrix Market filename (extensions
.mtx, .mtz.gz) or open file-like object.
Returns andarray or coo_matrix Dense or sparse matrix depending on the
matrix format in the Matrix Market file.

SciPy should return a sparse matrix, if that is the format of the file.
Try:
import scipy

sparse_mat = scipy.io.mmread('matrix_file_name.mtx')

A: Well, I figured it out by using the following code (where n is the matrix size):
import numpy as np
from numpy import *
from matplotlib.pyplot import *
import re
import scipy.linalg as la

data = loadtxt('matKSMMF.txt', skiprows=8)
s = len (data)
print(s)
n = 6567
kmat = [[0 for _ in range(n)] for _ in range(n)]
for x in range (s):
    m = data[x:x+1, :]
    kmat[int (m[0, 0]) - 1][int (m[0, 1]) - 1] = m[0, 2]
K = np.array(kmat)
print (K)


text:
Q: Issues with customizing Amcharts I have created stock graphs using amcharts library . I want a give a title and other things to this graph. Individual panel title are working. But Title for complete graph is not working.
Here is the working example http://jsfiddle.net/hwhpguaf/
I tried to provide titles to graph but its not working
"titles": [
        {
            "text": "Chart Title",
            "size": 15
        }
    ]

Sample image of what I want

A: Stock Chart does now have titles property and cannot have any additional titles and/or labels displayed on it.
You can however, add titles array to each individual panel, though:
panels: [{
    title: "Value",
    percentHeight: 70,

    "titles": [
        {
            "text": "Chart Title",
            "size": 15
        }
    ], ...

This will produce a title over the panel:

Here's updated fiddle: http://jsfiddle.net/hwhpguaf/1/
If however you are looking for a way to add a title over the whole of the chart, then putting as an external HTML element, might be an even straightforward solution:

Chart title


text:
Q: merge overlapping sub-intervals I actually tried this question in some different way
#include"bits/stdc++.h"
using namespace std;

vector<vector<int> > overlap(vector<vector<int> > arr,int n){

    deque<int> q;
    q.push_back(arr[0][0]);
    q.push_back(arr[0][1]);
    int i=1;

    while(i<n){
        int j=0;

        if(q.back()>arr[i+1][j]){
            if(q.back()<arr[i+1][j+1]){
                q.pop_back();
                q.push_back(arr[i+1][j+1]);
            }
        }
        else{
            q.push_back(arr[i+1][j]);
            q.push_back(arr[i+1][j+1]);
        }

        i++;
    }

    vector<vector<int> > out(n,vector<int>(n,0));
    int k=0;

    while(!q.empty()){
        int l=0;
        out[k][l]=q.front();
        q.pop_front();
        out[k][l+1]=q.front();
        q.pop_front();
        k++;
    }

    return out;
}

but while running it isn't showing any output. Is there something wrong in my code or my approach is wrong


text:
Q: iOS Google Maps SDK Memory Management/Memory Leak I am using iOS Google Maps in my app. I've been looking for memory leaks as of lately as I noticed the Memory started spiking whenever I would zoom out. Both on simulator and my actual iPhone X device experience such memory spikes when zooming out. I am also zooming out because I am using the marker clustering feature.
I've done some research on different ways to detect memory leaks such as enabling sound actions on breakpoints and looking at Backtrace tree for strong references. It seems that there is a strong reference when I configure my GMSMapView (Code below).
func configureMapView() {
    guard let location = locationManager.location else { return }
    let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude, longitude: location.coordinate.longitude, zoom: 16.5)
    mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    mapView.isMyLocationEnabled         = true
    mapView.settings.compassButton      = true
    mapView.settings.rotateGestures     = false
    mapView.settings.tiltGestures       = false
    view = mapView
}

Xcode is pointing to this line that has a strong reference.
mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)

Is this strong reference the reason why memory usage spikes up when zooming out? Also, not entirely sure how to fix this strong reference with Google Maps, any help would be appreciated!


text:
Q: How to find the intersection point between a line and a rectangle? I have a line that goes from points A to B; I have (x,y) of both points. I also have a rectangle that's centered at B and the width and height of the rectangle.
I need to find the point in the line that intersects the rectangle. Is there a formula that gives me the (x,y) of that point?

A: Here is a solution that works for me. I assume that the rect is aligned to the axes.
Data:
// Center of the Rectangle
let Cx: number
let Cy: number
// Width
let w: number
// Height
let h: number

// Other Point
let Ax: number
let Ay: number

Now translate point A by the center of the rectangle so the rect is centered in O(0,0) and consider the problem in the first quarter (i.e. x > 0 and y > 0).
// Coordinates Translated
let Px = Math.abs(Ax - Cx)
let Py = Math.abs(Ay - Cy)

// Slope of line from Point P to Center
let Pm = Py / Px

// Slope of rectangle Diagonal
let Rm = h / w

// If the point is inside the rectangle, return the center
let res: [number, number] = [0, 0]

// Check if the point is inside and if so do not calculate
if (!(Px < w / 2 && Py < h / 2)) {

    // Calculate point in first quarter: Px >= 0 && Py >= 0
    if (Pm <= Rm) {
        res[0] = w / 2
        res[1] = (w * Pm) / 2
    } else {
        res[0] = h / (Pm * 2)
        res[1] = h / 2
    }

    // Set original sign
    if (Ax - Cx < 0) res[0] *= -1
    if (Ay - Cy < 0) res[1] *= -1
}

// Translate back
return [res[0] + Cx, res[1] + Cy]

A: I am not a math fan nor do I particularly enjoy translating stuff from other languages if others have already done so, so whenever I complete a boring translation task, I add it to the article that led me to the code. To prevent anyone doing double work.
So if you want to have this intersection code in C#, have a look here http://dotnetbyexample.blogspot.nl/2013/09/utility-classes-to-check-if-lines-andor.html

A: Let's make some assumptions :

Points A and C are given, such that they define a rectangle ABCD aligned with the traditional axes. Assume that A is the bottom-left corner, and C is the top-right (i.e. xA < xC and yA < yC).
Assume that X and Y are two points given such that X lies inside the rectangle (ie xA < xX < xC && yA < yX < yC) and Y lies outside (i.e. not(xA < xY < xC && yA < yY < yC).

This allows us to define a unique intersection point E between the segment [X,Y] and the rectangle ∂ABCD.

The trick is to look for a certain 0 < t < 1 such that t*Y+(1-t)*X is on the rectangle ∂ABCD. By re-writing the condition Γ(t) ∈ ABCD as :

(xY - xX) * t ∈ [xA - xX, xC - xX] and (yY - yX) * t ∈ [yA - yX, yC - yX],

it is now possible to unwind all the scenarios. This yields :
var t = 0;

if(xY == xX) {
    t =  max((yA - yX)/(yY - yX), (yC - yX)/(yY - yX));
} else {
    if(yY == yX) {
        t = max((xA - xX)/(xY - xX), (xC - xX)/(xY - xX));
    } else {
        if(xY > xX) {
            if(yY > yX) {
                t = min((xC - xX)/(xY - xX), (yC - yX)/(yY - yX));
            } else {
                t = min((xC - xX)/(xY - xX), (yA - yX)/(yY - yX));
            }
        } else {
            if(yY > yX) {
                t = min((xA - xX)/(xY - xX), (yC - yX)/(yY - yX));
            } else {
                t = min((xA - xX)/(xY - xX), (yA - yX)/(yY - yX));
            }
        }
    }
}

xE = t * xY + (1 - t) * xX;
yE = t * yY + (1 - t) * yX;

A: Given the original question, I think that @ivanross answer is the most concise and clear so far, and I found myself using the same approach.

If we have a rectangle

*

*centered in B

*with sides parallel to x and y axes

we can use a bit of trigonometry to get:

*

*tan φ (phi) = h/w

*tan θ (theta) = (yB-yA)/(xB-xA)

and some trivial math to get in which quadrant (of the x-y plane centered in B) the point A is.
finally we compare the angles and use the tangents to calculate the coordinates of the intersection point, applying again basic trigonometry principles.

/**
 * Finds the intersection point between
 *     * a rectangle centered in point B
 *       with sides parallel to the x and y axes
 *     * a line passing through points A and B (the center of the rectangle)
 *
 * @param width: rectangle width
 * @param height: rectangle height
 * @param xB; rectangle center x coordinate
 * @param yB; rectangle center y coordinate
 * @param xA; point A x coordinate
 * @param yA; point A y coordinate
 * @author Federico Destefanis
 * @see based on
 */

function lineIntersectionOnRect(width, height, xB, yB, xA, yA) {

  var w = width / 2;
  var h = height / 2;

  var dx = xA - xB;
  var dy = yA - yB;

  //if A=B return B itself
  if (dx == 0 && dy == 0) return {
    x: xB,
    y: yB
  };

  var tan_phi = h / w;
  var tan_theta = Math.abs(dy / dx);

  //tell me in which quadrant the A point is
  var qx = Math.sign(dx);
  var qy = Math.sign(dy);

  if (tan_theta > tan_phi) {
    xI = xB + (h / tan_theta) * qx;
    yI = yB + h * qy;
  } else {
    xI = xB + w * qx;
    yI = yB + w * tan_theta * qy;
  }

  return {
    x: xI,
    y: yI
  };

}

var coords = lineIntersectionOnRect(6, 4, 0, 0, 1, 0);
console.log(coords);

A:

/**
 * Finds the intersection point between
 *     * the rectangle
 *       with parallel sides to the x and y axes
 *     * the half-line pointing towards (x,y)
 *       originating from the middle of the rectangle
 *
 * Note: the function works given min[XY] <= max[XY],
 *       even though minY may not be the "top" of the rectangle
 *       because the coordinate system is flipped.
 * Note: if the input is inside the rectangle,
 *       the line segment wouldn't have an intersection with the rectangle,
 *       but the projected half-line does.
 * Warning: passing in the middle of the rectangle will return the midpoint itself
 *          there are infinitely many half-lines projected in all directions,
 *          so let's just shortcut to midpoint (GIGO).
 *
 * @param x:Number x coordinate of point to build the half-line from
 * @param y:Number y coordinate of point to build the half-line from
 * @param minX:Number the "left" side of the rectangle
 * @param minY:Number the "top" side of the rectangle
 * @param maxX:Number the "right" side of the rectangle
 * @param maxY:Number the "bottom" side of the rectangle
 * @param validate:boolean (optional) whether to treat point inside the rect as error
 * @return an object with x and y members for the intersection
 * @throws if validate == true and (x,y) is inside the rectangle
 * @author TWiStErRob
 * @licence Dual CC0/WTFPL/Unlicence, whatever floats your boat
 * @see source
 * @see based on
 */
function pointOnRect(x, y, minX, minY, maxX, maxY, validate) {
 //assert minX <= maxX;
 //assert minY <= maxY;
 if (validate && (minX < x && x < maxX) && (minY < y && y < maxY))
  throw "Point " + [x,y] + "cannot be inside "
      + "the rectangle: " + [minX, minY] + " - " + [maxX, maxY] + ".";
 var midX = (minX + maxX) / 2;
 var midY = (minY + maxY) / 2;
 // if (midX - x == 0) -> m == ±Inf -> minYx/maxYx == x (because value / ±Inf = ±0)
 var m = (midY - y) / (midX - x);

 if (x <= midX) { // check "left" side
  var minXy = m * (minX - x) + y;
  if (minY <= minXy && minXy <= maxY)
   return {x: minX, y: minXy};
 }

 if (x >= midX) { // check "right" side
  var maxXy = m * (maxX - x) + y;
  if (minY <= maxXy && maxXy <= maxY)
   return {x: maxX, y: maxXy};
 }

 if (y <= midY) { // check "top" side
  var minYx = (minY - y) / m + x;
  if (minX <= minYx && minYx <= maxX)
   return {x: minYx, y: minY};
 }

 if (y >= midY) { // check "bottom" side
  var maxYx = (maxY - y) / m + x;
  if (minX <= maxYx && maxYx <= maxX)
   return {x: maxYx, y: maxY};
 }

 // edge case when finding midpoint intersection: m = 0/0 = NaN
 if (x === midX && y === midY) return {x: x, y: y};

 // Should never happen :) If it does, please tell me!
 throw "Cannot find intersection for " + [x,y]
     + " inside rectangle " + [minX, minY] + " - " + [maxX, maxY] + ".";
}

(function tests() {
 var left = 100, right = 200, top = 50, bottom = 150; // a square, really
 var hMiddle = (left + right) / 2, vMiddle = (top + bottom) / 2;
 function intersectTestRect(x, y) { return pointOnRect(x,y, left,top, right,bottom, true); }
 function intersectTestRectNoValidation(x, y) { return pointOnRect(x,y, left,top, right,bottom, false); }
 function checkTestRect(x, y) { return function() { return pointOnRect(x,y, left,top, right,bottom, true); }; }
 QUnit.test("intersects left side", function(assert) {
  var leftOfRect = 0, closerLeftOfRect = 25;
  assert.deepEqual(intersectTestRect(leftOfRect, 25), {x:left, y:75}, "point above top");
  assert.deepEqual(intersectTestRect(closerLeftOfRect, top), {x:left, y:80}, "point in line with top");
  assert.deepEqual(intersectTestRect(leftOfRect, 70), {x:left, y:90}, "point above middle");
  assert.deepEqual(intersectTestRect(leftOfRect, vMiddle), {x:left, y:100}, "point exact middle");
  assert.deepEqual(intersectTestRect(leftOfRect, 130), {x:left, y:110}, "point below middle");
  assert.deepEqual(intersectTestRect(closerLeftOfRect, bottom), {x:left, y:120}, "point in line with bottom");
  assert.deepEqual(intersectTestRect(leftOfRect, 175), {x:left, y:125}, "point below bottom");
 });
 QUnit.test("intersects right side", function(assert) {
  var rightOfRect = 300, closerRightOfRect = 250;
  assert.deepEqual(intersectTestRect(rightOfRect, 25), {x:right, y:75}, "point above top");
  assert.deepEqual(intersectTestRect(closerRightOfRect, top), {x:right, y:75}, "point in line with top");
  assert.deepEqual(intersectTestRect(rightOfRect, 70), {x:right, y:90}, "point above middle");
  assert.deepEqual(intersectTestRect(rightOfRect, vMiddle), {x:right, y:100}, "point exact middle");
  assert.deepEqual(intersectTestRect(rightOfRect, 130), {x:right, y:110}, "point below middle");
  assert.deepEqual(intersectTestRect(closerRightOfRect, bottom), {x:right, y:125}, "point in line with bottom");
  assert.deepEqual(intersectTestRect(rightOfRect, 175), {x:right, y:125}, "point below bottom");
 });
 QUnit.test("intersects top side", function(assert) {
  var aboveRect = 0;
  assert.deepEqual(intersectTestRect(80, aboveRect), {x:115, y:top}, "point left of left");
  assert.deepEqual(intersectTestRect(left, aboveRect), {x:125, y:top}, "point in line with left");
  assert.deepEqual(intersectTestRect(120, aboveRect), {x:135, y:top}, "point left of middle");
  assert.deepEqual(intersectTestRect(hMiddle, aboveRect), {x:150, y:top}, "point exact middle");
  assert.deepEqual(intersectTestRect(180, aboveRect), {x:165, y:top}, "point right of middle");
  assert.deepEqual(intersectTestRect(right, aboveRect), {x:175, y:top}, "point in line with right");
  assert.deepEqual(intersectTestRect(220, aboveRect), {x:185, y:top}, "point right of right");
 });
 QUnit.test("intersects bottom side", function(assert) {
  var belowRect = 200;
  assert.deepEqual(intersectTestRect(80, belowRect), {x:115, y:bottom}, "point left of left");
  assert.deepEqual(intersectTestRect(left, belowRect), {x:125, y:bottom}, "point in line with left");
  assert.deepEqual(intersectTestRect(120, belowRect), {x:135, y:bottom}, "point left of middle");
  assert.deepEqual(intersectTestRect(hMiddle, belowRect), {x:150, y:bottom}, "point exact middle");
  assert.deepEqual(intersectTestRect(180, belowRect), {x:165, y:bottom}, "point right of middle");
  assert.deepEqual(intersectTestRect(right, belowRect), {x:175, y:bottom}, "point in line with right");
  assert.deepEqual(intersectTestRect(220, belowRect), {x:185, y:bottom}, "point right of right");
 });
 QUnit.test("intersects a corner", function(assert) {
  assert.deepEqual(intersectTestRect(left-50, top-50), {x:left, y:top}, "intersection line aligned with top-left corner");
  assert.deepEqual(intersectTestRect(right+50, top-50), {x:right, y:top}, "intersection line aligned with top-right corner");
  assert.deepEqual(intersectTestRect(left-50, bottom+50), {x:left, y:bottom}, "intersection line aligned with bottom-left corner");
  assert.deepEqual(intersectTestRect(right+50, bottom+50), {x:right, y:bottom}, "intersection line aligned with bottom-right corner");
 });
 QUnit.test("on the corners", function(assert) {
  assert.deepEqual(intersectTestRect(left, top), {x:left, y:top}, "top-left corner");
  assert.deepEqual(intersectTestRect(right, top), {x:right, y:top}, "top-right corner");
  assert.deepEqual(intersectTestRect(right, bottom), {x:right, y:bottom}, "bottom-right corner");
  assert.deepEqual(intersectTestRect(left, bottom), {x:left, y:bottom}, "bottom-left corner");
 });
 QUnit.test("on the edges", function(assert) {
  assert.deepEqual(intersectTestRect(hMiddle, top), {x:hMiddle, y:top}, "top edge");
  assert.deepEqual(intersectTestRect(right, vMiddle), {x:right, y:vMiddle}, "right edge");
  assert.deepEqual(intersectTestRect(hMiddle, bottom), {x:hMiddle, y:bottom}, "bottom edge");
  assert.deepEqual(intersectTestRect(left, vMiddle), {x:left, y:vMiddle}, "left edge");
 });
 QUnit.test("validates inputs", function(assert) {
  assert.throws(checkTestRect(hMiddle, vMiddle), /cannot be inside/, "center");
  assert.throws(checkTestRect(hMiddle-10, vMiddle-10), /cannot be inside/, "top left of center");
  assert.throws(checkTestRect(hMiddle-10, vMiddle), /cannot be inside/, "left of center");
  assert.throws(checkTestRect(hMiddle-10, vMiddle+10), /cannot be inside/, "bottom left of center");
  assert.throws(checkTestRect(hMiddle, vMiddle-10), /cannot be inside/, "above center");
  assert.throws(checkTestRect(hMiddle, vMiddle), /cannot be inside/, "center");
  assert.throws(checkTestRect(hMiddle, vMiddle+10), /cannot be inside/, "below center");
  assert.throws(checkTestRect(hMiddle+10, vMiddle-10), /cannot be inside/, "top right of center");
  assert.throws(checkTestRect(hMiddle+10, vMiddle), /cannot be inside/, "right of center");
  assert.throws(checkTestRect(hMiddle+10, vMiddle+10), /cannot be inside/, "bottom right of center");
  assert.throws(checkTestRect(left+10, vMiddle-10), /cannot be inside/, "right of left edge");
  assert.throws(checkTestRect(left+10, vMiddle), /cannot be inside/, "right of left edge");
  assert.throws(checkTestRect(left+10, vMiddle+10), /cannot be inside/, "right of left edge");
  assert.throws(checkTestRect(right-10, vMiddle-10), /cannot be inside/, "left of right edge");
  assert.throws(checkTestRect(right-10, vMiddle), /cannot be inside/, "left of right edge");
  assert.throws(checkTestRect(right-10, vMiddle+10), /cannot be inside/, "left of right edge");
  assert.throws(checkTestRect(hMiddle-10, top+10), /cannot be inside/, "below top edge");
  assert.throws(checkTestRect(hMiddle, top+10), /cannot be inside/, "below top edge");
  assert.throws(checkTestRect(hMiddle+10, top+10), /cannot be inside/, "below top edge");
  assert.throws(checkTestRect(hMiddle-10, bottom-10), /cannot be inside/, "above bottom edge");
  assert.throws(checkTestRect(hMiddle, bottom-10), /cannot be inside/, "above bottom edge");
  assert.throws(checkTestRect(hMiddle+10, bottom-10), /cannot be inside/, "above bottom edge");
 });
 QUnit.test("doesn't validate inputs", function(assert) {
  assert.deepEqual(intersectTestRectNoValidation(hMiddle-10, vMiddle-10), {x:left, y:top}, "top left of center");
  assert.deepEqual(intersectTestRectNoValidation(hMiddle-10, vMiddle), {x:left, y:vMiddle}, "left of center");
  assert.deepEqual(intersectTestRectNoValidation(hMiddle-10, vMiddle+10), {x:left, y:bottom}, "bottom left of center");
  assert.deepEqual(intersectTestRectNoValidation(hMiddle, vMiddle-10), {x:hMiddle, y:top}, "above center");
  assert.deepEqual(intersectTestRectNoValidation(hMiddle, vMiddle), {x:hMiddle, y:vMiddle}, "center");
  assert.deepEqual(intersectTestRectNoValidation(hMiddle, vMiddle+10), {x:hMiddle, y:bottom}, "below center");
  assert.deepEqual(intersectTestRectNoValidation(hMiddle+10, vMiddle-10), {x:right, y:top}, "top right of center");
  assert.deepEqual(intersectTestRectNoValidation(hMiddle+10, vMiddle), {x:right, y:vMiddle}, "right of center");
  assert.deepEqual(intersectTestRectNoValidation(hMiddle+10, vMiddle+10), {x:right, y:bottom}, "bottom right of center");
 });
})();
<link href="https://code.jquery.com/qunit/qunit-2.3.2.css" rel="stylesheet"/>

A: I'll not give you a program to do that, but here is how you can do it:

*

*calculate the angle of the line

*calculate the angle of a line from the center of the rectangle to one of it's corners

*based on the angles determine on which side does the line intersect the rectangle

*calculate intersection between the side of the rectangle and the line

A:
The point A is always outside of the rectangle and the point B is always at the center of the rectangle

Assuming the rectangle is axis-aligned, this makes things pretty simple:
The slope of the line is s = (Ay - By)/(Ax - Bx).

*

*If -h/2 <= s * w/2 <= h/2 then the line intersects:

*

*The right edge if Ax > Bx

*The left edge if Ax < Bx.

*If -w/2 <= (h/2)/s <= w/2 then the line intersects:

*

*The top edge if Ay > By

*The bottom edge if Ay < By.

Once you know the edge it intersects you know one coordinate: x = Bx ± w/2 or y = By ± h/2 depending on which edge you hit. The other coordinate is given by y = By + s * w/2 or x = Bx + (h/2)/s.

A: Another option that you can consider especially if you are planning on testing many lines with the same rectangle is to transform your coordinate system to have the axes align with diagonals of the rectangle. Then since your line or ray starts at the center of the rectangle you can determine the angle then you can tell which segment it will intersect by the angle (i.e. <90deg seg 1, 90deg< <180deg seg 2 etc...). Then of course you have to transform back to the original coordinate system
Although this seems like more work the transformation matrix and its inverse can be calculated once and then reused. This also extends to higher dimensional rectangles more easily where you would have to consider quadrants and intersections with faces in 3D and so on.

A:
Hope It works 100%
I am also had this same problem. So after two days of hard effort finally I created this method,
Main method,
    enum Line
    {
        // Inside the Rectangle so No Intersection Point(Both Entry Point and Exit Point will be Null)
        InsideTheRectangle,

        // One Point Inside the Rectangle another Point Outside the Rectangle. So it has only Entry Point
        Entry,

        // Both Point Outside the Rectangle but Intersecting. So It has both Entry and Exit Point
        EntryExit,

        // Both Point Outside the Rectangle and not Intersecting. So doesn't has both Entry and Exit Point
        NoIntersection
    }

    // Tuple<entryPoint, exitPoint, lineStatus>
    private Tuple<Point, Point, Line> GetIntersectionPoint(Point a, Point b, Rectangle rect)
    {
        if (IsWithinRectangle(a, rect) && IsWithinRectangle(b, rect))
        {
            // Can't set null to Point that's why I am returning just empty object
            return new Tuple<Point, Point, Line>(new Point(), new Point(), Line.InsideTheRectangle);
        }
        else if (!IsWithinRectangle(a, rect) && !IsWithinRectangle(b, rect))
        {
            if (!LineIntersectsRectangle(a, b, rect))
            {
                // Can't set null to Point that's why I am returning just empty object
                return new Tuple<Point, Point, Line>(new Point(), new Point(), Line.NoIntersection);
            }

            Point entryPoint = new Point();
            Point exitPoint = new Point();

            bool entryPointFound = false;

            // Top Line of Chart Area
            if (LineIntersectsLine(a, b, new Point(0, 0), new Point(rect.Width, 0)))
            {
                entryPoint = GetPointFromYValue(a, b, 0);
                entryPointFound = true;
            }
            // Right Line of Chart Area
            if (LineIntersectsLine(a, b, new Point(rect.Width, 0), new Point(rect.Width, rect.Height)))
            {
                if (entryPointFound)
                    exitPoint = GetPointFromXValue(a, b, rect.Width);
                else
                {
                    entryPoint = GetPointFromXValue(a, b, rect.Width);
                    entryPointFound = true;
                }
            }
            // Bottom Line of Chart
            if (LineIntersectsLine(a, b, new Point(0, rect.Height), new Point(rect.Width, rect.Height)))
            {
                if (entryPointFound)
                    exitPoint = GetPointFromYValue(a, b, rect.Height);
                else
                {
                    entryPoint = GetPointFromYValue(a, b, rect.Height);
                }
            }
            // Left Line of Chart
            if (LineIntersectsLine(a, b, new Point(0, 0), new Point(0, rect.Height)))
            {
                exitPoint = GetPointFromXValue(a, b, 0);
            }

            return new Tuple<Point, Point, Line>(entryPoint, exitPoint, Line.EntryExit);
        }
        else
        {
            Point entryPoint = GetEntryIntersectionPoint(rect, a, b);
            return new Tuple<Point, Point, Line>(entryPoint, new Point(), Line.Entry);
        }
    }

Supporting methods,
    private Point GetEntryIntersectionPoint(Rectangle rect, Point a, Point b)
    {
        // For top line of the rectangle
        if (LineIntersectsLine(new Point(0, 0), new Point(rect.Width, 0), a, b))
        {
            return GetPointFromYValue(a, b, 0);
        }
        // For right side line of the rectangle
        else if (LineIntersectsLine(new Point(rect.Width, 0), new Point(rect.Width, rect.Height), a, b))
        {
            return GetPointFromXValue(a, b, rect.Width);
        }
        // For bottom line of the rectangle
        else if (LineIntersectsLine(new Point(0, rect.Height), new Point(rect.Width, rect.Height), a, b))
        {
            return GetPointFromYValue(a, b, rect.Height);
        }
        // For left side line of the rectangle
        else
        {
            return GetPointFromXValue(a, b, 0);
        }
    }

    public bool LineIntersectsRectangle(Point p1, Point p2, Rectangle r)
    {
        return LineIntersectsLine(p1, p2, new Point(r.X, r.Y), new Point(r.X + r.Width, r.Y)) ||
               LineIntersectsLine(p1, p2, new Point(r.X + r.Width, r.Y), new Point(r.X + r.Width, r.Y + r.Height)) ||
               LineIntersectsLine(p1, p2, new Point(r.X + r.Width, r.Y + r.Height), new Point(r.X, r.Y + r.Height)) ||
               LineIntersectsLine(p1, p2, new Point(r.X, r.Y + r.Height), new Point(r.X, r.Y)) ||
               (r.Contains(p1) && r.Contains(p2));
    }

    private bool LineIntersectsLine(Point l1p1, Point l1p2, Point l2p1, Point l2p2)
    {
        float q = (l1p1.Y - l2p1.Y) * (l2p2.X - l2p1.X) - (l1p1.X - l2p1.X) * (l2p2.Y - l2p1.Y);
        float d = (l1p2.X - l1p1.X) * (l2p2.Y - l2p1.Y) - (l1p2.Y - l1p1.Y) * (l2p2.X - l2p1.X);

        if (d == 0)
        {
            return false;
        }

        float r = q / d;

        q = (l1p1.Y - l2p1.Y) * (l1p2.X - l1p1.X) - (l1p1.X - l2p1.X) * (l1p2.Y - l1p1.Y);
        float s = q / d;

        if (r < 0 || r > 1 || s < 0 || s > 1)
        {
            return false;
        }

        return true;
    }

    // For Large values, processing with integer is not working properly
    // So I here I am dealing only with double for high accuracy
    private Point GetPointFromYValue(Point a, Point b, double y)
    {
        double x1 = a.X, x2 = b.X, y1 = a.Y, y2 = b.Y;
        double x = (((y - y1) * (x2 - x1)) / (y2 - y1)) + x1;
        return new Point((int)x, (int)y);
    }

    // For Large values, processing with integer is not working properly
    // So here I am dealing only with double for high accuracy
    private Point GetPointFromXValue(Point a, Point b, double x)
    {
        double x1 = a.X, x2 = b.X, y1 = a.Y, y2 = b.Y;
        double y = (((x - x1) * (y2 - y1)) / (x2 - x1)) + y1;
        return new Point((int)x, (int)y);
    }

    // rect.Contains(point) is not working properly in some cases.
    // So here I created my own method
    private bool IsWithinRectangle(Point a, Rectangle rect)
    {
        return a.X >= rect.X && a.X <= rect.X + rect.Width && a.Y >= rect.Y && a.Y <= rect.Y + rect.Height;
    }

A: You might want to check out Graphics Gems - this is a classic set of routines for graphics and includes many of the algorithms required. Although it's in C and slightly dated the algorithms still sparkle and it should be trivial to transfer to other languages.
For your current problem the just create the four lines for the rectangle and see which intersect your given line.

A: Here is a solution in Java that returns true if a line segment (the first 4 parameters) intersects an axis aligned rectangle (the last 4 parameters). It would be trivial to return the intersection point instead of a boolean. It works by first checking if completely outside, else using the line equation y=m*x+b. We know the lines that make up the rectangle are axis aligned, so the checks are easy.
public boolean aabbContainsSegment (float x1, float y1, float x2, float y2, float minX, float minY, float maxX, float maxY) {
    // Completely outside.
    if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || (y1 >= maxY && y2 >= maxY))
        return false;

    float m = (y2 - y1) / (x2 - x1);

    float y = m * (minX - x1) + y1;
    if (y > minY && y < maxY) return true;

    y = m * (maxX - x1) + y1;
    if (y > minY && y < maxY) return true;

    float x = (minY - y1) / m + x1;
    if (x > minX && x < maxX) return true;

    x = (maxY - y1) / m + x1;
    if (x > minX && x < maxX) return true;

    return false;
}

It is possible to shortcut if the start or end of the segment is inside the rectangle, but probably it is better to just do the math, which will always return true if either or both segment ends are inside. If you want the shortcut anyway, insert the code below after the "completely outside" check.
// Start or end inside.
if ((x1 > minX && x1 < maxX && y1 > minY && y1 < maxY) || (x2 > minX && x2 < maxX && y2 > minY && y2 < maxY)) return true;

A: I don't know if this is the best way, but what you could do is to figure out the proportion of the line that is inside the rectangle. You can get that from the width of the rectangle and the difference between the x coordinates of A and B (or height and y coordinates; based on the width and height you can check which case applies, and the other case will be on the extension of a side of the rectangle). When you have this, just take that proportion of the vector from B to A and you have your intersection point's coordinates.

A: Here is a slightly verbose method that returns the intersection intervals between an (infinite) line and a rectangle using only basic math:
// Line2      - 2D line with origin (= offset from 0,0) and direction
// Rectangle2 - 2D rectangle by min and max points
// Contacts   - Stores entry and exit times of a line through a convex shape

Contacts findContacts(const Line2 &line, const Rectangle2 &rect) {
  Contacts contacts;

  // If the line is not parallel to the Y axis, find out when it will cross
  // the limits of the rectangle horizontally
  if(line.Direction.X != 0.0f) {
    float leftTouch = (rect.Min.X - line.Origin.X) / line.Direction.X;
    float rightTouch = (rect.Max.X - line.Origin.X) / line.Direction.X;
    contacts.Entry = std::fmin(leftTouch, rightTouch);
    contacts.Exit = std::fmax(leftTouch, rightTouch);
  } else if((line.Offset.X < rect.Min.X) || (line.Offset.X >= rect.Max.X)) {
    return Contacts::None; // Rectangle missed by vertical line
  }

  // If the line is not parallel to the X axis, find out when it will cross
  // the limits of the rectangle vertically
  if(line.Direction.Y != 0.0f) {
    float topTouch = (rectangle.Min.Y - line.Offset.Y) / line.Direction.Y;
    float bottomTouch = (rectangle.Max.Y - line.Offset.Y) / line.Direction.Y;

    // If the line is parallel to the Y axis (and it goes through
    // the rectangle), only the Y axis needs to be taken into account.
    if(line.Direction.X == 0.0f) {
      contacts.Entry = std::fmin(topTouch, bottomTouch);
      contacts.Exit = std::fmax(topTouch, bottomTouch);
    } else {
      float verticalEntry = std::fmin(topTouch, bottomTouch);
      float verticalExit = std::fmax(topTouch, bottomTouch);

      // If the line already left the rectangle on one axis before entering it
      // on the other, it has missed the rectangle.
      if((verticalExit < contacts.Entry) || (contacts.Exit < verticalEntry)) {
        return Contacts::None;
      }

      // Restrict the intervals from the X axis of the rectangle to where
      // the line is also within the limits of the rectangle on the Y axis
      contacts.Entry = std::fmax(verticalEntry, contacts.Entry);
      contacts.Exit = std::fmin(verticalExit, contacts.Exit);
    }
  } else if((line.Offset.Y < rect.Min.Y) || (line.Offset.Y > rect.Max.Y)) {
    return Contacts::None; // Rectangle missed by horizontal line
  }

  return contacts;
}

This approach offers a high degree of numerical stability (the intervals are, in all cases, the result of  a single subtraction and division) but involves some branching.
For a line segment (with start and end points), you'd need to provide the segment's start point as the origin and for the direction, end - start. Calculating the coordinates of the two intersections is a simple as entryPoint = origin + direction * contacts.Entry and exitPoint = origin + direction * contacts.Exit.

A: With a little math, you can solve this problem in a much easier fashion than most of these answers suggest.
Strategy:

*

*Transform the line and rectangle so that the center of the rectangle is at the origin (0,0).

*Scale both line and rectangle by the width/2 and height/2 of the rectangle (called xradius and yradius in my code sample below), so the problem becomes essentially "find the intersection point of [a line between point p and the origin] with [a square of size 2 which is centered on the origin]".

*We can now find the intersection point on the nearest side of the square by scaling down the coordinates of point p so that it lies on the square (by making either of the coordinates equal to +1 or -1).

*Since the problem is now symmetrical, if we take the absolute value of x and y, we can transform (mirror) the problem into only "Quadrant 1" of the grid, where x and y are both positive. This avoids having to handle each side of the box individually.

*In Quadrant 1, find the intersection point. If p is above the line x==y, we need to divide by y to put the point on the nearest line, and if it's below that line we need to divide by x instead. Note that even though the scaling factor was calculated with the absolute values of the x and y coordinates, it can be used to scale the original coordinates also.

*Now that we have the intersection point, inverse-transform it to undo the transformations from step 2 and step 1.

In C++, this looks something like:
struct point { double x, y; };
struct rect { point center; double xradius, yradius; }
point intersect(const point& p, const rect& r) {
    // Steps 1 and 2: Transform to origin and scale by xradius and yradius.
    point q{ (p.x - r.center.x) / r.xradius, (p.y - r.center.y) / r.yradius };
    // Steps 3 and 4: Transform to Quadrant 1 and find scaling factor.
    double f = max(abs(q.x), abs(q.y));
    // Step 5: Divide by scaling factor to find intersection point on square.
    point intersect{ q.x/f, q.y/f };
    // Step 6: Inverse transformations from steps 1 and 2.
    return {intersect.x * r.xradius + r.center.x, intersect.y * r.yradius + r.center.y};
}

if you have access to a true vector and matrix class with operator overloading, the code becomes even easier:
point intersect(const point& p, const rect& r) {
    matrix m = scale_matrix(r.xradius, r.yradius)*translate_matrix(p - r.center)
    point q = m * p;
    return m.inverse() * q/(max(abs(q.x), abs(q.y))
}

Warning: This code doesn't handle the case where p.x==r.centerx && p.y==r.centery which will result in a divide-by-zero error in step 5. Handling that error condition will be left as an exercise to the reader. :-)


text:
Q: I am trying to write a function in python that takes user input and stores it in a list right now I believe I have started off the loop correctly but for some reason it stops after two iterations, and when I print the list, there are no values.
I know its a really beginner question, but I am really having trouble with this.
def string():
    """Grabs user input and stores it in a list"""
    vegies = []
    choice = None

while choice != "Q":
    choice = input("Please select a vegetable or fruit to the list or Q to quit:")
    vegies = vegies.append(choice)

A: The problem is that you are doing veggies = veggies.append(something).
The method append does not return any value, so it is wrong to write variable = list.append() once, as it won't return anything, variable will hold None as value.
In order to use append, use only veggies.append(something)
def string(): #Although not wrong in terms of syntax, it is not recommended to name the function 'string'
 """Grabs user input and stores it in a list"""
    vegies = []
    choice = None

    while choice != "Q":
        choice = input("Please select a vegetable or fruit to the list or Q to quit:")
        vegies.append(choice)

A: A much easier route (Note : I am using python 2.7.9, you are using python 3.x so just substitute raw_input with input
vegies = raw_input('Enter vegetable or fruit seperated by spaces: ')
print vegies.split(' ')

Output:
Enter vegetable or fruit seperated by spaces: apple banana orange
['apple', 'banana', 'orange']

You can very do veggie_list = vegies.split(' ') to store the list and carry on with your program


text:
Q: Is there a term before the first term in a sequence? I was skimming through some questions on arithmetic sequences and I came across one that confused me it goes:
 The sum of three consecutive terms of an A.P. is 18 and their product 120. Find the terms.
The terms they used were (a-d), a, (a+d). If a is the first term then what term is (a-d) and why was it used.

A: Call the three elements in arithmetic progression Good, Bad and Ugly. Then the assumptions are that

*

*There exists $d$ such that $\mathit{Bad}=\mathit{Good}+d$ and $\mathit{Ugly}=\mathit{Bad}+d$;

*$\mathit{Good}+\mathit{Bad}+\mathit{Ugly}=18$;

*$\mathit{Good}\cdot\mathit{Bad}\cdot\mathit{Ugly}=120$.

Well, maybe using $G=\mathit{Good}$, $B=\mathit{Bad}$ and $U=\mathit{Ugly}$ might make things simpler. Then the second and third conditions would become
$$
G+(G+d)+(G+2d)=18,\qquad G(G+d)(G+2d)=120
$$
However, exploiting symmetry is always better. Note that if we change $d$ to $-d$, we get another feasible solution with the same middle term.
Thus, instead of starting from the first term, we start from the second:
$$
(B-d)+B+(B+d)=18,\qquad (B-d)B(B+d)=120
$$
Isn't this simpler? The first equation becomes $3B=18$, so $B=6$. Therefore the second equation is
$$
6(6-d)(6+d)=120
$$
or $36-d^2=20$, thus $d^2=16$ and $d=\pm4$.
If $d=4$, we have $\mathit{Good}=6-4=2$, $\mathit{Bad}=6$, $\mathit{Ugly}=6+4=10$; if $d=-4$, we have $\mathit{Good}=6+4=10$, $\mathit{Bad}=6$, $\mathit{Ugly}=6-4=2$.
"Bad" was not so bad, after all!

A: Well $a$ is not the first term of that A.P., instead it is the second term. In fact the first term of that A.P. is $a-d$. It can be made easier to visualize by setting $a-d=b$ and so you get $a=b+d$ and $a+d=b+2d$. So nevertheless, they are considering the A.P. $b,b+d,b+2d$ with $b=a-d$. Such type of substitutions are made especially when the problem refers to product of terms because in that case we can use the identity $(a+d)(a-d)=a^2-d^2$ which makes the product look better. Also sometimes such substitutions are made in the case of adding terms in an A.P. because $(a+d)+(a)+(a-d)=3a$ looks much better than $(b)+(b+d)+(b+2d)=3b+3d$.


text:
Q: How to stop the animation of my object at a set distance? I have written a code where my object starts animation at a click and ends when the mouse is hovered over the object, but I'm struggling to implement how to stop it at a certain distance ie animation of object stops after 200px distance. I've tried doing experiments with setIntervals and such in my code, but none went the way I wanted it to. In the end, I've ended up deleting it back to this original code below:

//      MOTION VARIABLES
const block = document.querySelector('.red');
const center = {
  x: parseFloat(getComputedStyle(block).left),
  y: parseFloat(getComputedStyle(block).top),
};
let newX = 0.0;
let newY = 0.0;
let motionSway = 0.02;
let naturalSway = 0.1;
let animatedValue = 0.0;
let animationId = null;

function startAnimation(){

// MOTION MODIFICATION
  newX = center.x + animatedValue;
  newY = center.y + (25/*size of amp*/ * Math.sin(motionSway * animatedValue /*the time it takes*/)) + naturalSway;

  block.style.left = `${newX}px`;
  block.style.top = `${newY}px`;

  animatedValue++;

  animationId = requestAnimationFrame(startAnimation);//recursion

}

window.addEventListener('click', () => {
      startAnimation();
});

window.addEventListener("mouseover", () =>{
  cancelAnimationFrame(animationId);
});
.red{
  width: 100px;
  height: 100px;
  background: red;
}

NOTE
I adjusted the objects, classname etc from my original code in attempt for readibility, but it ended up making the JS not responsive. (The JS code works as is in my original but it lags quite a bit with all the other functions etc <- not sure if this is due to my own laptop not being able to handle all the animation going or what..) It's suppose to move in an up and down motion but please let me know if I should change the snippet to what I have in my original code!
If anyone knows a way to implement stopping at a set distance with the code I have it would be great! :)
Thank  you!

A: I am trying to resolve your problem in the following way as per your requirement. Please check the same.
I have added the animation through CSS and handing it through Javascript.
When clicked anywhere on the document, the animation starts playing. And when hovered over the object, the animation will pause and if clicked again, it will run. Also, at a distance of 200px, it will pause by itself.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Animation</title>

A: If you are trying to stop the animation when the x position of the object is at say 200px, you can do something like this:
if(newX <= 200){
     newX = center.x + animatedValue;
     block.style.left = `${newX}px`;
     animatedValue++;
     animationId = requestAnimationFrame(startAnimation);
}

A: Sorry if it's confusing, another reason why I set it the way I did in the snippet was because I was unsure how add SCSS to the styling portion of the code.
Perhaps I could just post my codepen here:
https://codepen.io/ko-d14/pen/poeKOga
I'm still in the process of learning how JS works, so I apologize in advance if the code isn't clean.

//      MOTION VARIABLES
const candle1 = document.querySelector('.container');
const center = {
  x: parseFloat(getComputedStyle(candle1).left),
  y: parseFloat(getComputedStyle(candle1).top),
};
let newX = 0.0;
let newY = 0.0;
let motionSway = 0.02;
let naturalSway = 0.1;
let animatedValue = 0.0;
let animationId = null;

function startAnimation(){

// MOTION MODIFICATION
  newX = center.x + animatedValue;
  newY = center.y + (25/*size of amp*/ * Math.sin(motionSway * animatedValue /*the time it takes*/)) + naturalSway;

  candle1.style.left = `${newX}px`;
  candle1.style.top = `${newY}px`;

  animatedValue++;

  animationId = requestAnimationFrame(startAnimation);//recursion

}

window.addEventListener('click', () => {
      startAnimation();
});

window.addEventListener("mouseover", () =>{
  cancelAnimationFrame(animationId);
});

// makes the eye follow mouse
window.addEventListener('mousemove', function (e) {eyeball(e.pageX, e.pageY);});
function eyeball(targetX, targetY) {
  const eye = document.querySelectorAll('.eye');
  eye.forEach(function(eye){
    let x = (eye.getBoundingClientRect().left) + (eye.clientWidth / 2);
    let y = (eye.getBoundingClientRect().top) + (eye.clientHeight / 2);

    let radian = Math.atan2(targetX - x, targetY - y);
    let transformX = Math.round(Math.sin(radian) * 100);
    let transformY = Math.round(Math.cos(radian) * 100);
    eye.style.transform = "translate("+transformX+"%, "+transformY+ "%)";
  });
}

$('.candle-fire-container').fadeOut(15000);
$bg: #0f092e;
$candle-width: 60px;

body {
  margin: 0;
  padding: 0;
  background: $bg;
  display: flex;
  width: 100%;
}
// EYE

.eye-container {
  position: absolute;
  display: flex;
  justify-content: center;
  width: 100%;
  margin-top: 20px;
 }

@keyframes blink{
  to{
    transform: translateY(-99%);

  }
}
.eyeball{
  position: relative;
  width: 100px;
  height: 90px;
  border-radius: 50%;
  background: white;
  margin-right: 50px;
  box-shadow: inset 0 0 5px black;
  overflow: hidden;

  &:before{
    content: '';
    position: absolute;
    @extend .eyeball;
  background: $bg !important;
    animation: blink 6s infinite ease-in-out alternate;
    transition-delay: 15s;
    box-shadow: none !important;
    z-index: 3;
    border-radius: 0 !important;
  }
}
.pupil{
  margin-left: 25px;
  margin-top: 25px;
 width: 50px;
  height: 45px;
  border-radius: 50%;
  background: black;
  border: 10px solid purple;
    box-sizing: border-box;
}

// CANDLE
.container { // what will be used for eyes to follow
  position: absolute;
  display: flex;
  width: 100%;
  left: 50%;
  top: 50%;
  //box-shadow: 0 0 3px #3b3657;
  transform: translate(-50%, -50%);
  padding: 35px;
    z-index: 10;
}

@keyframes float{
  35%{
    transform: scale(1.5) translate(0, -10%);
  }
  50%{
    transform: scale(1) translate(0, -20%);
  }
  75%{
    transform: scale(1.2) translate(0, -30%);
  }
  100%{
    transform: scale(1) translate( -5%, 0);
  }
}
.candle-fire-container {
  position: relative;
opacity: 0.7;

  .candle-fire {
    position: absolute;
    top: -90px;
    left: 15px;
    width: 0;
    height: 0;

    border-right: 17px solid transparent;
    border-left: 17px solid transparent;
    border-bottom: 60px solid salmon;
    border-bottom-left-radius: 15px;
    border-bottom-right-radius: 12px 10px;
animation: float 5s ease alternate infinite;

    &:after {
      //bottomhalf
      content: "";
      position: absolute;
      width: 30px;
      height: 40px;
      border-radius: 50%;
      background: salmon;
      top: 35px;
      left: -15px;
      box-shadow: 0 6px 60px 25px salmon;
      z-index: 2;
    }
  }
}

.candle-fire-inner {
  position: absolute;
  top: -80px;
  left: 25px;
  width: 0;
  height: 0;

  border-right: 6px solid transparent;
  border-left: 6px solid transparent;
  border-bottom: 40px solid yellow;
  border-bottom-left-radius: 15px;
  border-bottom-right-radius: 16px 19px;
  z-index: 3;
  animation: float 5s ease alternate infinite;

  &:after {
    content: "";
    position: absolute;
    width: 11px;
    height: 22px;
    border-radius: 50%;
    background: yellow;
    top: 25px;
    left: -5px;
    box-shadow: 0 0 35px 10px yellow;
  }
}

.candle-wick {
  position: relative;
  width: 2px;
  height: 15px;
  background: #452d2b;
  top: -10px;
  left: 30px;
}

.candle-stick {
  background: #ededed;
  height: 200px;
  width: $candle-width;
  border-radius: 5px;
  border-top-left-radius: 10px;
  border-top-right-radius: 15px;
  box-shadow: inset 0 0 5px lightGray;

  &:after {
    //shadow
    content: "";
    position: absolute;
    background: lightGray;
    height: inherit;
    width: 30px;
    border-radius: inherit;
    border-top-right-radius: 3px 20px;
    border-bottom-right-radius: 10px 20px;
  }
}

.candle-reflection {
  position: relative;
  height: 100px;
  width: 7px;
  background: white;
  border-radius: 20px;
  left: -13px;
  top: 20px;
}


text:
Q: If the range of a random variable is an interval, is its CDF continuous? Let $X:\Omega\to\mathbb{R}$ be a random variable whose range is an interval. Does it follows that its CDF is continuous?
Many probability books define a continuous random variable to be a random variable which takes values in a "continuous scale," whatever that means. More rigorous books define it to be a random variable whose CDF is continuous. I'm trying to reconcile these two definitions.

A: Let
$$F(x)=\begin{cases}0&\text{for }x<0\\\frac x 2&\text{for }0\le x <\frac12\\\frac{x+1}2&\text{for }\frac12\le x<1\\1&\text{for }x\ge 1.\end{cases}$$
This is the cdf of a random variable whose range is the interval $[0,1]$, but $F(x)$ is discontinuous as a function of $x$.  The distribution of the random variable is a non-trivial convex combination of the uniform distribution on $[0,1]$, which is a continuous distribution, and the discrete point-mass at $x=\frac12$.  Since the support of the discrete part is a subset of the interval supporting the continuous part, the range is an interval.


text:
Q: how to position a div in the center and hide it? i want to make a login page but it is hidden in the center of the main page.
and then i use jquery to make the div that surrounds it visible and it will be like the login page at www.bytes.com.
but i cant figure it out how to center it with css. it doesnt work without affecting the main pages div positions.
i just want it to float over the main page. someone?

A: Is this what you want? Note the CSS comment. It's important to get the div centered. The "trick" that make the float above the other parts of your site, is position: absolute.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Centering a DIV with CSS</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        Login content

<input type="button" value="Login" onclick="$('#login').show()" />

A: You could try using a modal form for your login. jquery ui do a nice one http://jqueryui.com/demos/dialog/#modal-form which will open up a form for you to use in the centre of the page.


text:
Q: File.SetAttributes() not working on USB key as expected FileAttributes attrs = File.GetAttributes( path);
File.SetAttributes( path, FileAttributes.Hidden );
attrs = File.GetAttributes( path);

This code snippet works on my NTFS file system (C:\Temp...\whatever_file).  But when I try to perform this same operation on a USB key (FAT file system) it never successfully sets the Hidden attribute.  If I manually set it in Windows Explorer, then the first line returns correctly that it is set.  But the third line (checking it) never sets it if its not set.
I'll give a free puppy to whoever can tell me why. :)
UPDATE: When I say it doesn't work, I mean when I go back to Windows Explorer and look at the file it doesn't have the hidden attribute set.  In fact, when I do the second GetAttributes it shows that the bit is set.  But in Windows Explorer it is not set.  Even if I remove the USB key and reinsert it to be sure it refreshes correctly.

A: Thank you all for your input, but I completely neglected to look at the REST of my code where I recursively turn off the read-only attribute on all of the files I've written to my USB key, thus negating whatever I'd done before.
I repent in dust and ashes.


text:
Q: Android: How to write text under the icon in the actionbar I would like to write under the text in the action bar so i use this xml:
 <item
    android:id="@+id/Home"
    android:icon="@drawable/ic_action_home"
    android:showAsAction="always|withText"
    android:title="home"/>
<item
    android:id="@+id/Refresh"
    android:icon="@drawable/ic_action_refresh"
    android:orderInCategory="100"
    android:showAsAction="always|withText"
    android:title="refresh"/>

although i write:
  android:showAsAction="always|withText"

this what i get :

How could I write text under the icons ?

A: 'always|withText' only works if there is sufficient room. Else, it will only place icon. In your case, you've got several icons there which does not leave any spare room for text.
You've got two options:

*

*Reduce the icons by moving them either to an overflow menu or somewhere else in your UI.

*Design images which consist both icon and text and use them as your icons.

Edit: Well, here's a lot better answer: https://stackoverflow.com/a/12225863/2511884


text: Q: How to make swagger 3 show multiple responses on swagger UI using annotations? Is it possible to use the latest swagger 3 release to show in response model not only one response class. I want to show all possible variants (e.g. 3 possible child classes can be in response - not only base class or one of child). I think, there are lots of cases where polymorphic response is returned. I have such case but I can't document it in swagger-UI using java annotations. I tried @ApiModel with subtypes and parent parameterers but this have no effect on UI. I have seen lots of bugs and issues on GitHub about my issue but still have not found any examples how to make it possible.


text:
Q: Issue resizing image in xournal I am trying to add a signature image to a pdf using xournal, which has worked many times for me in the past. This time, however, I am able to insert the image, but then it will not resize or move when I click and drag on the image, its edges, or its corners using either the left or right mouse buttons.
Is there a way to diagnose or solve this problem?
So far, I have tried rebooting, updating everything, and looking for the (nonexistent?) documentation. When I open xournal from the command line, it does give

Gtk-Message: 05:56:40.011: Failed to load module "canberra-gtk-module"

although this seems irrelevant.
If there is a better forum to post this question in, I am happy to do that.

A: I encountered the same symptoms today. Disabling XInput (in the Tools menu) restored the resizing and moving functionality.


text:
Q: Mechanical properties of solids Young's modulus of bone for tensile is $16× 10^9 N/m^2$ and for compressive is $9  × 10^9 N/m^2$
Why is  tensile Young's modulus is more than for compressive?

A: The possible sources for difference are: 1) different sample materials (i.e. different bones studied); 2) different conditions (like water content in the bone etc.); 3) different methods used (e.g. ultrasonic and mechanical results differ).
Other than that, for the same bone type measured with the same technique under same conditions both values should be the same.


text:
Q: How to add hosts to Icinga2? I'm having problem adding a host to Icinga2. I know that it is possible to add it via the following command:
icinga2 node wizard

But I have a feeling that you could add the hosts yourself, choosing which services you would like to monitor and giving your host special names and attributes. I can't seem to find those options when I add them using via the node wizard.
Do you have a clue on how to add a host without using the node wizard?
Best regards,
Eric

A: You need to do some background reading of the Icinga2 docs. Its very different from the old version and of Nagios.
This is a very simple example taken from section 3.1 of the docs
object Host "my-server1" {
  address = "10.0.0.1"
  check_command = "hostalive"
}

object Service "ping4" {
  host_name = "my-server1"
  check_command = "ping4"
}

object Service "http" {
  host_name = "my-server1"
  check_command = "http"
}

This would create a host called my-server1 with the IP of 10.0.0.1 checking it for ICMP and HTTP. There are a lot of options and a lot of setup required so you need to get familiar with the general config arrangements and directives of Icinga2. If you have a general grasp but want to know about setting up the config files see section 4 of the docs.

A: First Configuring Master server (Icinga 2 Server).
enter image description here
[root@red ~]# systemctl restart icinga2
[root@red ~]# icinga2 pki ticket --cn Bharat.centosms.com
84122cd5b3e5387d1c0f239afb9145845c0671ec
[root@Bharat ~]# yum install https://packages.icinga.com/epel/icinga-rpm-release-7-latest.noarch.rpm
[root@Bharat ~]# yum install icinga2 –y
[root@Bharat ~]# systemctl start icinga2 && systemctl enable icinga2
[root@Bharat ~]# icinga2 node wizard
[root@Bharat ~]# systemctl restart icinga2
[root@red ~]# vi /etc/icinga2/conf.d/hosts.conf
enter image description here
##################################Bharat.centosms.com##########

object Zone "Bharat.centosms.com" {
  endpoints = [ "Bharat.centosms.com" ]
  parent = "red.centosms.com"
}
object Endpoint "Bharat.centosms.com" {
  host = "192.168.10.116"
}
object Host "Bharat.centosms.com" {
  import "generic-host"
  address = "192.168.10.116"
  vars.http_vhosts["http"] = {
    http_uri = "/"
  }
    vars.disks["disk"] = {
    }
  vars.disks["disk /"] = {
    disk_partitions = "/"
  }

  vars.notification["mail"] = {
    groups = [ "icingaadmins" ]
  }
  vars.client_endpoint = "Bharat.centosms.com"
}

##################################

[root@red ~]# systemctl restart icinga2


text:
Q: How to filter an array when given the keyword and a list of fields to search? I have the following code:
export function getByKeyword(list, keyword, searchFields) {
    const search = keyword.trim().toLowerCase()

    if (!search.length) {
        return list
    }

    return list.filter(item =>
        item.name.toLowerCase().indexOf(search) > -1 ||
        item.email.toLowerCase().indexOf(search) > -1
    )
}

Currently I am using || and hardcoding the fields to search.
However I would like to make the function more reusable and pass in the searchFields which is an array of fields to search (e.g. [ 'name', 'email', 'group' ].

A: Can use Array#some()
export function getByKeyword(list, keyword, searchFields) {
    const search = keyword.trim().toLowerCase()

    if (!searchFields.length) {
        return list
    }

    return list.filter(item =>{
        return searchFields.some(field=> item[field].toLowercase().includes(keyword));
    });
}


text:
Q: Inequality in a bounded real sequence Prove or disprove that for any bounded real sequence $\{x_n\}_{n\in\mathbb{N}}$ there exist two distinct natural numbers $u,v$ such that:
$$|x_u-x_v|\cdot|u-v|\leq 1.$$

A: Here is a counter-example using Hurwitz's theorem
Let $\phi = \frac{1+\sqrt 5}2$ be the golden ration.
Since the inequality $|\phi - p/q| < 1/3q^2$ has finitely many solution for integers $p,q$,
let $N$ be an integer greater than all the $|p|$ occurring in those solutions.
Let $x_n = 3n\phi \pmod {3N}$
Suppose you find distinct integers $u$ and $v$ such that $|x_u - x_v||u-v| < 1$.
Then there are integers $p_u$ and $p_v$ such that $x_u = 3u\phi - 3Np_u$ and $x_v = 3v\phi - 3Np_v$. So $|3(u-v)\phi-3N(p_u-p_v)||u-v| < 1$, and $|\phi - N(p_u-p_v)/(u-v)| < 1/3(u-v)^2$. Hence $(N(p_u-p_v), u-v)$ is one of the finitely many solutions to the inequality above, hence $N > |N(p_u-p_v)|$. This implies $p_u = p_v$, and we get $|\phi| < 1/3(u-v)^2 \le 1/3 < \phi$, which is a contradiction.

A: I don't have any solid proof, but I do have some evidence to suggest that the proposition might be false: a proof that if there are always such $u,v$ pairs, then they occur frequently in any sequence, and second, a computed example of a sequence that has no such $u,v$ pairs, yet appears to be bounded.
Take a bound $[a,b]$.
Consider $S_n$, the set of finite sequences such that $|x_u-x_v|\cdot|u-v|<1$ for some $u,v$. Then, $|x_u-x_v|=\frac{1}{|u-v|}-\epsilon$ for some $\epsilon>0$, and so the set $$
[a,b]\times [a,b]\times\cdots\times(x_u-\frac{\epsilon}{2},x_u+\frac{\epsilon}{2})\times[a,b]\times\cdots\times[a,b]\times(x_v-\frac{\epsilon}{2},x_v+\frac{\epsilon}{2})\times[a,b]\times\cdots\times[a,b]
$$ is open in $[a,b]^n$ and is a subset of $S_n$, meaning that $S_n$ is open in $[a,b]^n$. It follows that, since $[0,b]$ is compact, by Tychonoff's theorem, $[a,b]^n$ is compact, and therefore, $\overline{S_n}$ is closed and thus compact. Let $C_n$ be the extension of $\overline{S_n}$ to $[a,b]^\omega$ by appending copies of $[a,b]$, so that by Tychonoff's Theorem, $C_n$ is compact. However, $\{C_n\}$ is a sequence of decreasing compact sets, whose intersection $\bigcap_{n\in N} C_n$ is nonempty if each $C_n$ is. An element of $\bigcap_{n\in N} C_n$ would be a sequence such that $|x_u-x_v|\cdot|u-v|\ge1$ for all $u,v$.
Thus, for a sequence bounded by $[a,b]$, if we can always find some finite sequence of length $n$ such that $|x_u-x_v|\cdot|u-v|\ge1$ for all $u,v$, we can find an infinite sequence violating the proposition. This means that, if the proposition is true, pairs $u,v$ will appear "commonly", in the sense that there is some $n$ at which all finite sequences of length $n$ must have a $u,v$ pair with $|x_u-x_v|\cdot|u-v|<1$, and so $u,v$ pairs will take up at least $\frac{2}{n}$ of the sequence.
A simple strategy of setting $x_0=0$ and $x_n$ to the minimum positive number such that $\{x_0,\cdots,x_n\}$ has $|x_u-x_v|\cdot|u-v|\ge1$ seems to work well, as demonstrated by the computer program below. The output of the program will have the bound on $\{x_n\}$ taper off to just above $2.5$ all the way into a sequence of length $250,000$, which seems to indicate that this naive sequence is bounded.
#include <stdbool.h>
#include <stdio.h>
#include <float.h>

#define EPS 0.0000000000000000002
#define NUM 250000
long double data[NUM];

static bool within(long double x, long double y, int n){
        long double test = (x-y)*n;
        return test >= (long double)(-1.0) && test <= (long double)(1.0);
}

main(){
        long double max = 0.0;
        int i;
        data[0] = 0.0;
        for(i=1; i<NUM; i++){
                long double test = ((long double)1.0)/i;
                int j;
                for(j=i-1; j>0; j--){
                        if(within(test,data[j],i-j)){
                                test = data[j]+((long double)1.0)/(i-j)+EPS;
                                j=i;
                        }
                }
                data[i] = test;
                if(test > max){
                        max = test;
                }
                if(i%100==0) printf("Got %d/%d -- max=%.15Lf\n",i,NUM,max);
        }
}


text:
Q: Conditionally sort WPF CollectionViewSource Is it possible to do a conditional sorting for WPF collection view source?
<CollectionViewSource x:Key="MyCVS" Source="{Binding MyData}">
    <CollectionViewSource.SortDescriptions>
      <scm:SortDescription PropertyName="MyProperty1" Direction="Ascending" />
    </CollectionViewSource.SortDescriptions>
</CollectionViewSource>

I want to sort on MyProperty1 under some condition and MyProperty2 under some other condition. I may be able to do it in code behind. But I would prefer do it Xaml itself if it is possible.
Something like if "MySortCondition" is true then sort by MyProperty1 if not sort by MyProperty2.
Thanks

A: Could you write a converter to change your MySortCondition into the appropriate SortDescription object (probably have to make the SortDescriptionCollection yourself in the converter...)?

A: Unfortunatly SortDescriptions are not very customizable as tey are stucts and cant be derived to add this logic, so code behind will be your best option.
   var cvs = FindResource("MyCVS") as CollectionViewSource;
   cvs.SortDescriptions.Clear();
   if (condition)
   {
      cvs.SortDescriptions.Add(new SortDescription("Property1", ListSortDirection.Ascending));
   }
   else
   {
      cvs.SortDescriptions.Add(new SortDescription("Property2", ListSortDirection.Ascending));
   }

Or... If both properties are of the same type the simple way would be to create a Sort property in your class and use that in the SortDescription
Example:
public int SortProperty
{
   get
   {
       if (condition)
       {
          return Property1;
       }
       return Property2;
   }
}

But in most cases its easier to sort the underlying collection first using Linq
public List<Type> MyData
{
    get
    {
        return _data.OrderBy(x => .........
    }
}


text:
Q: How is $\frac{1 * 3 \dots (2N+1)}{2^{N+1}} = \frac{(2N+2)!}{2^{2N+2}(N+1)!}$ $\frac{1 * 3 \dots (2N+1)}{2^{N+1}} = \frac{(2N+2)!}{2^{2N+2}(N+1)!}$
but I'm having a hard time seeing it... Starting with the LHS if we try to match the denominators then we can do this by multiply by $2^{N+1}(N+1)!$
so $\frac{1 * 3 \dots (2N+1)}{2^{N+1}}*\frac{2^{N+1}(N+1)!}{2^{N+1}(N+1)!} = \frac{\text{something}}{2^{2N+2}(N+1)!}$
but I don't see how the numerators ("something") multiplies to $(2N+2)!$
I'm looking at part (a) here if that matters.

A: Observe that
$$2^{N+1}(N+1)!=2^{N+1}(1*2*\cdots(N+1))\\=2*2^2*\cdots*(2N+2)$$
Thus
$$1*3*\cdots*(2N+1)*2^{N+1}(N+1)!=1*3*\cdots*(2N+1)*2*2^2*\cdots*(2N+2)\\=(2N+2)!$$

A: \begin{align}
\frac{1 \cdot 3 \cdots (2N+1)}{2^{N+1}}
&= \frac{\prod_{k=1}^{N+1} (2k-1)}{2^{N+1}} \\
&= \frac{\prod_{k=1}^{N+1} (2k-1) \prod_{k=1}^{N+1} (2k)}{2^{N+1}\prod_{k=1}^{N+1} (2k)} \\
&= \frac{\prod_{k=1}^{2N+2} k}{2^{N+1} 2^{N+1}\prod_{k=1}^{N+1} k} \\
&= \frac{(2N+2)!}{2^{2N+2}(N+1)!}\\
\end{align}


text:
Q: Expression isn't computed correctly I wrote this code that has evaluated everything correctly until this specific set of numbers :
#include <cmath>

int n1 = 187972 ;
int n2 = 12026 ;
double a = 0.002 ;
int partial = round((n1*n2)*a) ;
int result = n1 - partial ;

result is returned by the program as 4256804, which is completely wrong. I suppose I am mistaken,but I cannot see how.

A: as in the comments suggested, the result is correct because n1*n2 is overflowing the int max value generating a negative number as result from an overflow
actually -2034416024
here ideone so you can verify
https://ideone.com/NIGCmx
a solution could be use long numbers instead

A: #include <cmath>

int n1 = 187972 ;
int n2 = 12026 ;
double a = 0.002 ;
long long partial = round((n1*n2)*a) ;   // new
long long result = n1 - partial ;   // new


text:
Q: Action RTS style video game with javascript I wanted to see if it's possible to make a game similar to LOL DOTA or Starcraft in the browser with javascript. I'd want it to be multiplayer for sure and I'd want it to run at 60 fps. Is this possible, or would it go too slowly?

A: You could try using the WebGL technology along with WebSockets and probably then you could acheive satisfactory performance, but your game will be limited to browser which supports these technologies.


text:
Q: Add custom content after redirect wordpress I've created a function redirecting all my logged-out users to the membership page.
I want them to buy a package plan before they can view the page they tried to visit before being redirected.
If logged-in -> view the download page.
If logged-out -> redirect to the membership page -> purchase a package -> view the download page.
I want to add content to the membership page, something like:
'The product that you are trying to download cannot be purchased individually, but it's part of our membership package'
The problem is that I couldn't find a way to execute any function after the wp_redirect() function. So I don't know how to display the content only to those redirected.
Is there a way to achieve it?

A: in your header.php:
if( !is_user_logged_in() ){
    nocache_headers();
    wp_safe_redirect( get_permalink( 'YOUR_MEMBERSHIP_PAGE_ID' ) . '?message=true' );
    exit;
}

in your functions.php:
function add_query_vars_filter( $vars ){
    $vars[] = "message";
    return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

in your membership page:
if( get_query_var('message') && !is_user_logged_in() ){
        echo 'The product that you are trying to download cannot be purchased individually, but it\'s part of our membership package';
    }


text:
Q: Yii2.0 export function using kartik-v I am new in using kartik. Can I just check with you whether kartik is able to do below things? And how to do it?

*

*Display date in different format than in db. i.e. in db it is displayed as YYYY-MM-DD"T"HH:MM:SS" whereas on screen, I want to display it as YYYY-MM-DD.

*Show subtotal and total?

Since in my report screen, im using a normal html to display data since from my understanding, the gridview does not have the subtotal function.
Below is my html:
$reports = $dataProvider->getModels();
$i=1;

echo "
";
echo "
#	Item	Total Summary Usage Qty	Current Stock On Hand	Measurement
";
foreach ($reports as $report) {
    $item_key = $report['report_item_key'];
    $item_model = Item::find()->where(['item_key' =>$item_key])->one();
    $item_e_desc_tx = $item_model->desc_e_tx;
    $item_c_desc_tx = $item_model->desc_c_tx;
    $item_qty_no = $item_model->qty_no;
    $item_measurement_tx = $item_model->measurement;
    echo "
";
    echo "" . $i++ . "	";
    echo "" . Html::a($item_key, array('stockmovementreportdetailbyitem', 'item_key' => $item_key, 'search' => 'true', 'stockmovement_summary_from_sales_date' => $stockmovement_summary_from_sales_date, 'stockmovement_summary_to_sales_date'=>$stockmovement_summary_to_sales_date)) . "
" . $item_e_desc_tx . "
" . $item_c_desc_tx ."	";
    echo "" . $report['total_summary_usage_qty'] . "	";
    echo "" . $item_qty_no . "	";
    echo "" . $item_measurement_tx . "	";
    echo "
";
}
echo "
";
echo \yii\widgets\LinkPager::widget([
    'pagination'=>$dataProvider->pagination,
]);


text:
Q: Rabbit MQ. HA in kubernetes Is there any official documentation about how to deploy RabbitMQ on Kuberentes with HA?
I have found several kubernetes Helm Charts for this but they do not look official.
I'm looking for official and supported way to have HA in kubernetes.
Thank you.

A: I suspect the RabbitMQ Peer Discovery Kubernetes plugin is a good place for you to start. Notice that there are links to further documentation.

The RabbitMQ team monitors the rabbitmq-users mailing list and only sometimes answers questions on StackOverflow.


text:
Q: PIC operating temperature... "industrial" vs. "extended" I am shopping for a PIC micro-controller for use in an automotive application. I noticed that PICs are offered in both "industrial" and "extended" temperature ranges ([-40C to +85C] vs [-40 to +125]). I should use the extended version, but due to availability, I may be forced to use the industrial or do something else entirely.
In any case, I became confused when I looked at the datasheet and saw that there is no distinction made on the line where operating temperature is specified. Here is an excerpt from page 265 of the datasheet found here: http://ww1.microchip.com/downloads/en/DeviceDoc/39995d.pdf

The subsequent tables all make the distinction as seen here:

Can anyone decipher the meaning of this temperature range? Are the two versions fabricated using the same process and the extended versions are simply qualified to a higher level? Should I be concerned that the industrial version of the chip will fail at higher rates between 85C and 125C?

A: For this kind of IC, the are fabricated on the same process (thus same absolute max ratings and thermal characteristics) and the temperature grade that you buy has to do with the guaranteed test limits on Electrical Characteristics.


text:
Q: Typeahead not working, doesn't log or return anything Typeahead loads, because the input changes to what it needs to be, but then does absolutely nothing. Code:
$(function() {
 $('.typeahead').typeahead([
    {
        name: 'Search',
        valueKey: 'name',
        remote: {
            url: 'frontpage_search.php?q=%QUERY',

        },
        template: [
            '
{{name}}
'
        ].join(''),
        engine: Hogan // download and include http://twitter.github.io/hogan.js/
    }
 ]);

I include jQuery, typeahead, Hogan, and this file when the page is done loading. JSON is this:
[
 {
  "name": "Wind, Earth and Fire",
  "category": "Type"
 },
 {
  "name": "Fire Emblem",
  "category": "Finisher"
 }
]

With an application/json header, and it properly validates as JSON. What is going on?


text:
Q: UIView Frame View and CGRect Not Working on First Call So I am trying to slide a tableview in over top of a lower view, which happens to also to be a uitableview.  I have a sandwich icon to slide it in and a close icon to slide it out.
The button switching works great.  However, when clicking the close button, the first time, the tableview will not slide out, it will basically slid out and right back to where it is.
However subsequent times, after the close icon switches back to sandwich, and then I click again to bring back close, it will slide it out just fine.   Why it not work on the first try.
Below is my code.   As you can see my CGRect is supposed to animate and slide the view to the displaywidth X.
@objc func showNewsList(_ sender: UIButton) -> Void {
    let displayWidth: CGFloat = self.view.frame.width
    let displayHeight: CGFloat = self.view.frame.height
    newsIconClose.isHidden = true

    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
newsSourceTable.frame = CGRect(x: displayWidth, y: 0, width:
        displayWidth, height: displayHeight + 100)
        self.addNewsIcon()
    })

}

A: Bingo, figured it out.  For whatever reason, CGRect wasn't liked, but this is.
     self.newsSourceTable?.frame.origin.x = 0


text:
Q: vue cli inspecting css from browser development console Following various vue cli example to successfully implement scss file into the vue file, the page now loads with css imported but I cannot inspect from which file / line number the css declaration comes from, all it says in chrome console is within the  not from the actual file like "margin.scss line 40".
here is my vue.config.js
module.exports = {
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'scss',
      patterns: ["@/src/css/index.scss"]
    }
  },

here is my App.vue
<template>
  <div >

  </div>
</template>

<style lang="scss" >
  @import "./css/index.scss";
</style>

and here is what I see,

A: Activate sourcemaps:
module.exports = {
  css: {
    sourceMap: true,
  },
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'scss',
      patterns: ["@/src/css/index.scss"]
    }
  },

https://cli.vuejs.org/config/#css-sourcemap


text:
Q: A $R$-module over a ring $R$ with identity is free iff it is a direct sum of copies of $R_R$, where $R_R$ is $R$ considered as a module over itself Let $R$ be a ring with identity and $M$ be an $R$-right module. Then $M$ is called free over $X \subseteq M$ if for every module $N$ with mapping $\alpha : X \to N$ we can extend it uniquely to a homomorphism $\overline \alpha : M \to N$. For a ring $R$ denote by $R_R$ the module structure if $R$ is regarded as a module over itself.
Now I am looking for a slick and short proof of the following

A right $R$-module $M$ is free (over some set $X$) if and only if it is a direct sum of copies of $R_R$.

By some "high-level" theorems, like that $X$ is a minimal generating set for $M$ and the elements of $X$ are lineary independent in $M$ (i.e. every element from $M$ could be uniquely written as linear combination of finitely many elements from $X$) we get an isomorphism by mapping onto the "coordinates" and the direct product of a ring is module isomorphic to the direct sum of $R_R$, thus showing that every free modules is isomorphic to such a direct sum. But I hoped there might be some easier argument, without supposing linear independence of the $X$ and that $M = \langle X \rangle$.
My attempt. If $x \in X$ consider the $R$-right module $xR$ and the mapping $\beta : X \to \{x\}$, then we have a unique $\overline \beta : M \to xR$ which happens to be surjective as $\overline \beta(xr) = \beta(xr) = xr$. Now $M = xR \oplus \mbox{ker}(\overline \beta)$ as $m = rx + (m - rx)$ with $rx = \overline\beta(m)$. Now I wanted to show that $\mbox{ker}(\overline \beta)$ is free over $X \setminus \{x\}$ and hence proceed inductively. But then I realised that this is just possible if $X$ is countable or has some other structure which permits such inductive reasoning. So I guess such a reasoning is not valid in general, right? If this proof scheme does not work, are there any other short proofs of this fact?

A: It's not entirely clear to me what you are looking for exactly, but here is a short proof of your statement:
Consider the $R$-module $N= \bigoplus_{x \in X} R_x$, where each $R_x$ is just a copy of $R_R$. Denote the unit of $R_x$ by $1_x$. Then the map of sets $f: X \to N, x \mapsto 1_x$ gives a unique module homomorphism $M \to N$ extending $f$ (and which I will abusively denote by $f$ as well). Furthermore, the maps $g_x: R \to M, g_x(r) = xr$ sum up to give a homomorphism $g:N \to M$. I claim that $f \circ g = \mathrm{id}_N$ and $g \circ f = \mathrm{id}_M$. For the first equality, consider an element $a = (a_x)_{x \in X} \in N$. Then
$f \circ g(a) = f(\sum_x x a_x) = \sum_x f(x) a_x = \sum_x a_x = a$
which proves the first identity. For the latter equality, we have $g \circ f (x) = g_x(1_x) = x$, and hence $g \circ f$ is the identity on $X$. Since M is free, and $g \circ f$ is a module homomorphism, this means that it must be equal to $\mathrm{id}_M$.


text:
Q: Hash function for 2D point in limited Euclidean space I am storing a lot of objects with geographically positions as 2D points (x,y) in granularity of meters. To represent the world I am using a grid divided in cells of 1 square km. Currently I am using HashMap<Position, Object> for this. Any other map or appropriate data structure is fine, but I the solution works so I am only interested in solving the details.
I have been reading a lot about making good hash functions, specifically for 2D points. So far, no solutions have been really good (rated in terms of as collision-free as possible).
To test some ideas I wrote a very simple java program to generate hash codes for points from an arbitrary number (-1000,-1000) to (1000, 1000) (x1, y1 -> x2,y2) and storing them in a HashSet<Integer> and this is my result:
# java HashTest
4000000 number of unique positions
test1: 3936031 (63969 buckets, 1,60%) collisions using Objects.hash(x,y)
test2: 0 (4000000 buckets, 100,00%) collisions  using (x << 16) + y
test3: 3998000 (2000 buckets, 0,05%) collisions using x
test4: 3924037 (75963 buckets, 1,90%) collisions using x*37 + y
test5: 3996001 (3999 buckets, 0,10%) collisions using x*37 + y*37
test6: 3924224 (75776 buckets, 1,89%) collisions using x*37 ^ y
test7: 3899671 (100329 buckets, 2,51%) collisions using x*37 ^ y*37
test8: 0 (4000000 buckets, 100,00%) collisions using PerfectlyHashThem
test9: 0 (4000000 buckets, 100,00%) collisions using x << 16 | (y & 0xFFFF)

Legend: number of collisions , buckets(collisions), perc(collisions)
Most of these hash functions perform really bad. In fact, the only good solution is the one that shifts x to the first 16 bits of the integer. The limitation, I guess, is that the two most distant points must not be more than the square root of Integer.MAX_INT, i.e. area must be less than 46 340 square km.
This is my test function (just copied for each new hash function):
  public void test1() {

    HashSet<Integer> hashCodes = new HashSet<Integer>();
    int collisions = 0;

    for (int x = -MAX_VALUE; x < MAX_VALUE; ++x) {
      for (int y = -MAX_VALUE; y < MAX_VALUE; ++y) {
        final int hashCode = Objects.hash(x,y);

        if (hashCodes.contains(hashCode))
          collisions++;

        hashCodes.add(hashCode);
      }
    }

    System.console().format("test1: %1$s (%2$s buckets, %3$.2f%%) collisions using Objects.hash(x,y)\n", collisions, buckets(collisions), perc(collisions));
  }

Am I thinking wrong here? Should I fine-tune the primes to get better results?
Edits:
Added more hash functions (test8 and test9). test8 comes from the reponse by @nawfal in Mapping two integers to one, in a unique and deterministic way (converted from short to int).

A: public void test1() {

    int MAX_VALUE = 1000;

    HashSet<Integer> hashCodes = new HashSet<Integer>();
    int collisions = 0;

    for (int x = -MAX_VALUE; x < MAX_VALUE; ++x) {
        for (int y = -MAX_VALUE; y < MAX_VALUE; ++y) {
            final int hashCode = ((x+MAX_VALUE)<<16)|((y+MAX_VALUE)&0xFFFF);

            if (hashCodes.contains(hashCode))
                collisions++;

            hashCodes.add(hashCode);
        }
    }

    System.out.println("Collisions: " + collisions + " // Buckets: " +  hashCodes.size());
}

Prints: Collisions: 0 // Buckets: 4000000

A: I a similar question with the answer being to use a Cantor pairing function. Here:
Mapping two integers to one, in a unique and deterministic way.
The Cantor pairing function can be used for negative integers as well, using bijection.


text:
Q: Reason for a blocked page on WebSense On some perfectly ligitimate sites, WebSense will randomly block images and allow others. However, when blocking images, instead of having blockpage.cgi display a page with the reason the page was blocked, it returns a 1px image so that the page that requested the image still renders. Makes sense.
My question: Is there any way, as a user, using the provided ws-session, to get the reason  WebSense blocked the image so that I can diagnostic the problem with the page?

A: To my knowledge, without access to the Websense admin console, you can't do what you want to do.


text:
Q: File is not closing properly I'm not sure why, but the file 'refined.txt' is not closing properly (see code below). I get a Windows error ("The process cannot access the file because it is being used by another process") when I try to rename the file in the last line of code.
It is important that this file is renamed because this piece of code is part of a for loop, so if I don't rename the file to something unique it will get written over.
I am hoping that someone will be able to tell me why the file isn't closing properly.
Code:
    of = open('refined.txt')
    d=of.readlines()

    for line in d[:20]:
        #some code

    of.close()
    os.rename('refined.txt', new)

A: Try using the with statement to open the file instead, and see if that makes any difference.
with open('refined.txt') as of:
    d = of.readlines()

for line in d[:20]:
    #some code

os.rename('refined.txt', new)


text:
Q: Javascript syntax error ) SyntaxError Uncaught

            Edit this post

This will Update the content of this post

this is how the syntax looks like on the browser

          Edit this post

This will Update the content of this post

and this is the syntax on the editor
when I'm trying to invoke EditRegPost() function on click
it fails and display this message :
Uncaught SyntaxError: missing ) after argument list
I'm not really sure how , my syntax seems to be right . I would appreciate any help , thanks

A: Use \ in the String of the second param
onclick="EditRegPost('5' , 'I\'M NEW REGULATION')"