Creating SVG rectangle in React using mouse events

Question: I'm trying to convert a vanillajs/jquery example of using mouse events to draw SVG rectangles to a React component. Here is the vanilla js example:  VanillaJS SVG Rectangles (click codesandbox refresh button is html doesn't display)
 import "./styles.css";
var svgns = "http://www.w3.org/2000/svg";
var svgDoc;
var currentDrawing;
var startX;
var startY;
var offsetX;
var offsetY;
var isDrawing = false;

function init() {
  createSVGDoc();
  var position = $("#svgWrapper").position();
  offsetX = position.left;
  offsetY = position.top;
  console.log("offsetX = " + offsetX);
  $("#svgWrapper").mousedown(onCanvasMouseDown);
  $("#svgWrapper").mousemove(onCanvasMouseMove);
  $("#svgWrapper").mouseup(onCanvasMouseUp);
  $("#svgWrapper").mouseleave(onCanvasMouseLeave);
}

function createSVGDoc() {
  var imageWidth = parseInt($("#image").css("width"));
  var imageHeight = parseInt($("#image").css("height"));
  console.log(imageWidth);
  console.log(imageHeight);
  svgDoc = document.createElementNS(svgns, "svg");
  svgDoc.setAttribute("style", "border: 1px solid black");
  svgDoc.setAttribute("width", imageWidth);
  svgDoc.setAttribute("height", imageHeight);
  $("#svgWrapper").append(svgDoc);
}

function onCanvasMouseDown(event) {
  isDrawing = true;
  currentDrawing = document.createElementNS(svgns, "rect");
  startX = event.pageX - offsetX;
  startY = event.pageY - offsetY;
  currentDrawing.setAttributeNS(null, "x", startX);
  currentDrawing.setAttributeNS(null, "y", startY);
  currentDrawing.setAttributeNS(null, "width", "5");
  currentDrawing.setAttributeNS(null, "height", "5");
  currentDrawing.setAttributeNS(null, "fill", "none");
  currentDrawing.setAttributeNS(null, "stroke", "red");
  currentDrawing.setAttributeNS(null, "stroke-width", "5");
  svgDoc.appendChild(currentDrawing);
}

function onCanvasMouseMove(event) {
  if (!isDrawing) {
    return;
  }
  var wid = event.pageX - offsetX - startX;
  var hei = event.pageY - offsetY - startY;
  if (wid > 0) {
    currentDrawing.setAttributeNS(null, "width", wid);
  } else {
    currentDrawing.setAttributeNS(null, "width", Math.abs(wid));
    currentDrawing.setAttributeNS(null, "x", event.pageX - offsetX);
  }
  if (hei > 0) {
    currentDrawing.setAttributeNS(null, "height", hei);
  } else {
    currentDrawing.setAttributeNS(null, "height", Math.abs(hei));
    currentDrawing.setAttributeNS(null, "y", event.pageY - offsetY);
  }
}

function onCanvasMouseUp(event) {
  if (!isDrawing) {
    return;
  }
  var wid = currentDrawing.getAttributeNS(null, "width");
  var hei = currentDrawing.getAttributeNS(null, "height");
  if (wid < 10 || hei < 10) {
    svgDoc.removeChild(currentDrawing);
  }
  isDrawing = false;
}

function onCanvasMouseLeave(event) {
  if (!isDrawing) {
    return;
  }
  svgDoc.removeChild(currentDrawing);
  isDrawing = false;
}

$(document).ready(function() {
  init();
});

Here is an attempt to rewrite the code using React: React SVG Rectangles
    import React from "react";
import "./styles.css";
const initMouse = {
  width: 0,
  height: 0,
  offsetX: 0,
  offsetY: 0,
  startX: 0,
  startY: 0,
  isDrawing: false
};
const getElOffset = el => {
  const rect = el.getBoundingClientRect();

  return {
    top: rect.top + window.pageYOffset,
    left: rect.left + window.pageXOffset
  };
};

const getCoords = e => {
  if (e.pageX || e.pageY) {
    return { x: e.pageX, y: e.pageY };
  }
  return {
    x: e.clientX,
    y: e.clientY
  };
};

export default function App() {
  const [drawings, setDrawings] = React.useState([]);
  const [mouseState, setMouseState] = React.useState(initMouse);

  const down = e => {
    var mouseCoords = getCoords(e);
    var offset = getElOffset(e.target.parentNode);
    const startX = mouseCoords.x - offset.left;
    const startY = mouseCoords.y - offset.top;

    setMouseState({
      ...mouseState,
      isDrawing: true,
      startX: startX,
      startY: startY,
      width: 5,
      height: 5,
      offsetX: offset.left,
      offsetY: offset.top
    });
  };
  const up = e => {
    if (!mouseState.isDrawing) return;

    var wid = mouseState.width;
    var hei = mouseState.height;

    if (wid < 10 || hei < 10) {
      setMouseState({ ...initMouse });
    } else {
      setMouseState({ ...initMouse });
      setDrawings([...drawings, ...[mouseState]]);
    }
  };
  const move = e => {
    if (!mouseState.isDrawing) return;

    var currX = e.pageX - mouseState.offsetX;
    var currY = e.pageY - mouseState.offsetY;

    var wid = currX - mouseState.startX;
    var hei = currY - mouseState.startY;
    if (wid <= 0) {
      wid = Math.abs(wid);
    } else {
      currX = mouseState.startX;
    }
    if (hei <= 0) {
      hei = Math.abs(hei);
    } else {
      currY = mouseState.startY;
    }

    setMouseState({
      ...mouseState,
      startX: currX,
      startY: currY,
      width: wid,
      height: hei
    });
  };
  const leave = e => {
    if (!mouseState.isDrawing) return;
    setMouseState({ ...initMouse });
  };
  const renderManual = () => {
    return drawings.length > 0 ? (
      <>
        {mouseState.isDrawing ? (
          <rect
            x={mouseState.startX}
            y={mouseState.startY}
            width={mouseState.width}
            height={mouseState.height}
            fill="none"
            style={{ strokeWidth: 5, stroke: "black" }}
          />
        ) : null}
        {drawings.map((a, index) => (
          <g key={index} style={{ cursor: "pointer" }}>
            <rect
              x={a.startX}
              y={a.startY}
              width={a.width}
              height={a.height}
              fill="none"
              style={{ strokeWidth: 5, stroke: "black" }}
            />
          </g>
        ))}
      </>
    ) : (
      <>
        {mouseState.isDrawing ? (
          <rect
            x={mouseState.startX}
            y={mouseState.startY}
            width={mouseState.width}
            height={mouseState.height}
            fill="none"
            style={{ strokeWidth: 5, stroke: "black" }}
          />
        ) : null}
      </>
    );
  };
  return (

          <svg width="800" height="500" style={{ border: "1px solid black" }}>
            {renderManual()}
          </svg>

  );
}

Everything appears to be working as expected until initiating mouse moves in the directions left and up. In this case the rectangles are not drawn. I'm having a difficult time understanding why the rectangles do not draw correctly when performing left and up direction mouse move events, but do so correctly in the VanillaJS example. Some extra eyes, and any help on this would be greatly appreciated.
Comment: Please include the code within the question itself, not as links.
Answer: Additional state props (lastMoveX, lastMoveY) where needed so the original start x,y coordinates don't get overwritten. Here are the modifications:
   const initMouse = {
        lastMoveX:0,
        lastMoveY:0,
        width:0,
        height:0,
        offsetX:0,
        offsetY:0,
        startX:0,
        startY:0,
        isDrawing: false
    }
 const imgMouseDown = (e) => {
        var mouseCoords = getCoords(e)
            var offset = getElOffset(e.target);
            console.log(offset)
            const startX = mouseCoords.x - offset.left;
            const startY = mouseCoords.y - offset.top;
            setMouseState({...mouseState, isDrawing:true, lastMoveX:startX, lastMoveY:startY, startX: startX, startY: startY, width: 5, height:5, offsetX: offset.left, offsetY: offset.top})

    }
const imgMouseMove = (e) => {
    if(!mouseState.isDrawing) return;

    let state = {...mouseState};

    var width = e.pageX - state.offsetX - state.startX;
    var height = e.pageY - state.offsetY - state.startY;
    console.log(`w ${width} h ${height}`);

    if(width > 0){
        state.width = width;

    } else{
        state.width = Math.abs(width);
        state.lastMoveX= e.pageX - state.offsetX;

    }
    if(height > 0){
        state.height = height;

    } else{
        state.height = Math.abs(height);
        state.lastMoveY = e.pageY - state.offsetY;

    }
    setMouseState({...state})

    }
    const render = () => {

            return drawings.length > 0 ? (
                <>
                { mouseState.isDrawing ?
                    <rect
                        x={mouseState.lastMoveX}
                        y={mouseState.lastMoveY}
                        width={mouseState.width}
                        height={mouseState.height}
                        fill='none' style={{strokeWidth:5 ,stroke:'#009900', strokeDasharray:2 }}></rect>
                 : null }
                {drawings.map((a,index) =>
                    <g key={index} style={{cursor: 'pointer'}}>
                    <rect
                        x={a.lastMoveX}
                        y={a.lastMoveY}
                        width={a.width}
                        height={a.height}
                        fill='none' style={{strokeWidth:5 ,stroke:'#009900', strokeDasharray:2}}></rect>
                    </g>

                )
                }
                </>

            ) : (
                <>
                { mouseState.isDrawing ?
                    <rect
                        x={mouseState.lastMoveX}
                        y={mouseState.lastMoveY}
                        width={mouseState.width}
                        height={mouseState.height}
                        fill='none' style={{strokeWidth:5 ,stroke:'#009900', strokeDasharray:2}}></rect>
                 : null }
                </>
            )

        }


java access class's variable in thread and use outside thread

Question: I've a GUI Class Named as NewFrame.java and another one is Client.java. in Client.java, the NewFrame's object is made inside a thread. ex,
public class ClientA {

NewJFrame gui;
int x ;

public void go() {
            java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                gui  = new NewJFrame();
                gui.setVisible(true);
                x = 10;
            }
        });

        System.out.println(x); // does not print 10 but it prints 0

        gui.setTextboxvalue("value changed !!!");

        // can'se pass value to the function, with this error occurs as,
        // "java.lang.NullPointerException" at here.

      }
}

here two problems occuring,
there is the setter method in NewFrame class named setTextboxValue but calling this as shown above the error occurs "java.lang.NullPointerException".
another problem is : why i can't set the variable x inside that thread, setting this inside thread, the outside printing the variable x's value which is 10 is not printing there instead it prints 0
Comment: *"i've a gui class called.."*  Do you have a shift key?  That should be *"I've a GUI class called.."*.  Please show more effort in future.
Comment: Question is Updated as per your Desire !!!
Answer: EventQueue.invokeLater invokes its methods on a separate thread, which is fired off asynchronously on the event dispatch thread after all the other tasks on the event dispatch thread have finished.  In other words, that code inside the run() method is likely going to be executed after your method finishes.  Therefore, the gui variable is still going to be null, resulting in a NullPointerException when you call gui.setTextboxvalue; and x is still going to be 0 when you print out the value.
Comment: the code under `java.awt.EventQueue.invokeLater` is autogenerated with netbeans and i think its not good to initialize the gui class out of the `java.awt.EventQueue.invokeLater` ..
Comment: so what is the solution to access it ?
Comment: You can either create the NewJFrame instance in your main thread, or you can do the other work in the event dispatch thread after the NewJFrame instance has been initialized.
Comment: @BhaveshGangani Use a second EventQueue.invokeLater to wrap around setTextboxvalue
Comment: @EricGalluzzo See [Initial Thread](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html) for reasons why it's a bad idea to initialise the UI outside of the EDT
Comment: is it safe to declare `gui  = new NewJFrame();` outside the thread ? eg. before the thread ?


When is subsetting survey data prior to analysis NOT a problem?

Question: Survey researchers are typically advised to not subset their data prior to analysis because it will produce incorrect variance estimates. My understanding of the inferential issue is that removing observations rather than setting their sampling probability to 0 is only problematic because it will lead to incorrect numbers of PSUs.
However, I'm not sure then how to reconcile this with other advice I've found, which is that it is okay to pre-subset when there is no clustering or stratification in the design. On the one hand, subsetting could theoretically remove all observations from a PSU and that information would be lost. On the other hand, in non-clustered/stratified sampling, each observation is its own PSU and therefore dropping observations would be problematic on the grounds that it removes PSUs from the sampling information.
Can someone provide an explanation for when it IS okay to pre-subset rather than set weights to 0? (or INF depending upon how the weights are provided)? Would appreciate some demonstration via reference to the variance estimation of the H-T estimator, but okay without.
Answer: There are two issues here:

When is it desirable to remove some records from the data set before analysis?
When doesn't it make any difference?

When to remove records before analysis
You want to remove records before analysis when the records are not part of the sample.  Consider, if you will, the NHANES series of surveys. These recruit a whole lot of people. Some of the people only get asked questions; some also get a full medical exam; some also get blood drawn for biochemical tests.  If you want to analyse the blood tests, you need to use the blood tests sample. People who were not chosen for the medical exam/blood tests are not part of the sample and should not be included.  Operationally, they will have missing values for the blood-test-sample weight variable.
You can think of this as just a data-compression hack. There are three (or maybe more) overlapping but conceptually distinct samples being taken. They are stored in the same data file for convenience, so some of the records in that data file may not belong to the sample you are analysing. This has nothing to do with the Horvitz-Thompson variance estimator; it's just bookkeeping.
When subsetting (potentially) doesn't matter
Once you have identified the sample, your analysis should ideally use everyone in the sample, even when you are interested in a specific subpopulation. If you want, say, the mean for people over 60, you estimate by setting the sampling weight to zero for people who are not over 60.
You will get the same point estimates by just subsetting to the subpopulation of interest. In general you will not get the same standard error estimates. But sometimes you will. There are two situations where you get the correct standard errors by subsetting.
The good one: strata. Strata behave like (are?) separate survey samples conducted for specific subpopulations.  If your subpopulation of interest is a stratum or a set of strata, it is valid to subset to just those strata before analysis.  In terms of the variance estimator, the variance of an estimated population total is just the sum over strata of the variance of the estimated stratum totals, because the estimated stratum totals are independent.
The slightly dodgy one: all the PSUs. This is the one that depends on the details of the variance estimator. Suppose your survey is (or is approximated by) a single stage of stratification and clustering, with clusters sampled 'with replacement'. This is a common public-use data format, eg for NHANES. The Horvitz-Thompson variance estimator for a total is
$$\sum_{h\in\textrm{strata}}\sum_{i\in\textrm{PSUs}} (Z_{hi}-\bar Z_h)^2$$
where $Z_{hi}$ is the weighted sum in PSU i, stratum h.
If every PSU appears in the subpopulation, then $Z_{hi}$ is a non-empty sum for every PSU, so $Z_{hi}$ is the same whether you (incorrectly) drop records outside the subpopulation or (correctly) use a weight of zero for records outside the subpopulation.  If PSU $i$ in stratum $h$ does not appear in the subpopulation and you (incorrectly) drop records, you don't have a $Z_{hi}$. If you (correctly) use zero weights, you get $Z_{hi}=0$.
If you have a more complicated design -- eg the actual four-phase NHANES design -- you would need to worry about smaller changes when some secondary sampling units or tertiary sampling units or whatever weren't in the subpopulation. But if you're working with the actual four-phase NHANES design you probably know the answer already.
Comment: It would be great if you could offer more precision about "not part of the sample." Suppose you have a simple random sample of adults but wish to make inferences about (adults | age >= 50). The subpop of adults | age < 50 is "part of the sample" but the inferential population is different. Seems like you'd advise down-weighting rather than excluding. I understand your claim that the difference between this and the blood test is that the blood test has missing data due to membership in the subpop...but supposing we imputed missing values, would we use subgroup analysis? (1/2)
Comment: This isn't about the inferential population or about missing data, it's entirely about the sampling design.  Probability sampling gives you a well-defined sample (which might have missing data). Design-based inference is from that sample to the sampling frame it was drawn from.


NFL standings: 8-6-2 team vs 9-7-0 team?

Question: Are they considered to have the same records? One should just apply tie-breaking procedures?
NFL rules say:

If, at the end of the regular season, two or more clubs in the same division finish with identical won-lost-tied percentages

Not sure what the won-lost-tied percentage means. Above they mention that tie counts as half win, then why would you compute a "percentage" instead of simply ranking teams by their equivalent wins?
Bonus question: has this ever happened?
Answer: Won-Lost-Tied Percentages are applied as follows:

A win = 1.000
A loss = 0.000
A tie = 0.500

8-6-2: (8(1.000) + 6(0.000) + 2(0.500))/16 = (8 + 1)/16 = 9/16 = 0.563 (0.5625)
9-7-0: (9(1.000) + 7(0.000) + 0(0.500))/16 = 9/16 = 0.563 (0.5625)
*Divisor is the # of games played...in this case, we assume 16 games have been played.
Therefore, both teams W-L-T % is 0.563 and has the same record percentage.
The reason why a percentage is computed is because of the scenario above, equivalent wins (in the win column) doesn't equal equivalent record percentage (such as 9-6-1 and 9-7, 9-6-1 will have the better W-L-T %). In a extreme case, a team who is 0-0-16 has the same W-L-T % as a team who is 8-8-0 (or 7-7-2, 6-6-4, etc...).
Comment: A tie **isn't** a win. In terms of percentage, two ties for two games = .500 and one win for one game = 1.000. You compare two 16-game records...one has one less win and loss and two more ties. For all intents and purposes: 1-1-0 = 0-0-2 in terms of W-L-T %.
Comment: You say"A percentage is computed for the scenario above, equivalent wins doesn't equal equivalent records/percentage". What's the difference with saying the 8-6-2 team has 9 equivalent wins, just like the 9-7-0 team? Likewise, the 9-6-1 team has 9.5 wins clearly better than the 9-7-0 team. I just feel like the percentage is an unnecessary complication.
Comment: I feel the percentage removes any doubt...I would be more concerned with head-to-head, division, conference, and similar schedule records to determine standings.
Comment: The percentage can be particularly usefully mid season when not all teams have played the same number of games. While,  of course,  rankings mid season don't mean much, the information can still be interesting.
Comment: An interesting scenario took place with the AFC North recently. The Bengals were leading the division at 4-2-1. The Ravens and Steelers were second and third at 5-3, and the Browns were last at 4-3.
Comment: Another way to look at it - a tie is equivalent to half a win and half a loss.
Answer: To answer the bonus question, yes, two or more ties used to happen fairly often prior to 1974 because the rules did not allow an overtime to happen at all prior to that. In 1974, the old overtime rules where the first team to score in the 15 minute overtime wins began. During this period tie games were much more infrequent than before. The new overtime rules that began in 2012 appear to have made ties slightly more prevalent than before since the opposing team now has a chance to answer if the team playing offense scores a field goal on the opening overtime drive. This is generally considered to be a fairer system than the old rules by most, but fairness comes at the cost of more ties. One thing to consider though is that tie games did not count for anything in the NFL prior to 1972. Prior to that, if two teams tied, their winning percentage was calculated as if the game never even happened.
Bonus bonus answer: The 1936 Chicago Bears hold the record for most ties in one season having 6 of them, 3 of them coming in back to back to back consecutive games. The last time any team had two or more ties in one season was the 1973 season when the Browns, Chiefs, Packers, and Broncos all had two a piece.
Data on tied NFL games can be found at http://en.wikipedia.org/wiki/List_of_NFL_tied_games
Comment: The 1936 Bears did play in an era where the 0-0 tie was fairly common, of course...


Policy on duplicate answers

Question: What is the policy on duplicate answers?
I was a few examples of questions for which there are 2 answers that look remarkably similar (if not the same).
For example these (but there are others):
https://magento.stackexchange.com/a/10907/146
https://magento.stackexchange.com/a/19571/146
The answers were posted a few months apart so is not a case of who was faster by a few seconds.
Both the answers above practically say the same thing.
Are these answers allowed or should be flagged?
Answer: Well, ideally we get more than one answer per question (it's a key metric in the SE world), but in the case of a true duplicate there is no value added. These should be removed or converted to a comment (as I had already done with the example you posted).

Policy on duplicate answers


How do I convert a simple bit of MySQL to pdo

Question: I know nothing about MySQL let alone PDO and am struggling to convert something to PDO.
I have tried everything I can by copying code from other bits of the script but can't get anything to work and knowing absolutely nothing about MySQL let alone PDO does not help in fact MySQL seems a heck of a lot easier to say the least.
I want is this very simple bit of MySQL to work as PDO.
$query = " UPDATE " . $DBPrefix . "settings SET
logo = '" . $_FILES['logo']['name'] . "' ";
$system->check_mysql(mysql_query($query), $query, __LINE__, __FILE__);
$system->SETTINGS['logo'] = $_FILES['logo']['name'];

Answer: First you need to create new PDO() object. Something like this:
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
$pdo = new PDO($dsn, $user, $pass, $opt);

Next your code will transform to:
$sql = "UPDATE {$DBPrefix}settings SET logo = '{$_FILES['logo']['name']}'";
$result = $pdo->query($sql);

But this is not a good practice to just write SQL manually, wrapping and escaping all params. Better way using prepared statements, it'll wrap and escape all params automatically:
$ps = $pdo->prepare("UPDATE {$DBPrefix}settings SET logo = :logo");
$ps->execute(['logo' => $_FILES['logo']['name']]);

Answer: you should put . after db prefix:
$query = " UPDATE " . $DBPrefix . ".settings SET
logo = '" . $_FILES['logo']['name'] . "' ";
$system->check_mysql(mysql_query($query), $query, __LINE__, __FILE__);
$system->SETTINGS['logo'] = $_FILES['logo']['name'];

Comment: sorry I don't understand what you mean I am trying to convert that code to PDO
Comment: you didn't add dot after db prefix, " . $DBPrefix . ".settings, to be database.settings
Comment: It already works as it is flawless as a MySql i want it to be PDO not MySql


Find stationary points of $f(x,y) = (6 - x - y)x^2y^3$

Question: I am stuck in the middle. I need to find stationary points of function from title. I managed to differentiate and create system of equations but I have no idea how to proceed with this.
$f_x(x,y) = xy^3(12 - 3x - 2y)$
$f_y(x,y) = x^2y^2(18 -3x - 4y)$
Part below made me stuck:
$\Bigg\{\begin{array}{c}xy^3(12 - 3x - 2y) = 0\\x^2y^2(18 -3x - 4y) = 0\end{array}$
I am looking for your help.
Comment: Can you think of any easy answers?
Answer: Well, If $x=0$ or $y=0$, you have a solution, so every point on the coordinate axes is a stationary point of $f$. If $x\ne 0$ and $y \ne 0$ the only solution is found solving the linear system $12-3x-2y=0, \quad 18-3x-4y=0$. so, the solutions are

$(0,t), \quad t \in \mathbb{R}$
$(t,0), \quad t \in \mathbb{R}$
$(2,3)$
Comment: So in such situation when I have for instance $xy(x+1) = 0$, $x = 0 \lor y = 0 \lor (x+1) = 0$, if x or y equals 0, it makes whole expression equal 0 and only option I should suspect to be stationary points are cases when $x \ne 0$ and $y \ne 0$?
Comment: @KasataAta Not exactly... It would depend on the other equation. In the case you presented, taking the first equation, we get $x=0 \vee y=0 \vee 12-3x-2y=0$. As it turns out, if $x=0$ or $y=0$ the second equation also holds, we take note of those soluitons (1. and 2.) and  concentrate on the remaining part (the linear system).
Comment: So, correct me if I am wrong, but first two solutions are lines in coordinate system, and third solution is the result of solving system of x and y not equal 0?
Comment: @KasataAta Yes, solving the system for solutions with $x \ne 0$ and $y\ne 0$ is the same as solving the linear system and you end up with two straight lines (1. and 2.) and a point (3.).
Comment: Now I get it. Thanks. One more question. If I will proceed with this and try to calculate extremas, so I will need $f_(xx)$, $f_(xy)$, $f_(yx)$ and $f_(yy)$ and then I will prepare a hessian matrix, what should I do with these $(0, t)$ and $(t, 0)$?
Comment: For the points in the axes, the second order criteria (Hessian matrix) may reveal inconclusive. If you look at the signal of $f$ in the whole plane, you will immediately be able to classify those stationary points.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/98302/discussion-between-kasata-ata-and-pierrecarre).


Access windows 7 guest http port from linux host with virtualbox (using redmine and rails)

Question: I've just installed redmine on a Windows 7 Enterprise SP1 running on VirtualBox 5.2.12 r122571
I disabled windows firewall.
The host and the guest can ping each other.
I start redmine using webrick:
bundle exec rails server webrick -e production

From the guest I can access the app with localhost:3000 and with 127.0.0.1:3000, but not using the guest ip address
From the host I can ping the guest, but I cannot access it using <guest_ip_address>:3000
I tried with node's http_serve and it works ok, I can browse it from the guest and from the host using <guest_ip_address>:8080
Is there some ruby/rails/webrick configuration missing somewhere???
--
This is my configuration
Host machine: Linux antergos 4.16.8-1-ARCH #1 SMP PREEMPT Wed May 9 11:25:02 UTC 2018 x86_64 GNU/Linux
VirtualBox version: 5.2.12 r122571
Guest machine: Windows 7 Enterprise SP1
Network: bridged
Redmine version: 3.4.5.stable
Ruby version: 2.3.3-p222 (2016-11-21) [x64-mingw32]
Rails version: 4.2.8
Answer: One way I could find to solve it is to explicitly specify the ip address to bind to like this:
bundle exec rails server webrick -e production -b <guest_ip_address> -p 3000

That way I can access it using the ip of the guest, but I can no longer use localhost from the guest.
Still not sure if this is the best solution, I'd like to be able to use localhost and 127.0.0.1 from the guest and the guest's ip from the host.
Answer: A better solution is to drop webrick and use thin.
According to this guide you have to:
Edit <redmine_folder>/Gemfile file and add:
gem "thin"
Then run
$> bundle install

After that you can start it with
$>thin start -e production
Using rack adapter
Thin web server (v1.7.2 codename Bachmanity)
Maximum connections set to 1024
Listening on 0.0.0.0:3000, CTRL+C to stop
Especificación de unidad no válida.

And then I can start it from the guest with localhost:3000, 127.0.0.1:3000 or <guest_ip_address>:3000, and from the host with <guest_ip_address>:3000
Also, the application seems to be much more responsive than with Webrick


Minimum spanning tree edge count

Question: Given is a weighted complete graph where every weigth is a positive ineger. Let n be the amount of vertices.
I have to prove that the number of edges of a minimum spanning tree of that graph is equal to n-1.
Answer: A spanning tree of a connected graph $G$ by definition is a tree whose vertex set is all of $V(G)$. All trees $T$ satisfy the equation $E(T) = V(T) -1$. Let $V(G) =n$.
Therefore, if $T$ is spanning tree of $G$, $T$ has $E(T) = V(T) -1 = V(G) -1 = n-1$.

Minimum spanning tree edge count


How to measure memory usage of a Rack or Sinatra app?

Question: How do you measure memory usage of a Rack or Sinatra app?
I understand that probably depends a lot on how it is deployed.
But how do you get a basic idea of how much memory it uses?
Comment: can `top` or `htop` with process id would work
Answer: If you're using passenger, you could try passenger-memory-stats which gives you a nice overview split up by site, otherwise you can get some idea of memory usage by using top, shift-M and looking for the ruby processes.
Answer: Despite it's name, I've successfully used the derailed_benchmarks gem to dynamically benchmark memory usage in a Padrino (built on Sinatra) app. The docs describe how to do this for a non-Rails Rack app - you just need to define DERAILED_APP in a simple Rake task to tell it how to boot your app.
It can be run with a real server (I use Unicorn) on your localhost and potentially even with your production database (define DATABASE_URL). It can also be used to test any endpoint and bypass authentication, if necessary. Use cases include memory use over time (to find leaks) and profiling gems/required library memory at boot for a given endpoint (lots of memory use at boot).
As an example, the command bundle exec derailed exec perf:mem gives the output below for my app's root at boot (here hiding < 3 MiB usage). Around 70 MiB tallies with what Heroku's stats are telling me on my production server. My app is called 'padfoot' btw.
TOP: 71.75 MiB
  mechanize: 19.0898 MiB (Also required by: /Users/me/dev/padfoot/lib/parsers/transaction_table_parser.rb, /Users/me/dev/padfoot/lib/scrapers/app_details_scraper.rb, and 4 others)
    mechanize/pluggable_parsers: 11.1055 MiB
      mime/types: 10.9766 MiB (Also required by: /Users/me/.rvm/gems/ruby-2.3.1/gems/rest-client-1.8.0/lib/restclient/request, /Users/me/.rvm/gems/ruby-2.3.1/gems/rest-client-1.8.0/lib/restclient/payload)
  padrino: 13.1016 MiB
    padrino-core: 8.0273 MiB (Also required by: padrino-cache, padrino-admin)
      padrino-core/application: 3.3555 MiB
      sinatra/base: 3.1406 MiB (Also required by: padrino-core/ext/sinatra, sinatra/main)
    padrino-helpers: 3.707 MiB (Also required by: padrino-cache, padrino-admin)
      padrino/rendering: 3.3203 MiB (Also required by: /Users/me/dev/padfoot/app/app.rb)
  /Users/me/dev/padfoot/config/apps.rb: 6.9805 MiB
    /Users/me/dev/padfoot/app/app.rb: 6.8906 MiB
  aws-sdk-core/s3: 6.3711 MiB
  /Users/me/dev/padfoot/lib/scrapers/gps/gps_scraper.rb: 4.25 MiB
    linguistics/en: 4.1523 MiB
  /Users/me/dev/padfoot/lib/scrapers/digimap/digimap_scraper.rb: 3.0547 MiB


Adding a "my messages (x)" link in the block template file

Question: I have installed Privatemsg, and I need to output the "My messages (x)" link programmatically in block.tpl.php.
I tried the following code, but it only prints "My Messages", when I need a counter for the new messages:
print l('My messages', 'messages');

Answer: The module already contains a block that does something similar: "New message indication". You can use that block and alter the output if needed by overriding the theme_privatemsg_new_block() function.
Answer: You can use the function privatemsg_title_callback() like this:
print l(privatemsg_title_callback(), 'messages');

And as marcvangend mentioned, Privatemsg already provides a block that informs the user if he has new messages and a block that contains exactly such a link and additionally a link to write a new private message. Why not use one of these instead?
Comment: I've created individual block for users, to edit their profiles, content etc. I mean, i manually added such links:

So i needed to manually create a link to "my messages (x)"


Give an example of two languages that are not recognisable such that their union is recognisable?

Question: I have this question:
Give an example of two languages that are not recognisable such that
their union is recognisable. Justify your answer (you are allowed to use
any properties of the class Rec $A^∗$ of recognisable languages over an
alphabet $A$).
i.e. $A \notin Rec A^*$ and $B \notin Rec A^*$ but $A \cup B \in Rec A^*$
Not quite sure how to answer it. I know I should provide my workings so far, but as it's simply "state an example", and I don't know an example, I find it hard to provide any workings...
Although I imagine it is something simple, like $A = {\phi}$ and $B = \{a\}$ or something?
Thanks for any help.
Comment: My guess is that for any unrecognizable language, its complement is also not recognizable?
Comment: @Penguin47 That sounds very much like what I (from only learning about this stuff here on SE and on Wikipedia) would call a [regular language](https://en.wikipedia.org/wiki/Regular_language#Equivalent_formalisms). Does that seem right?
Comment: Yes, I believe they are all equivalent. Regular language = Rat $A^*$ = Rec $A^*$.
Comment: What's the union of a language and its complement?
Comment: This might just be because I'm unfamiliar with the terminology, but what exactly does "recognizable" mean?
Comment: Yes, I think I noticed that recognisable is notated differently in different textbooks as I read other papers on the subject. Our module definition is "A recognisable language is a subset $L$ of $A^*$ such that $L=L(Z)$ for some DFA $Z$".
Comment: @rici It equals $\phi^c$. How would we know this is recognisable, when $A$ and $A^c$ are not? Thanks. Can we simply state it is rational, therefore recognisable?
Comment: What is $\phi$ here? And is $A$ both an alphabet and a language? What does "'rational" mean in this context?
Comment: $\phi$ is the empty set. A is a language, not necessarily the alphabet (though maybe it has to be). Rational means the same thing as regular in this context.
Answer: I found a great example elsewhere on this website HERE, but it took me a while to find it as it used different language to how I have studied it.
Let there be two languages, neither recognisable:
$$L_1 = [a^i b^j : j \leq i]$$ and $$L_2 = [a^i b^j : i < j]$$
Their union is:
$$L_1 \cup L_2 = [a^* b^*]$$ This is rational, therefore recognisable (by Kleene's Theorem).


Multiply the number $(1001)_{2}$ by 3 digit number

Question: I want to multiply the number $(9)_{10} \rightarrow (1001)_{2}$ by a 3 digit binary number.
1) How I can extract the boolean equations?

2) Make a circuit of it.

so what I did is just see what happen if I multiply it, for example:
$$(1001)_{2}* (A_{1}B_{1}C_{1})_{2}$$
$$A_{1}*1 A_{1}*0 A_{1}*0 A_{1}*0$$
$$B_{1}*1 B_{1}*0 B_{1}*0 B_{1}*0$$
$$C_{1}*1 C_{1}*0 C_{1}*0 C_{1}*0$$
after I do that I need to sum them. so what I choose to user Ripple Carry Adder for that:

I would like to get some comments if its ok or I need to do it in another way.
thanks!
Comment: If the goal is to make a circuit that multiplies a three-digit binary number with $9=1001_2$, instead of multiplying it with arbitrary 4-digit numbers, the minimal circuit doesn't even need gates.
Comment: yes I got that, so using a ripple carry adder its ok?
Comment: I admit that I don't know what a ripple carry adder is.
Comment: Ripple Carry Adder : http://www.circuitstoday.com/ripple-carry-adder
Comment: OK, so it seems to just be a specific implementation of an adder. If so, and if I understand your circuit correctly, then no. As far as I can see, you *add* $9$ to your number, multiply by $2$, and add $F0$ (whatever that is). But neither $9a=2(a+9)$, nor $9a=2(a+9)+1$ for all $a\in\{0,…,7\}$.
Comment: so what I need to change? not to add $F0$?
Comment: I have no idea what $F0$ actually is, in your problem description it doesn't occur. BTW, I now don't have the time to continue until in about 12 hours.
Answer: You definitely have to do it differently.
Let's consider an example: $7_{10}\cdot 9_{10} = 111_2\cdot 1001_2$. The result is of course $63_{10}=111111_2$. Now what would your circuit give?
Well, you feed the $7=111_2$ and the $9=1001_2$ into an adder, which calculates $7+9=16=10000_2$ Then you append another bit, which you get from an input "F0" which you nowhere specify. However, it can only be either $0$ or $1$, so the final result from your circuit is either $100000_2$ or $100001_2$. Neither of which equals $111111_2$.
To find out what to do differently, think about the following question:
For the binary number $x=abc_2$ (where $a$, $b$ and $c$ are binary digits), what is the binary representation of $9_{10}\cdot x$? Try a few concrete examples (there are only eight of them, so you can even try all of them; however I'm sure you'll see the pattern before you've done so).
Also, for enlightenment, multiply a three-digit decimal number with $1001_{10}$.


spawn strace command with Node.js child_process

Question: Since I'm not happy with this approach and I got no answers, I'm trying another method to track the output of an already running program. I based this code on this Unix Stack Exchange and what I'm trying to do is just retrieve the log information of a program that is already running.
Obs: to use strace without sudo you need to allow it with the following command:
echo kernel.yama.ptrace_scope = 0 > /etc/sysctl.d/10-ptrace.conf

And probably it will work only after reboot.
This is my code using strace linux command and node child_process, where -p1234 is the number of the process we want to track.
  import { spawn } from 'child_process';
  const strace = spawn('strace', [ `-p1234`, '-s9999', '-e', 'write']);

  strace.stdout.on('data', (data) => {
    // I don't know why, but my output is not being returned here
    console.log(`stdout: ${data}`);
  });

  strace.stderr.on('data', (data: any) => {
    // 'data' output is something like: 'write(4, "my real log", 4)                = 4\n',
    // so we need to cleanup a little bit with regex.
    const prefix = /^\write\(1, "/
    const suffix = /", [0-9]\)?\s*=?\s?[0-9]?/
    const raw = `${data}`.trim()

    if (raw.match(prefix) && raw.match(suffix)) {
      // cleaning msg
      let log = raw.replace(prefix, '').trim().replace(suffix, '').trim();
      if (!log.includes('\n')) {
        // showing msg: "my real log"
        console.log(log);
      }
    }
  });

First of all: I don't why my log is being outputed on stderr and not on stdout, but ok, I follow coding anyway.
Second: It works pretty fine if the program I'm running is outputing logs slowly, like one print at a time.
But when I have a sequence of 2, 3 or 4 prints it's not working. I guess I,m taking too much time to cleanup the message, so when the other strace.stderr.on() comes, I'm in the middle of the process and some issues happen. In this case, I'm able to see only the first print of the sequence.
I need to clean a lot of info because the message is outputed as something like:
'write(4, "9883", 4)                     = 4\n'

Which is a mess. I think maybe a command that print only content of message would fix my problem too.
Any idea on how can I obtain a more consistent output of those messages? As I said, my only purpose is to retrieve the messages that are being output by another program that is already running. I also tried to follow the "log on file and read the file" approach, but as I said, I had some other issues
Any advice, improvement, or totally different approach to achieve this goal will be very much appreciated!
Comment: I'm not sure this will fix the issue, but I could recommend using RxJS with `fromEvent`: https://www.learnrxjs.io/learn-rxjs/operators/creation/fromevent
Comment: @Cehhiro, can you explain better how this is going to help me? Thanks!
Answer: First, my reading of the strace(1) man page suggests that stderr is the default for that command (look for --output in that page).
The output that you're getting from strace in the data event is not guaranteed to be split on newline boundaries.  When you're getting slow output, it will just happen to work correctly.  Faster output will clump multiple lines together and may split lines at non-newline boundaries.  For a quick fix, pipe stderr to an instance of readline:
const rl = require('readline').createInterface({input: strace.stderr})

Once you have that done, if you need further help parsing the output, you can use a better regular expression to parse the whole line at once:
rl.on('line', line => {
  const re = /^write\((?<fd>\d+),\s*"(?<data>(?:[^"]|\\")*)",\s*(?<len>\d+)\)\s*=\s*(?<written>\d+)/
  const m = line.match(re)
  if (m) {
    console.log(m.groups.data)
  }
})

That uses the new named capture groups, so if you're using a very old version of node, remove the portions that look like ?<fd> and instead of m.groups.data use m[2].
This also assumes that a double-quote in the strace output gets output as \", but I don't know if that's actually the case.
Comment: Change the regex to `/^write\(1,\s*"(?(?:[^"]|\\")*)",\s*(?\d+)\)\s*=\s*(?\d+)/`, so you're replacing `(?\d+)` with `1`, to match the one literal character.  `\d` means "any digit, 0-9".
Comment: OMG! I was stucked on this problem a lot of time and this `readline()` trick did the job. Thanks a lot for a so well explained answer! I'm not a pro on regex and this certainly fits better too
Comment: If I want to accept only `write(1` at the beggining, and not all numbers, what change should I make?


Proof of asymptotic normality of Maximum Likelihood Estimator (MLE)

Question: I am a self-learner trying to understand the proof of asymptotic normality of Maximum Likelihood Estimator (MLE) from the notes at http://www.konstantinkashin.com/notes/stat/Maximum_Likelihood_Estimation.pdf (pp. 25).
I am having certaing difficulties understanding how this converges in distribution to normal distribution
$\sqrt{n}(\hat\theta_{MLE}-\theta_o)=-\frac{\sqrt{n}l'(\theta_o)}{l''(\tilde \theta)}\xrightarrow{d}N(0, \frac{nI_n(\theta_o)}{(-I_n(\theta_o))^2})=N(0,\frac{n}{In(\theta_o)})$
if it was stated that nominator converges to normal distribution and denominator converges in probability to Fisher information.
I would be thankful for a simple as possible (mathematical) explanation.
Answer: In order to combine the two results
\begin{align}
\sqrt{n} \ell'(\theta) &\overset{d}{\to} N(0, n I_n(\theta))
\\
\ell''_n(\tilde{\theta}) &\overset{a.s.}{\to} -I_n(\theta_0)
\end{align}
to arrive at your claim, you just need to apply Slutsky's theorem, which appears in the appendix of your linked notes.
Comment: In addition, for a single observation, how it is possible that the mean of the score is distributed as a normal with variance $\frac{I_1(\theta)}{n}$ (pp. 24, second expression from the bottom)? Shouldn't $n$ be equal to 1 then?


CryptoJS and PHP SHA256

Question: I would like to get Both CryptoJS's SHA256  and php's Crypt SHA256 output to match.
PHP crypt has a salt and a number of rounds. E.g. for 5000 rounds and salt of "usesomesillystringforsalt" it would be;

$hash = crypt('Clear Text String', '$5$rounds=5000$usesomesillystringforsalt$');

I hope im not blind, but i cant find how to reproduce this behaviour in crypto-js. Its syntax doesn't seem to allow for rounds or salt.
Is it possible or should i just resort to using the basic PHP hash instead of crypt?
Answer: The CryptoJS API doesn't provide a way to specify a salt or the number of rounds for SHA256. You could add a salt manually if necessary, and specifying rounds doesn't make sense since "plain" SHA256 always uses a fixed number of rounds (64).
The number of rounds in PHP's crypt() actually defines how often the SHA256 algorithm is applied consecutively, in order to increase the complexity of brute force attacks. The PHP source code comments on this as follows: "Repeatedly run the collected hash value through SHA256 to burn CPU cycles".
As you can see in the source code (here and here), crypt() is actually a key derivation function that only makes use of SHA256 to generate cryptographically secure, salted hashes. So it also doesn't simply append the given salt to the key, instead it's a more elaborate process.
Therefore, it is not possible to get the same results with the algorithms provided by CryptoJS.
crypt() is mainly intended for password hashing. So if you need the hashes for another purpose, hash() is a good alternative (and of course creates exactly the same results as CryptoJS.SHA256()).
However, bear in mind that any cryptography with JavaScript is generally considered harmful. Hence, you should better use SSL in your application, if possible, and generate the hashes server side. If this is an option, have a look at bcrypt.
Comment: Perfect Answer, Thank you for the considered and detailed response.

CryptoJS and PHP SHA256


ListView exibe apenas uma linha, por que?

Question: Tenho um ListView em um layout com mais itens, e ele só exibe uma linha. Se eu fizer o mesmo esquema em um código que o layout tenha apenas o ListView ele funciona perfeitamente, se alguem tiver idéia do por que agradeço.
Aqui é o meu xml
<?xml version="1.0" encoding="utf-8"?>

    <ScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="#fff">

        <LinearLayout
            android:padding="5dp"
            android:background="#E3F2FD"
            android:elevation="2dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="3dp"
            android:layout_marginRight="3dp"
            android:orientation="vertical">

            <ImageView
                android:layout_marginTop="3dp"
                android:layout_gravity="center_horizontal"
                android:src="@mipmap/piscina"
                android:layout_width="match_parent"
                android:layout_height="150dp" />

            <TextView
                android:layout_marginTop="5dp"
                android:layout_gravity="center"
                android:textSize="15sp"
                android:text="Nome do cliente"
                android:id="@+id/visual_nome"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <TextView
                android:layout_gravity="center"
                android:textSize="15sp"
                android:layout_marginTop="5dp"
                android:text="email@example.com"
                android:id="@+id/visual_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

                <TextView
                    android:layout_gravity="center"
                    android:textSize="15sp"
                    android:layout_marginTop="5dp"
                    android:text="(47)33823449"
                    android:id="@+id/visual_telefone"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:layout_gravity="center"
                    android:textSize="15sp"
                    android:layout_marginTop="5dp"
                    android:text="(47)88565576"
                    android:id="@+id/visual_celular"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:layout_gravity="center"
                    android:textSize="15sp"
                    android:layout_marginTop="5dp"
                    android:text="Rua tatata 178"
                    android:id="@+id/visual_rua"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:layout_gravity="center"
                    android:textSize="15sp"
                    android:layout_marginTop="5dp"
                    android:text="Centro"
                    android:id="@+id/visual_bairro"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:layout_gravity="center"
                    android:textSize="15sp"
                    android:layout_margin="5dp"
                    android:text="Terça e Sexta"
                    android:id="@+id/visual_dia"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

        </LinearLayout>

        <LinearLayout
            android:background="#2196F3"
            android:layout_marginTop="1dp"
            android:layout_marginRight="3dp"
            android:layout_marginLeft="3dp"
            android:elevation="6dp"
            android:padding="1dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:textColor="#fff"
                android:padding="3dp"
                android:textSize="18sp"
                android:layout_gravity="center"
                android:text="Produtos do Mês"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>

            <ScrollView
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                >

            <ListView
                android:verticalScrollbarPosition="right"
                android:id="@+id/lista_produtos"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
            </ListView>
            </ScrollView>

    </LinearLayout>

</ScrollView>

Aqui o código do meu adapter
public class VisualClienteAdapter extends BaseAdapter {

    private ClientesDAO pDao;

    private TextView valor;
    private TextView qtd;
    private TextView nome;

    private LinkedList<Produto> data = new LinkedList<Produto>();
    private Context context;

    public VisualClienteAdapter(Context context){
        this.context = context;

        data.add(new Produto(R.mipmap.ic_launcher,"Algicida de Choque","20,00",1));
        data.add(new Produto(R.mipmap.ic_launcher,"Cloro Granulado 10Kg","220,00",1));
        data.add(new Produto(R.mipmap.ic_launcher,"Barrilha Leve 2Kg","20,00",1));
        data.add(new Produto(R.mipmap.ic_launcher,"PH Estavel 1,5Kg","20,00",1));
        data.add(new Produto(R.mipmap.ic_launcher,"Clarificante","20,00",1));
        data.add(new Produto(R.mipmap.ic_launcher,"Reagente Cloro","7,50",1));
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Produto getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View view = LayoutInflater.from(context).inflate(R.layout.item_produtos,null,false);

        ImageView image = (ImageView) view.findViewById(R.id.imagemLista);
        TextView nome = (TextView) view.findViewById(R.id.id_produto_nome);
        TextView qtd = (TextView) view.findViewById(R.id.id_qtd);
        TextView valor = (TextView) view.findViewById(R.id.produto_valor);

        Produto p = getItem(position);

        image.setImageResource(p.getId());
        nome.setText(p.getNome());
        qtd.setText(String.valueOf(p.getQdt()));
        valor.setText(p.getValor());

        return view;
    }
}

Aqui a minha Activity.class referente ao .xml
package br.com.piscinas.piscinas;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import br.com.piscinas.piscinas.adapter.VisualClienteAdapter;
import br.com.piscinas.piscinas.dao.ClientesDAO;

    public class VisualizarCliente extends AppCompatActivity implements view.OnClickListener{

    private TextView nome;
    private TextView email;
    private TextView rua;
    private TextView tel;
    private TextView cel;
    private TextView bairro;
    private TextView diaSemana;
    private ClientesDAO hp;
    private VisualClienteAdapter adapter;
    private ListView list;

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

        adapter = new VisualClienteAdapter(this);
        list = (ListView) findViewById(R.id.lista_produtos);
        list.setAdapter(adapter);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setElevation(6f);
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#2196F3")));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (item.getItemId() == android.R.id.home) {

            finish();
            return true;

        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {

        }
}

Aqui os itens que são "inflados" em cada linha da lista
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="20dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:background="#fff">

    <ImageView
        android:id="@+id/imagemLista"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:minWidth="30dp"
        android:id="@+id/id_produto_nome"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_marginLeft="10dp"
        android:text="R$: "
        android:id="@+id/id_valor_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView

        android:id="@+id/produto_valor"
        android:minWidth="30dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/id_qtd_text"
        android:layout_marginLeft="10dp"
        android:text="Qtd: "
        android:minWidth="30dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView

        android:id="@+id/id_qtd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Comment: Quando você diz que exibe só uma linha quer dizer que a lista só tem um item ou quer dizer que só tem a altura de um item?
Comment: Posta o XML dos itens da lista por favor
Comment: Este é o .xml dos itens que são inflados no campo individual da lista
Comment: A única coisa que eu vejo mal é a forma como é feita o *inflate* da *view* no método `getView()` troque a linha `View view = LayoutInflater.from(context).inflate(R.layout.item_produtos,null,false);` por `View view = LayoutInflater.from(context).inflate(R.layout.item_produtos,parent,false);`. Em vez de `null`passe `parent` ao método `inflate()`
Comment: ok vou fazer a alteração
Comment: Nada amigo continua na mesma. Já tentei um método diferente, busquei os itens na lista do meu banco de dados ordenei asc e desc e ele exibiu a primeira e a ultima informação em cada caso, sou iniciante realmente nao tenho a minima ideia do que fazer ,pesquisei mas  ninguem postou nada parecido até agora , pelo menos não que eu tenha visto.
Comment: Não é só uma linha mesmo, coloquei um ScrollView ,não sei se isso serve como teste para esse caso mas mesmo com ele funcionando continuou exibindo apenas uma linha(um item)
Comment: Fiquei sem perceber se a lista tem todos os itens ou não. Se tem todos os itens mas a altura dela é de uma só linha, uma possível causa seria mesmo o facto de estar a usar a *ListView* dentro de um *ScrollView*.
Comment: Outra coisa que noto é que ou não postou por completo os seus xml ou falta incluí-los dentro de algum tipo de Layout(LinearLayout, RelativeLayout, etc)
Comment: Sim notei que na hora da postagem eles sumiram, mas em fim, é o que você falou, removi o ScrollView e a lista foi exibida. Só que então como devo fazer para poder visualizar a lista completa, ela fica no fim do meu layout preciso do ScrollView, mas com ele fica apenas uma linha, como devo fazer?
Comment: Executei o app sem o scrollview, ele adiciona um scrollview automaticamente no layout que está minha lista, só que como ela fica proximo ao limite da tela fica muito pequeno para o usuario poder manusear, tens idéia do que devo fazer?
Comment: Agrupe a informação por contexto e apresente cada grupo em, por exemplo, *tabs*.
Comment: Bom, ai já está alem dos meus conhecimentos, vou começar a pesquisar. Obrigado pela ajuda.
Comment: Estou meio perdido quanto ao que procurar, poderia me indicar algum tópico?
Comment: @CesarRobertoMartins, o ramaral se refere a estas tabs http://pt.stackoverflow.com/a/76497/10315
Comment: Passei pelo seu mesmo problema. Quando procurei no google em ingles pela resposta eis:
Mude no layout do item `android:layout_height="match_parent"` para `wrap_content` https://stackoverflow.com/questions/36819329/recyclerview-shows-just-a-single-row-in-android/36819884#36819884
Answer: É porque você está usando um listview dentro de um scrollview. O listview já possui um scrollview internamente, então na prática tem um monte de scroll dentro do outro. Recomendo refazer o layout, mas se realmente precisar manter assim, existe um workaround pra recalcular o tamanho da lista.
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

public class Helper {
    public static void getListViewSize(ListView myListView) {
        ListAdapter myListAdapter = myListView.getAdapter();
        if (myListAdapter == null) {
            //do nothing return null
            return;
        }
        //set listAdapter in loop for getting final size
        int totalHeight = 0;
        for (int size = 0; size < myListAdapter.getCount(); size++) {
            View listItem = myListAdapter.getView(size, null, myListView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
      //setting listview item in adapter
        ViewGroup.LayoutParams params = myListView.getLayoutParams();
        params.height = totalHeight + (myListView.getDividerHeight() * (myListAdapter.getCount() - 1));
        myListView.setLayoutParams(params);
        // print height of adapter on log
        Log.i("height of listItem:", String.valueOf(totalHeight));
    }
}

Fonte


My public IP address keeps changing. How can I connect to AWS EC2?

Question: My public IP address changes every 24 hours which is normal, but my question is: how can I make it static or what setting do I need to change so I don't have to re-allow and recreate a new security group for my new public IP address in AWS EC2?
Comment: @MichaelHampton dynamic IP addresses is *very* normal and the very reason many dynamic DNS services have been very successful over the years.  Im not sure why you think this is abnormal - a static IP address is very much the exception and has been for a long time, in-fact its often an up-sell item or reserved for business connections.
Comment: Changing IP addresses every day is not common at all, except in a few countries where it's misapprehended as a "privacy" measure, and elsewhere in a few broken ISPs. That said, if you're stuck with this and can't get the ISP to stop doing it, you can't really restrict anything to a single IP address in the security group.
Comment: What @MichaelHampton was saying is that the _rate_ of reallocation is normally much lower than 24 hours. My ISP typically changes my IP once a year, if even that.
Comment: @MichaelHampton i beg to differ, for a lot of ISPs that is perfectly normal - Ive seen it a lot in the UK and here in NZ for example during my years on the internet.
Comment: @Moo I said, quote: "Changing IP addresses every day" is not normal, not that dynamic IP assignment is not normal.
Comment: There is a scale, on one end is security, the other, ease of development. It's always the case and especially so with cloud computing. You should try calling your ISP, they're usually quite happy to at least reduce the rate at which your IP gets reallocated. Just say you have to work from home and it interferes with your companies security.
Comment: In the UK ISPs can normally switch you over to a static IP address for an additional monthly charge (of around £5 typically), but having a fixed IP address is less secure.  I need a fixed IP address for a lot of client sites, so we use a VPN service that provides a fixed IP address that's assigned exclusively to us.
Answer: A dynamic IP address is fairly common in many countries. So is carrier grade NAT, which means many people share the same IP address.
You don't need to create a new security group; you just need to add your new IP address to the existing security group and ideally need to remove all others from the security group. There are scripts you can find online that automate this for you, such as this one. You could extend it to remove old IP addresses using the AWS CLI / SDK. An EC2 instance can have five security groups, I tend to have one dedicated to home IP on various ports, one for my CDN's IPs, and then a "misc" SG for other things. This is useful as SGs have a limit of around 50 rules per group, and keeping things together makes them easier to organise.
Alternately, if your IP addresses are all in a given CIDR range or set of ranges, you could add those to your security group.
Another option is to remove the IP address restriction, which decreases security somewhat, but if you keep your private key private maybe that's good enough. That would open you up to brute force login attempts, and if any vulnerabilities are found in SSH or SSH is poorly configured that could let people into your server, so I wouldn't recommend it but it is an option.
Answer: You can sidestep the open IP address issue by using AWS Systems Manager Session Manager.
It logs you in to your EC2 instances through the AWS CLI. How AWS routes your connection internally is a bit of a black box, but it does permit you to keep those ports closed to the public Internet.
To use things like scp or rsync, you can enable ssh connections through the AWS CLI following this documentation.
Answer: I'd avoid using another commercial service for a VPN, and instead either

Run a VPN server like OpenVPN on your own EC2 instance in your VPC, or

Since you're already paying for AWS services, use the AWS Client VPN  https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/what-is.html

Both will let you connect to your remote host securely, with certificates rather than passwords, and you can leave your security group allowing unrestricted access in on port 1194/udp.
Optionally you could lookup all the IPs owned by your ISP and add the entire blocks to your inbound security group.

Another option is to upgrade your residential grade ISP connection to one with static IPv4 addressing, at some cost, if they offer it, or change to an ISP that does.

Finally, consider IPv6 connectivity.  This is relatively simple at the AWS side, but again depends on your ISP supporting it.... not all do.
Answer: Some commercial VPNs will offer a solution that gives your traffic a consistent network egress. I've used that solution commercially, especially as many workers previously connecting through the corporate network infrastructure transitioned to work from home arrangements but still needed access to the same cloud resources.
This is likely overkill for anything on the scale of a personal project.
Answer: 2Xs a month AWS changes my IP Address - Now the client wants AWS to pay for the outage of 20 people 40 mins a month!
What is going on AWS???
Comment: If you have a new question, please ask it by clicking the [Ask Question](https://serverfault.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/518726)
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: Good Day I might have another option for you
Feel free to use my powershell script for this .
The script detects your public ip and adds it to the inbound security group rules of dedicated RDP and SSH security groups .
If these groups do not exist , the script will create them and add it to the appropriate instances .
https://github.com/manuelh2410/public/blob/1/AWSIP_Linux_Win.ps1
Share
Answer: Feel free to use my powershell script for this .
The script detects your public ip and adds it to the inbound security group rules of dedicated RDP and SSH security groups .
If these groups do not exist , the script will create them and add it to the appropriate instances .
https://github.com/manuelh2410/public/blob/1/AWSIP_Linux_Win.ps1
Share


Find an expression for $A^n = \left( \begin{array}{cc} 1 & 4 \\ 2 & 3 \end{array} \right)^n$

Question: We want to find an expression for $A^n = \left( \begin{array}{cc} 1 & 4 \\ 2 & 3 \end{array} \right)^n$ for an arbitrary "n".
I have tried writing out a few elements of the sequence as $n \to \infty$:

$A^2 =  \left( \begin{array}{cc} 9 & 16 \\ 8 & 17 \end{array} \right)$
$A^3 = \left( \begin{array}{cc} 41 & 84 \\ 36 & 51 \end{array} \right)$

However, a pattern doesn't seem to appear.
This is where I want to ask my question: if we put this matrix into reduced-row echelon form, would an expression of the $(reduced matrix)^n$ work as an expression for the original matrix $A$?
i.e. reduced-row matrix $ = \left( \begin{array}{cc} 1 & 0 \\ 0 & 1 \end{array} \right)^n$. Then, we know that any diagonal matrix to the $n^{th}$ is just the diagonal entries to the $n^{th}$ and this would make an expression easy to come up with.
Thank you!
Comment: try an eigen-decomposition
Comment: having distinct eigenvalues is actually a stronger condition than non-defectivity.  A matrix is non-defective if for each eigenvalue its algebraic multiplicity is equal to its geometric multiplicity.  Or conversely, a matrix is defective if it has an eigenvalue whose geometric multiplicity is less than its algebraic multiplicity, which means its eigenvectors don't form a basis for the vector space.
Comment: as long as the matrix is non-defective (distinct eigenvalues is enough), then the eigenvalues of $A^n$ are just the eigenvalues of $A$ all raised to the $nth$ power.  Raising the eigen-decomposition to the $nth$ power and simplifying shows you why.
Comment: How did you know this would be useful? Just curious how you were able to come up with this answer just by looking at the problem!
Comment: Non-defective? What other conditions must a matrix satisfy (other than having distinct eigenvalues) to be non-defective? Thank you for your insight thus far!
Comment: you're welcome!
Comment: The values in $A^{3}$ are incorrect.
Answer: In problems such as these one of the most efficient ways to calculate powers of a matrix is through diference equations. For the matrix of this problem the following is obtained.
Given
\begin{align}
A = \left( \begin{array}{cc} 1 & 4 \\ 2 & 3 \end{array} \right)
\end{align}
it is found that
\begin{align}
A^{2} = \left( \begin{array}{cc} 9 & 16 \\ 8 & 17 \end{array} \right)
\hspace{10mm}
A^{3} = \left( \begin{array}{cc} 41 & 84 \\ 42 & 83 \end{array} \right).
\end{align}
The problem asks for the values of $A^{n}$. This is done by letting
\begin{align}
A^{n} = \left( \begin{array}{cc} a_{n} & b_{n} \\ c_{n} & d_{n} \end{array}
\right).
\end{align}
With this and $A^{n} = A \cdot A^{n-1}$ then
\begin{align}
\left( \begin{array}{cc} a_{n} & b_{n} \\ c_{n} & d_{n} \end{array} \right)
= \left( \begin{array}{cc} 1 & 4 \\ 2 & 3 \end{array} \right)
\left( \begin{array}{cc} a_{n-1} & b_{n-1} \\ c_{n-1} & d_{n-1} \end{array} \right).
\end{align}
From this equation it is quickly determined that
\begin{align}
a_{n} &= a_{n-1} + 4 c_{n-1} \hspace{12mm} b_{n} = b_{n-1} + 4 d_{n-1} \\
c_{n} &= 2 a_{n-1} + 3 c_{n-1} \hspace{10mm} d_{n} = 2 b_{n-1} + 3 d_{n-1}.
\end{align}
These equations are reducible to the second order difference equation, $\phi_{n} \in \{ a_{n} , b_{n}, c_{n}, d_{n} \}$,
\begin{align}
\phi_{n+2} = 4 \phi_{n-1} + 5 \phi_{n}
\end{align}
which has the solution
\begin{align}
\phi_{n} = A \, 5^{n} + B \, (-1)^{n}.
\end{align}
Now returnig to the first few powers of $A$ the conditions
\begin{align}
a_{1} &= 1, a_{2} = 9, a_{3} = 41 \\
b_{1} &= 4, b_{2} = 16, b_{3} = 84 \\
c_{1} &= 2, c_{2} = 8, c_{3} = 42 \\
d_{1} &= 3, d_{2} = 17, d_{3} = 83
\end{align}
are obtained. The second order difference equation equation can be solved for each of the condition sets and is determined that
\begin{align}
a_{n} &= \frac{1}{3} \left( 5^{n} + 2 (-1)^{n} \right) \hspace{10mm}
b_{n} = \frac{2}{3} \left( 5^{n} - (-1)^{n} \right) \\
c_{n} &= \frac{1}{3} \left( 5^{n} - (-1)^{n} \right) \hspace{12mm}
d_{n} = \frac{1}{3} \left( 2 \cdot 5^{n} + (-1)^{n} \right).
\end{align}
Putting this together the $n^{th}$-power of $A$ is given by
\begin{align}
A^{n} = \frac{1}{3} \left( \begin{array}{cc} 5^{n} + 2 (-1)^{n} & 2(5^{n} - (-1)^{n}) \\ 5^{n} - (-1)^{n} & 2 \cdot 5^{n} + (-1)^{n} \end{array}
\right).
\end{align}
Comment: In my opinion, you are actually better off in the matrix setting than you are in the difference equation setting; that is, given a hard difference equation, I would inevitably convert it into a matrix iteration, and would almost never convert a matrix iteration to a difference equation. But this is opinion; as you have shown, the two approaches are equivalent.
Comment: Very nice approach! +1.
Comment: you are reinventing cayley-hamilton theorem!
Answer: Performing row operations is the same as left-multiplication by elementary matrices: http://en.wikipedia.org/wiki/Elementary_matrix
Here is your question in these terms:
If $E_1,\cdots,E_n$ is are elementary matrices, can we find a useful relation between $(E_1\cdots E_n A)^n$ and $A^n$? It doesn't look like a good strategy!
However if you manage to diagonalize $A$ by solving its eigenvalue problem, then you will have a matrix $S$ with $SAS^{-1}$ diagonal. The easy relation $(SAS^{-1})^n=SA^nS^{-1}$ should then help you out.
Answer: Hint:
The matrix $\displaystyle A = \begin{pmatrix}
1 & 4 \\
2 & 3 \end{pmatrix}$ is diagonalizable.  That is, it can be written in the form $A = QDQ^{-1}$, where $D$ is a diagonal matrix and $Q$ is invertible.  This is useful since $A^n = (QDQ^{-1})^n = QD^nQ^{-1}$, and it is very easy to compute powers of diagonal matrices.
Click here for a reference on performing diagonalization.
Comment: Glad I could help!
Answer: you can also find $A^n$ using cayley-hamilton theorem which says that a matrix satisfies its own characteristic equation. the characteristic polynomial of $A$ is $$det (A-xI) = (x-5)(x+1).$$
by polynomial division algorithm, we can find constants $a$ and $b$ so that $$x^n = q(x)(x-5)(x+1) + ax + b \to a = \frac16\left(5^n - (-1)^n\right), b = \frac16\left(5^n + 5(-1)^n \right) $$
by cayley-hamilton, $$A^n = aA + bI. $$
Comment: What's $q(x)$? You also have several typos.
Comment: @Ian, $q(x)$ is the quotient polynomial produced by the polynomial division algorithm.
Comment: ......+1 Because used simple method...
Comment: @k1.M, thank you. there is no need to find eigenvectors. there is another method called putzers method that too works without ever finding the eigenvectors.
Comment: This method is very helpful, because working with this is better and simpler than diagonalizing...
Answer: Hint.  Try use  the Jordan form of $A.$


Given quintic polynomial $f$ - If ${\rm Gal}(f)$ has an element of order 3 then it is not solvable

Question:
Let $f(x) \in \mathbb Q[x]$  be a quintic irreducible polynomial, $E$ be the splitting field of $f(x)$ over $\mathbb Q$. Assume ${\rm Gal}(E/\mathbb Q)$ has a subgroup (or an element) of order $3$. Prove $f$ is not solvable by radicals over $\mathbb Q$

I'm trying to show that ${\rm Gal}(E/\mathbb Q)$ is not a solvable group, perhaps using this claim but can't find a way to show it. I have tried to regard ${\rm Gal}(E/\mathbb Q)$ as a subgroup of $S_5$ and then I know that an element of order $3$ is a cycle, say WLOG $(1\space2\space3)$. Can I conclude something from that?
Any help would be appreciated
Comment: What have you tried so far? You should write any partial progress you've made in the question.
Comment: $ckefa I have added some details
Comment: See https://math.stackexchange.com/q/837042/348926
Comment: @LukasHeger Can't see how this helps. I'm only given one element of order $3$ and the other one in the group is its inverse
Comment: @BulGali If it wasn't clear, the Galois group acts transitively on the set of roots (since the polynomial is irreducible)
Comment: Because the polynomial is irreducible, the degree is divisible by 5. So there's an element of order 5. Conjugate the element of order 3 by that.
Comment: @LukasHeger Can you elaborate a bit?
Answer: Here's a proof that a $3$-cycle and a $5$-cycle generate $A_5$.
Let $G$ be the subgroup of $A_5$ generated by a $3$-cycle $\sigma$ and a $5$-cycle $\tau$. Note that there are $\binom{5}{3}=10$ subgroups of order $3$ in $A_5$. By the Sylow theorems, the normalizer of a $3$-Sylow has index $10$, so  it consists of $6$ elements.
As we have $N_{G}(\langle \sigma \rangle) \subset N_{A_5}(\langle \sigma \rangle)$, $\tau$ (and in fact any $5$-cycle) does not normalize $\langle \sigma\rangle$. Hence the index $[G:N_{G}(\langle \sigma \rangle)]$ is divisible by $5$. But by Sylow theory, we have $[G:N_{G}(\langle \sigma \rangle)] \equiv 1 \pmod 3$, thus we get that $10$ divides $[G:N_{G}(\langle \sigma \rangle)]$ and hence $|G|$. So we get that $30$ divides $|G|$. But if $|G|=30$, then $[A_5:G]=2$, so $G$ is normal in $A_5$, contadicting the fact that $A_5$ is simple. Thus $G=A_5$, as claimed.
Why does this solve the question? Well, since $f$ is irreducible, we have that $5$ divides $[E:\Bbb Q]$, so $\mathrm{Gal}(E/\Bbb Q)$ contains an element of order $5$, i.e. a $5$-cycle.
Answer: It is a classic theorem that the maximal solvable transitive subgroup of $S_5$ consists of all transforms
$$n\mapsto an+b$$ where we have arithmetic modulo $5$. Here $0\leq b\leq 4$ and $1\leq a \leq 4$. This group has order $20$. From this the claim follows.


finding what commands are executed by eclipse

Question: I have a project in eclipse right now that is compiled using ant. I am wondering what eclipse is doing behind the curtains whenever I double click on the jar target of one of this build files.
Is it possible to get the commands that eclipse is executing with ant, as I'd like to setup a shell script that compiles the project. How can I find what commands it is actually executing and what parameters it is passing.
I imagine there are also some variables like classpath, and buildpath that are set, where do I find them as to be easily copied over.
Eclipse comes with its own installation of ant. Is it possible to use that bundled installation of ant to build via command line.
Any help appreciated,
Ted.
Comment: Did you find a way to do this on Linux by any change?
Answer: One possible way is to look at the process executed by Eclipse when building.
For that, use Process Explorer (if you are on Windows) in order to display the full command line and all its parameter when running that build.
Comment: Similar idea: http://stackoverflow.com/questions/1989419/eclipse-is-there-a-way-to-get-eclipse-to-output-the-commands-given-to-run-your/1989645#1989645


Cross-checking vs. Pushing in Ice Hockey

Question: Last night, I was in an discussion with the referee in my adult league game. He called me once for a "cross-check" during a situation where I pushed a player out of position using my stick. I never actually "checked" him with my stick, as there was no impact, and I never stiffened my arms. It was a simple position battle. This, to me, is not a cross check.
Later, I removed a player from in front of the net in a similar fashion, but made sure I contact the player using my hands (despite having both hands on my stick). I was given a warning for this.
Later, he and I discussed the events, and I maintain that it is not illegal to push or shove an opposing player out of position using your stick, as long as the action is not a "check." In other words, you cannot shove the player into the boards, you cannot shove the player onto the ice, and you cannot "hit" the player with your stick.
Under USA Hockey Rule 609, which states

(a) A minor or a major penalty shall be assessed to a player who delivers a check to an opponent using the stick with both hands on the stick and no portion of the stick on the ice (cross-checking).
(b) A major plus a game misconduct penalty shall be assessed to any player who injures an opponent as a result of crosschecking.

I believe I am correct. Am I?
Comment: You are correct. Although it seems to be very rare to see a player try to get positioning using his both hands on his/her stick. Don't you agree that you usually gain position using either your shoulder (shoving) or with your off hand (try not to get called for holding)?
Comment: I was behind the player, removing him from the net-front.
Answer: From the information you provided, you are correct. I dug up some rules that had to do with your description. You would only be penalized if you committed one of the following...

NHL Rule 59.1

Cross-checking - The action of using the shaft of the stick between
  the two hands to forcefully check an opponent.

You did not commit this penalty because you did not initiate a "check".
NHL Rule 58.1

Butt-ending – The action whereby a player uses the shaft of the stick,
  above the upper hand, to check an opposing player in any manner or
  jabs or attempts to jab an opposing player with this part of the
  stick.

You did not commit this foul because again, you did not initiate a "check".
NHL Rule 56.1 Interference

Stick: A player who does not have body position on his opponent, who
  uses his stick (either the blade or the shaft, including the butt-end
  of the shaft) to impede or prevent his opponent from moving freely on
  the ice shall be assessed a hooking penalty.

Although I was not there, this is the only circumstance I can see the ref having an edge on you. Some refs will make a call if you are fighting for position and you use your stick against the body, even if you don't check. Refs want to see you fight for position by shoving the other player and using your stick to tie up the opponent's stick, not the opponent's body.
Comment: The NHL rules are slightly different than USA Hockey rules, which is what the league operates under. However, your assessment is much the same as my own. I don't think interference is callable, because I'm not really preventing free motion of the player -- namely, I was not preventing the player from making a free play towards the puck.
Answer: I'm a USA Hockey official. In addition to the rule book the officials also receive a casebook (usually the same physical book) to help clarify the intent behind the rules. Let me quote one of the situations from the casebook on Cross-Checking

Situation 2
Two players are physically engaged in front of the goal and  competing for body position. The defensive player uses  the
stick – with no extension of the arms – to "steer" the  attacking
player in a desired direction. May this be considered  cross-checking?
No. Rule Reference 609(Note).
Even though two hands are on the stick
and the blade may be  off the ice, the fact that the arms have not
been extended and  no check is being delivered means that
cross-checking has not  occurred. Of course, if a competitive
advantage is gained and  there is no puck in the area, an interference
penalty may apply. However, if at any time the arms are extended and
deliberate  contact is made with the opponent by the stick with both
hands on the stick, a cross-checking infraction has occurred. This
most often occurs in front of the goal when a player  believes the
officials are not watching or along the boards  when a player is
protecting the puck by having their back  CASEBOOK – PLAYING RULES 234
USA Hockey turned to center ice. In this instance, the opponent will
extend the arms and make contact to the back of the  opponent with the
stick, but not use enough force to be  considered a check from behind.
This action should still be  considered a cross-checking violation.

So the main point of emphasis is the extension of the arms. Even if the stick doesn't contact the opponent if your stick is between hands and you push someone it is still cross-checking. You can use your stick to steer someone from out in front of the net as long as you don't forcefully extend your arms into them. The whole idea here is it is ok to "body up" on them to move them, but you can "hit" them if they don't have the puck.
Same idea with interference. You can body up on them to force out from in front of the net, but if you hit them meaning a forceful motion into them and they don't have the puck that is interference.
There are also videos on the USA Hockey referee site that show the difference between a body check vs body contact (now called competitive contact starting September 2021). You can find these on USA Hockey's YouTube channel.


Cubic root epsilon delta proof

Question: I'm reviewing this epsilon delta proof for the continuity of the cubic root:

but I can't see why is so evident that $\sqrt[3]{x^2}+\sqrt[3]{xc}+\sqrt[3]{c^2}\ge \sqrt[3]{c^2}$. Any help please? Thanks in advance.
Answer: Note that $c\neq0$. So, if $x$ is close enough to $c$, $x$ and $c$ will have the same sign and therefore $xc>0$. Therefore $\sqrt[3]{x^2}+\sqrt[3]{cx}>0$, and this implies that $\sqrt[3]{x^2}+\sqrt[3]{cx}+\sqrt[3]{c^2}>\sqrt[3]{c^2}$.
Comment: @Dunkelheit Oh, except in the negative case it would be $3c/2 < x < c/2$ instead.
Comment: @aschepler did you say that because we need to estimate the product $cx$ so if we request $\delta < |c|/2$ then from $|x-c|<\delta<|c|/2$ we deduce that $c-|c|/2 < x < c+|c|/2$, so $x$ is positive if $c$ is positive and $x$ is negative if $c$ is negative because in both cases is $c/2 < x < 3c/2$; but for both to be satisfied (continuity and sign accordance) we have to impose $\delta = \min(\varepsilon \sqrt[3]{c^2},|c|/2)$? Thanks.
Comment: Thank you José Carlos.
Comment: So it might be more precise to say we choose $\delta = \min(\epsilon \sqrt[3]{c^2}, |c|/2)$.
Comment: @Dunkelheit Exactly.
Comment: @aschepler yes, you're right! Thanks again for your kindness in answering me.
Comment: Thanks for all of the answers above. I am reviewing this myself, and I was just wondering if it is reasonable to argue that $(x^\frac{1}{3})^2+c^\frac{1}{3}x^\frac{1}{3}+c^\frac{2}{3}$ is a quadratic equation in $x^\frac{1}{3}$ leading to the argument that $(x^\frac{1}{3})^2+c^\frac{1}{3}x^\frac{1}{3}+c^\frac{2}{3} \geq \frac{3c^\frac{2}{3}}{4}$ by evaluating the quadratic at its vertex $x=-\frac{c}{8}$. We know that the quadratic is convex since the coefficient of the squared term is positive, so the vertex is the absolute minimum.
Answer: Note that for the denominator, $\sqrt[3]{x^2}+\sqrt[3]{c^2}=x^{2/3}+c^{2/3}\geq 0$, so $|g(x)-g(c)|\geq\frac{|x-c|}{|cx|^{1/3}}$.
We can now bound $|x|$ by (if $|x-a|<\delta$, which we can do by choosing $\delta$ as the minimum of 2 numbers) $|x|<2|a|$ (prove this as a good exercise for working with limits) , so it follows that we can bound
$$|g(x)-g(c)|\leq\frac{|x-c|}{|c|^{2/3}}$$ and we can use the $\epsilon-\delta$ definition easily to prove $g$ is continuous

Cubic root epsilon delta proof


Probability of choosing one group ahead of another

Question: Broker receives an order to purchase N units of stock A and M units of stock B - if individual orders are placed at random, what is the probability that all N units of A are purchased first (and therefore all M units of B are purchased last).
My Answer: The probability 1 unit of A is purchased before M units of B is 1/M+1 and hence the probability that N units of A are purchased before M units of B will be (1/M+1)^N. Is this correct?
Comment: @MattKrause No its not actually. Im working on interview Questions.
Answer: It sounds like having a non-bernoullian extraction here where the prob. to extract A at first try is N/(N+M). The prob. to extract A again at second try is (N-1)/(N+M-1)and again and again. Assuming the joint probability to extract AAA...A N-times in a row as the multiplication of the above it should yield to:
[N (N-1) (N-2) ... 1] /[(N+M)(N+M-1) ... M]
which if I am not wrong should be
[N! (M-1)!]/(N+M)!
Sorry for bad formatting.


How to perform efficient vector initialization in Rust?

Question: What's a good way to fill in a vector of structs in Rust where:

The size is dynamic, but known at the time of initialization.
Doesn't first initialize the memory to a dummy value.
Doesn't re-allocate memory as its filled.
In this example, all members of the vector are always initialized.(In keeping with Rusts assurance of no undefined behavior).

And ideally

Doesn't index check each index access(since the size is known when declaring the vector this should be possible).
Doesn't require unsafe(Not sure if this is reasonable, however the compiler _could_ detect that all values are always filled, allowing such logic in an unsafe block).

The C equivalent is:
struct MyStruct *create_mystruct(const uint n) {
    struct MyStruct *vector = malloc(sizeof(*vector) * n);
    for (uint i = 0; i < n; i++) {
        /* any kind of initialization */
        initialize_mystruct(&vector[i], i);
    }
    return vector;
}

I'm porting over some C code which fills an array in a simple loop, so I was wondering if there was a Rustic way to perform such a common task with zero or at least minimal overhead?
If there are typically some extra checks needed for the Rust version of this code, what's the nearest equivalent?
Comment: See also http://stackoverflow.com/q/20734743/155423, http://stackoverflow.com/q/27062874/155423, http://stackoverflow.com/q/27393166/155423, http://stackoverflow.com/q/28656387/155423, http://stackoverflow.com/q/29530011/155423, http://stackoverflow.com/q/31360993/155423.
Comment: Checked all the other questions, don't think they're direct duplicates (though some are close).
Answer: Just use map and collect.
struct MyStruct(usize);

fn create_mystructs(n: usize) -> Vec<MyStruct> {
    (0..n).map(MyStruct).collect()
}

"Initializing" doesn't make sense in safe Rust because you'd need to have the ability to access the uninitialized values, which is unsafe. The Iterator::size_hint method can be used when collecting into a container to ensure that a minimum number of allocations is made.
Basically, I'd trust that the optimizer will do the right thing here. If it doesn't, I'd believe that it eventually will.
Comment: @ideasman42 You'd use `MyStruct`'s constructor instead of `initialize_mystruct`, and then do `.map(MyStruct::new)`. Rust knows that `map` preserves the length and will allocate properly, yes.
Comment: How would the `initialize_mystruct` fit in here? Also, I assume Rust is smart enough to detect that the iterator has a fixed size and not resize the vector while running collect?
Comment: And since I used a *tuple struct*, `MyStruct's` constructor is just `MyStruct`, the function called in the `map`.


Finding the flaw in $-12=(-12)^1=(-12)^{6/6}=\cdots=12$

Question: I was tutoring today and came across a question that I was incapable of explaining sufficiently. It stems from the following false string of equalities...
$$-12=(-12)^1=(-12)^\frac{6}{6} =((-12)^6)^\frac{1}{6} =((-1)^6 12^6)^\frac{1}{6}=(12^6)^\frac{1}{6}=12$$
If anyone can explain the false step (Im assuming the third "="), why this string of equalities is wrong, and how to avoid making it that would be most helpful for when I need to explain it again.
Comment: Similar question has been asked many times ,the thing is $a^{bc}={(a^b)}^c$ need not be valid
Comment: At the last step there are many choices for the $6$-root...
Comment: Also a similar problem posted [here](https://math.stackexchange.com/questions/3907035/what-is-1-frac13/3907045#3907045)
Comment: Please [don't use `\frac` in exponents or limits of integrals](//math.meta.stackexchange.com/a/5057/290189). It looks bad and confusing, and it rarely appears in professional mathematics typesetting.
Answer:
$-12=(-12)^1=(-12)^\frac{6}{6} =((-12)^6)^\frac{1}{6}$

Last step above is wrong, because of the arbitrary convention that a positive number (i.e. $[(-12)^6]$) when taken to the $(1/6)$ power is equal to a positive number, not a negative number.


NBA Free Agency vs. Draft for foreign players

Question: I have a question related to how non-US/CAN players may join a NBA team. I understand that getting drafted should be usually preferred from the players' perspective, as you have a guaranteed salary in case you are actually signed. However, one could also sign at a NBA team as a free agent.
My question is the following: Luka Doncic entered the NBA this year as the one of the first draft picks. Arguably, as a EuroLeague MVP, he is more certain to become a top player than most other players at his age. Could he instead have negotiated with other NBA teams and just sign there? This way, he may have not ended up with a lottery team.There must have been a team with salary space willing to pay him above rookie salary. Are there any rules preventing this?
Answer: Yes. As with everything else, it's all down to the Collective Bargaining Agreement, the agreement between the players and the league/teams. The details are covered by the fantastic NBA Salary Cap FAQ:

An international player who is at least 19 but younger than 22 also can become draft eligible by declaring himself an early entry player. An international player who is older than 22 or was not selected in the draft in the same calendar year as his 22nd birthday is considered a rookie free agent.

As Dončić is 19, his only option if he wanted to play in the NBA before he was 22 was to declare himself an early entry player and enter the draft; an "early entry player" here is the same status as college underclassmen declaring themselves for the draft that gives them the ability to go back to college if they withdraw from the draft by a certain date - although this is somewhat irrelevant in Dončić's case as he wouldn't be able to play college basketball due to having played professional basketball in Europe.


SpringBoot logging - extraneous hyphen at start of every log entry

Question: I am trying to eliminate a leading hyphen from our console and file logs in SpringBoot 1.3.5.RELEASE with default logback config.
Logging pattern looks like:
logging:
  pattern:
    console: '%d{yyyy-MM-dd HH:mm:ss.SSS} %clr([${spring.application.name}]){red} %clr(%5p) %clr(${PID:- }){magenta} %clr(---){faint} %X{req.requestId} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%rEx}'

The file log pattern is similar, without the color coding. Both output every line after the first with a leading hyphen, which is making our syslog - logstash - grok filtering trickier.  Example output:
2016-06-21 11:52:00.576 [my-app] INFO etc.. (application started)
-2016-06-21 11:52:00.583 [my-app] DEBUG etc..
-2016-06-21 11:52:00.583 [my-app] INFO etc..

I can't see anything in the docs mentioning this behaviour. Welcome any advice on how to eliminate it, if possible!
Update
Thanks to Edgar's answer below, it turns out this was caused by the following at the end of our logging pattern:
${LOG_EXCEPTION_CONVERSION_WORD:-%rEx}

I replaced it with:
${LOG_EXCEPTION_CONVERSION_WORD:%rEx}
et voila, the hyphen at the start of the following line disappears. See http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html#boot-features-custom-log-configuration
Answer: The problem is in this part of logging.pattern.console:
${LOG_EXCEPTION_CONVERSION_WORD:-%rEx}

:- is Logback's default value delimiter and is what you should use in logback.xml. However, you're configuring things in application.properties where it's Spring Framework's default value delimiter (:) which should be used.
As you've used :-, you're saying use the value of LOG_EXCEPTION_CONVERSION_WORD and, if it's not set, use -%rEx instead.
The correct syntax is:
${LOG_EXCEPTION_CONVERSION_WORD:%rEx}

Comment: Document link is [here](http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-custom-log-configuration), search 'you should use Spring Boot's syntax'
Answer: It's hard to diagnose without your providing the full logging format. I'm seeing something similar in our code, and it seems to be related to including this in the format:
${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}
If you're using it, then the hyphen may be the one before the %w. I'm not sure what the intended purpose of this is. If I find it, I'll add it to my answer.
Comment: ah, so simple - just removed the hyphen from `${LOG_EXCEPTION_CONVERSION_WORD:%rEx}`. I hadn't included it as I didn't think it was relevant.. will update my question with the full logging pattern - thanks!
Comment: how can I apply filters to it?
Answer: The suggested answers are actually slightly wrong, or at least are missing some details of what is happening.
If you replace ${LOG_EXCEPTION_CONVERSION_WORD:-%rEx} with ${LOG_EXCEPTION_CONVERSION_WORD:%rEx}, Spring will interpolate it into %rEx when it parses the property file (unless there happens to be a property LOG_EXCEPTION_CONVERSION_WORD available at that time).
LOG_EXCEPTION_CONVERSION_WORD is actually a System property provided by LoggingSystem and it's intended to be interpolated by Logback (which uses the ":-" syntax for default values).
You can fix the issue by defining a Spring property for the dollar character
dollar: $

Then replace ${LOG_EXCEPTION_CONVERSION_WORD:-%rEx} with:
${dollar}{LOG_EXCEPTION_CONVERSION_WORD:-%rEx}
thus bypassing Spring property interpolation. Then Logback will take care of interpolating the resulting pattern.


Provee that $\mathbb{P}^2(\mathbb{R})/H \cong S^2$, where $H\subset \mathbb{P}^2(\mathbb{R})$ is a projective line

Question: $\mathbb{P}^2(\mathbb{R})/H$ identifies the topological quotient space given by the relation $x \sim y \Leftrightarrow x=y$ or $x,y \in H$.
I tried to build an identification $\mathbb{P}^2(\mathbb{R}) \longrightarrow S^2$ defined by $[v] \longmapsto \frac{v}{||v||}$, but it doesn't seem to work.
Comment: Intuition (not a proof): $\mathbb P^2(\mathbb R)$ is $\mathbb R^2$ plus a line at infinity. If you collapse that line to a point, you get $\mathbb R^2$ plus a point at infinity, and that's $\mathbb S^2$,
Answer: Let $p : \mathbb R^3 \setminus \{0\} \to \mathbb P^2 = \mathbb P(\mathbb R^2)$ denote the quotient map.
A projective line $H \subset \mathbb P^2$ is given as $p(H' \setminus \{0\})$, where $H'$ is a two-dimensional linear subspace of $\mathbb R^3$. Equivlently, a subset $H \subset \mathbb P^2$  is a projective line if $H' = p^{-1}(H) \cup \{0\}$ is a two-dimensional linear subspace of $\mathbb R^3$.
It is easy see that $\mathbb P^2 /H_1 \approx \mathbb P^2 /H_2$ for any two projective lines $H_i$. In fact, let $\phi'$ be a linear automorphism on $\mathbb R^3$ such that $\phi'(H'_1) = H'_2$. Note that $\phi$ is a homeomorphism. Clearly $\phi'$ induces a homeomorphism $\phi$ on $\mathbb P^2$ such that $\phi(H_1) = H_2$. Hence we get a homeomorphism $\bar \phi : \mathbb P^2/H_1 \to \mathbb P^2/H_2$.
It therefore suffices to show that $\mathbb P^2/H_0 \approx S^2$, where $H_0$ is the special projective line such that $H_0' = \overline{\mathbb R}^2 = \{(x,y,0) \mid x,y \in \mathbb R\}$. Let $S^2_+ = \{(x,y,z) \in S^2 \mid z \ge 0\}$ denote the closed upper hemisphere of $S^2$. It is well-known that
$$\mathbb P^2 = S^2_+ / \sim $$
where $\xi \sim \eta$ iff $\eta = \pm \xi$. Note that the only pairs of distinct points identified by $\sim$ lie on $\bar S^1= \{(x,y,0) \mid (x,y) \in S^1\}$. Under the identification $\mathbb P^2 = S^2_+ / \sim $ the projective line $H_0$ corresponds to $\bar S^1/\sim$ (which is homeomorphic to  $S^1$ although we do not need to know this). Therefore
$$\mathbb P^2 /H_0 \approx (S^2_+/\sim)/(\bar S^1/\sim) \approx S^2_+/\bar S^1 \approx S^2 .$$