Q: Run separate nodejs file from PhantomJS / CasperJS I'm trying to execute a nodejs script from CasperJS. This should be possible from the PhantomJS childprocess library. But it doesn't seem to be working for me. It's not giving any errors, but it's not executing the node script either. Because that script sends out a push notification. When I run the script directly from command then it works fine. But not from my CasperJS script.
var childProc = require("child_process");

var casper = require('casper').create({
    viewportSize: {width: 800, height: 400}
});
var utils = require("utils");

casper.start('http://www.google.com', function() {
    this.echo('Home page opened');
    this.echo(this.getTitle());
    childProc.execFile('C:\\Google Drive\\nodejs\\push.js', [], null, function (err, stdout, stderr){});

    this.exit();
});

Anyone any idea what I'm doing wrong?

A: You have two problems:

*

*You forgot to add the command for execution

*You're exiting too early, because execFile is an asynchronous function.

Try:
casper.start('http://www.google.com', function() {
    this.echo('Home page opened');
    this.echo(this.getTitle());
    childProc.execFile('C:\\Google Drive\\nodejs\\push.js', [], null, function (err, stdout, stderr){
        utils.dump(arguments);
        casper.echo("Exiting..."):
        casper.exit();
    });
}).run(function(){/* This prevents CasperJS from exiting */});


Q: Map Projection is not working as expected when zoom level is not the same I want to show the user location on top of the drawer that I have in my app instead of center of the map since the drawer covers part of the map :
fun centerMap(height: Int, drawerHeight: Int) {
        LocationDataProvider.location?.let {
            val length = ((height - drawerHeight) / 2) + (drawerHeight - (height / 2))
            val point = googleMap.projection.toScreenLocation(LatLng(it.lat, it.lng))
            Log.d("Ali", "${point.y.toString()},  ${point.x.toString()}")
            val newY = point.y + length
            val newLatLng = googleMap.projection.fromScreenLocation(Point(point.x, newY))
            moveCamera(newLatLng)
        }
    }

LocationDataProvider.location returns center of the map. Here is moveCamera method :
fun moveCamera(location: LatLng) {
        val cameraUpdate: CameraUpdate = CameraUpdateFactory.newLatLngZoom(
            location, 18F
        )
        googleMap.animateCamera(cameraUpdate)
        googleMap.setOnCameraMoveStartedListener(this@MapController)
    }

In my logic CenterMap method is called every 5 seconds.The problem is first it zooms somewhere over ocean and then immediately in 5 seconds, it zooms on the desired location (top of the drawer). Here is the log result of centerMap method every 5 seconds ("${point?.y.toString()},  ${point?.x.toString()}"):
D/Ali: 468,  1344
D/Ali: -18826752,  4133
D/Ali: 418,  542
D/Ali: 419,  539
...

As you see as a result of first log, it moves over ocean, from the second log it moves to desired location, and from there, it will be on desired location.
I concluded that when zoom level is not 18f, projection is not working as expected, so if I use following method, and then use projection, it works as expected :
fun centerMap() {
        LocationDataProvider.location?.let {
            moveCamera(LatLng(it.lat, it.lng))
        }
    }

That means moveCamera method will be called twice, but is there any solution that projection works as expected without considering zoom level?

A: Seems you can use map padding GoogleMap.setPadding():

public void setPadding (int left, int top, int right, int bottom)
Sets padding on the map.
This method allows you to define a visible region on the map, to
signal to the map that portions of the map around the edges may be
obscured, by setting padding on each of the four edges of the map. Map
functions will be adapted to the padding. For example, the zoom
controls, compass, copyright notices and Google logo will be moved to
fit inside the defined region, camera movements will be relative to
the center of the visible region, etc.


Q: PHP - Failed to Open Stream Error (no such file or directory) I have following directory structure for the project:

Home.php simply includes either of the two views i.e. login or invoice depending upon the session variables.
if (!isset($_SESSION['username'])) {
            include 'views/login.php';
        } else {
            include 'views/invoice.php';
        }

I include my constants file which contain database connection strings and other constants along with a autoloader file which register a autoload function to include all the classes.
include 'includes/constants.php';
include 'includes/autoloader.php';

It works without issues but when i use the same in get_data.php file it gives following error:
Warning: include(includes/constant.php): failed to open stream. No such file or directory.
Same error for autoloader.php too.


Q: Yajra laravel datatables oracle disable escaping string How to disable escaping string in yajra/laravel-datatables-oracle? version: "dev-master"
http://take.ms/hKGEI

A: I found the answer to your question. After updating yajra/laravel-datatables-orakle package to version 7.* - All columns escaped by default to protect from XSS attack. To allow columns to have an html content, use rawColumns api. doc


Q: Prove or refute that $g \circ f$ with $dom(g \circ f) = A...$ Here is my question from an assignment:

Let $f: A \to B$ and $g: \text{ran}(f) \to C$ be functions. We define the composition of $f$ and $g$ as the relation $g \circ f$ from $A$ to $C$ such that $(x,y)\in g \circ f \iff g(f(x)) = y$. Prove or refute $g \circ f$ is a function with $\text{dom}(g \circ f) = A$.

I have no idea how to do this. Also, I have only a slight understanding of the concept the question is asking about. Does anyone have any input?

A: First, i'm gonna proof that $dom(g \circ f)= dom(f) =A$, for a theorem, if $$ran(f) \subseteq dom(g) \implies dom(g \circ f)=dom(f)$$.
For hypothesis $dom(g)=ran(f)$ then $dom(g \circ f)=dom(f)$. By the definition of function $dom(f)=A$. Now, i'm gonna proof $(x,z_1) \in g \circ f \land (x,z_2) \in g \circ f \implies z_1=z_2$. Suppose  $(x,z_1) \in g \circ f \land (x,z_2) \in g \circ f$ by the definition of composition
$$(( \exists y_1)(x,y_1)\in f \land (y_1,z_1) \in g) \land (( \exists y_2)(x,y_2)\in f \land (y_2,z_2) \in g) \\
( \exists y_1)(\exists y_2)(x,y_1) \in f \land (x,y_2) \in f \land (y_1,z_1) \in g \land (y_2,z_2) \in g$$
As $f$ is a function, then $y_1=y_2$
$$(\exists y_1)(x,y_1) \in f \land (y_1,z_1) \in g \land (y_1,z_2) \in g$$
Similarly, as $g$ is function then $z_1=z_2$. So $g \circ f$ is a function $\blacksquare$


Q: Software PDR - how to explain the code by PDR ( preliminary design review) with clock/diagram I am trying to write PDR for the first time.
I have the follwoing important blocks/parts which I want to demonstrate in the PDR by blocks or diagarm (e.g UML).

*

*A job's queue which I add a new job (estimation job).

*The job "contains" a function (device_estimation) which call another function (send_msg). Bothe functions belongs to the same class.

How should I descript those three parts (the job, and the 2 functions) by special blocks / diagram?
p.s
I use Visio

A: You could use a sequence diagram in this case.

It's easy to show call structures like in your case.


Q: Openpyxl - I can't set cell format and sum values correctly in time format (h:mm) openpyxl version 3.0.7, python version 3.8.8
I’m trying to format cells as hours:minutes. From reading the openpyxl doc’s re formatting numbers:
https://openpyxl.readthedocs.io/en/stable/_modules/openpyxl/styles/numbers.html
FORMAT_DATE_TIME3 should do what I need. It uses BUILTIN_FORMATS(20) which is 'h:mm'. However, my implementation of the code does not have the expected results on the spreadsheet. The values come out as expected, but not with the formatting.
I want the cells to be formatted as h:mm, so when I add 1:02 and 1:58 I get 3:00 ( for 3 hours). I've tried 2 different ways to format a cell (meth 1 & meth 2), with a sum formula for meth 1 column but I'm not quite there.
Any help would be appreciated, Thanks.
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import numbers

wb = Workbook()
ws =  wb.active

ws['A3'] = "Meth 1"
ws['A4'] = "1:02"
ws['A5'] = "1:58"
ws['A4'].number_format = numbers.FORMAT_DATE_TIME3
ws['A5'].number_format = numbers.FORMAT_DATE_TIME3
print('A4 number format = ', ws['A4'].number_format)
print('A5 number format = ', ws['A5'].number_format)

cell = ws.cell(row=7, column=1, value='= SUM(A{}:A{})'.format(4, 5))
cell.number_format = numbers.FORMAT_DATE_TIME3

ws['C3'] = "Meth 2"
cell = ws.cell(row=4, column=3, value="1:02".format(numbers.FORMAT_DATE_TIME3))
cell.number_format = numbers.FORMAT_DATE_TIME3
cell = ws.cell(row=5, column=3, value="1:58")
cell.number_format = numbers.FORMAT_DATE_TIME3

wb.save(filename = 'hours_mins.xlsx')

I have printed the number format to verify it is the format required
A4 number format =  h:mm
A5 number format =  h:mm

excel output produced:

A: You have entered the times as strings. As such, the formatting for numbers has no effect. You need to enter either datetime.time objects or datetime.timedelta objects in order for the formatting to have an effect, though openpyxl by default will try and set it correctly.
eg.
ws["A4"] = datetime.time(hours=1, minutes=2)


Q: Can I include formulas in a struct somehow? I am trying to create a struct which uses a formula to automatically create data in one of the struct fields when the other two values are entered.
For example, I want to create a 2D rectangular room with Length and Width which are values that are entered. I would then like to include the formula Area = Length * Width  in the struct.
Have tried and just get a syntax error :

syntax error: unexpected =, expecting semicolon or newline or }

// CURRENT CODE
type room struct {
 L int
 W int
 A int
}
// WOULD LIKE IT TO BE
type room struct {
 L int
 W int
 A int = room.L*room.H
}

A: Since A is invariant, this would be a good fit for a function, not a field.
type room struct {
    L int
    W int
}

func (r *room) area() int {
    return r.L * r.W
}

A: If you would like to keep A as a Field, you can optionally preform the computation in a constructor.
type room struct {
 L int
 W int
 A int
}

func newRoom(length, width, int) room {
  return room{
    L: length,
    W: width,
    A: length * width,
  }
}

A: If you think about what you're after, you'll see that basically your desire to "not add unnecessary code" is really about not writing any code by hand, rather than not executing any code: sure, if the type definition
type room struct {
 L int
 W int
 A int = room.L*room.H
}

could be possible in Go, that would mean the Go compiler would have make arrangements so than any code like this
var r room
r.L = 42

is compiled in a way to implicitly mutate r.A.
In other words, the compiler must make sure that any modification of either L or W fields of any variable of type room in a program would also perform a calculaton and update the field A of each such variable.
This poses several problems:

*

*What if your formula is trickier—like, say, A int = room.L/room.W?
First, given the casual Go rules for zero values of type int,
an innocent declaration var r room would immediately crash the program because of the integer division by zero performed by the code inserted by the compiler to force the invariant being discussed.
Second, even if we would invent a questionable rule of not calculating a formula on mere declarations (which, in Go, are also initializations), the problem would remain: what would happen in the following scenario?
var r room
r.L = 42

As you can see, even if the compiler would not make the program crash on the first line, it would have to arrange for that on the second.
Sure, we could add another questionable rule to sidestep the problem: either somehow "mark" each field as "explicitly set" or require the user to provide an explicit "constructor" for such types "armed" with a "formula".
Either solution stinks in its own way: tracing write field access incurs performance costs (some fields now have a hidden flag which takes up space, and each access of such fields spends extra CPU counts), and having constructors goes again one of the cornerstone principles of the Go design: to have as little magic as possible.

*The formula creates a hidden write.
This may not be obvious until you start writing "harder-core" Go programs for tasks it shines at—highly concurrent code with lots of simultaneously working goroutines,—but when you do you're forced to think about shared state and the ways it's mutated and—consequently—on the ways such mutations are synchronized to keep the program correct.
So, let's suppose we protect access to either W or L with a mutex; how would the compiler make sure mutation of A is also proteted given that mutex operations are explicit (that is, a programmer explicitly codes locking/unlocking operations)?

*(A problem somewhat related to the previous one.)
What if "the formula" does "interesting things"—such as accessing/mutating external state?
This could be anything from accessing global variables to querying databases to working with a filesystems to exchanges over IPC or via networking protocols.
And this all could be very innocently-looking, like A int = room.L * room.W * getCoefficient() where all the nifty details are hidden in that getCoefficient() call.
Sure, we, again, could work-around this by imposing an arbitrary limit on the compiler to only allow explicit access to the fields of the same enclosing type and only allow them to participate in simple expressions with no function calls or some "whitelisted" subset of them such as math.Abs or whatever.
This clearly reduces the usefulness of the feature while greatly complicating the language.

*What if "the formula" has non-linear complexity?
Suppose, the formula is O(N³) with regard to the value of W.
Then setting W on a value to 0 would be processed almost instantly but setting it to 10000 would slow the program down quite noticeably, and both of these outcomes would result form a seemingly not too different statements: r.W = 0 vs r.W = 10000.
This, again, goes agains the principle of having as little magic as possible.

*Why would we ony allow such things on struct types and not on arbitrary variables—prodived they are all in the same lexical scope?
This looks like another arbitrary restriction.
And another—supposedly—the most obvious problem is what should happen when the programmer goes like
var r room
r.L = 2  // r.A is now 2×0=0
r.W = 5  // r.A is now 2×5=10
r.A = 42 // The invariant r.A = r.L×r.W is now broken

?

Now you can see that all the problems above may be solved by merily coding what you need, say, with the following approach:
// use "unexported" fields
type room struct {
 l int
 w int
 a int
}

func (r *room) SetL(v int) {
  r.l = v
  updateArea()
}

func (r *room) SetW(v int) {
  r.w = v
  updateArea()
}

func (r *room) GetA() int {
  return r.a
}

func (r *room) updateArea() {
  r.a = r.l * r.w
}

With this approach, you may be crystal-clear about all the issues above.
Remember that the programs are written for humans to read and only then for machines to execute; it's paramount for proper software engeneering to keep the code as much without any magic or intricate hidden dependencies between various parts of of it as possible. Please remember that

Software engineering is what happens to programming
  when you add time and other programmers.
© Russ Cox

See more.


Q: Spring AOP - proxying object returned from method In this example:
public class ConnectionPool {
  public java.sql.Connection getConnection() {
      ...
  }
}

@Bean
@Scope("singleton")
public ConnectionPool connectionPool(...) throws Exception {
    return new ConnectionPoolImpl(...);
}

I want to monitor calls to java.sql.Connection.close() on Connection objects returned from getConnection().
I tried adding @Lookup to the getConnection() method but it had no effect.
How do I get Spring to proxy the java.sql.Connection object?

A: You can create proxy for the ConnectionPool and return the proxy in the bean creation method
@Bean
@Scope("singleton")
public ConnectionPool connectionPool(...) throws Exception {
    ConnectionPoolImpl delegate = new ConnectionPoolImpl(...);
    ConnectionPoolCallHandler callHandler = new ConnectionPoolCallHandler(delegate);
    ConnectionPool proxy = Proxy.newProxyInstance(
                ConnectionPool.getClass().getClassLoader(),
                new Class[]{ConnectionPool.class},
                callHandler);

//    return new ConnectionPoolImpl(...);
    return proxy;
}

and
public class ConnectionPoolCallHandler implements InvocationHandler {
    private ConnectionPoolImpl delegate;
    public ConnectionPoolCallHandler(ConnectionPoolImpl delegate) {
        this.delegate=delegate;
    }
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
         //all invoked methods should call
         //appropriate methods of delegate passing all parameters
         //plus your additional tracking logic here
    }
}

A: @Pointcut("within(java.sql.Connection.close(..)")
public void closeAspect() {}

@Around("closeAspect()")
public void logAround(ProceedingJoinPoint joinPoint) throws Throwable
{
  joinPoint.getThis();//Will return the object on which it(close function) is called
  //Do whatever you want to do here
   joinPoint.proceed();
  //Do whatever you want to do here
}


Q: Classify each case in dataframe with significant groups (or clusters) in stratified data I am needing to cluster (perhaps k-means) a dependent variable (Value) considering stratification by two independents (Country; Year); and at the end classify each df case (example top, middle and bottom).
df structure:
df <- structure(list(Country = c("B", "B", "B", "B", "B",
"B", "B", "B", "B", "B", "E", "E", "E", "E",
"E", "E", "E", "E", "E", "E"), Year = c(2019L,
2019L, 2019L, 2019L, 2019L, 2020L, 2020L, 2020L, 2020L, 2020L,
2019L, 2019L, 2019L, 2019L, 2019L, 2020L, 2020L, 2020L, 2020L,
2020L), Value = c(64, 48, 20, 49, 43, 39, 32, 56, 36, 32,
70, 45, 36, 40, 34, 72, 49, 54, 26, 16)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -20L))

What I have done so far:
library(tidyverse)
df %>%
  group_by(Country, Year, .add = TRUE) %>%
  group_split() %>%
  map_df( ~ .x %>% mutate(cluster =
                            kmeans(.x[, c('Value')], 3)$cluster))

However, I am concerned that group stratification is not being incorporated. In my real df the message is returned:
Warning: did not converge in 10 iterations


Q: $\int_{0}^{1}f(x)\cdot g(x)dx=\int_{0}^{1}f(x)dx\cdot \int_{0}^{1}g(x)dx$ Let $f:[0,1]\rightarrow \mathbb{R} $ be a continuous function so that $\int_{0}^{1}f(x)\cdot g(x)dx=\int_{0}^{1}f(x)dx\cdot \int_{0}^{1}g(x)dx$, for any $g:[0,1]\rightarrow \mathbb{R}$, continuous and not differentiable.
Prove that $f$ is constant.
I have no idea on what to do.

A: Suppose $\{g(x)\}$ is a sequence of functions $g_n(x)=\frac{1}{n\sqrt {2\pi}} e^{-\frac {\mu}{2n^2}x^2}$
The sequence converges to the Dirac delta function $\delta(x-\mu)$
$\int_0^1 f(x)g(x) = f(\mu)$ if $\mu \in [0,1]$
$\int_0^1 f(x)\int_0^1 g(x) = \int_0^1 f(x) = f(\mu)$
and if we consider all $g.$
$f(\mu) = \int_0^1 f(x)$ for all $\mu \in [0,1]$
$f(\mu)$ is constant over the interval.

A: As @RobertIsrael pointed out, the non-differentiable continuous functions are dense in $C[0,1]$ with respect to the uniform norm, and therefore
$$\int_0^1 f(x) g(x) \, dx = \int_0^1 f(x) \, dx \int_0^1 g(x) \, dx$$
holds for any continuous function $g$. If we choose $f=g$, then we find
$$\int_0^1 f(x)^2 \, dx = \left( \int_0^1 f(x) \, dx \right)^2.$$
This means that
$$\int_0^1 ( f(x) - a)^2 \, dx = 0$$
for $a:= \int_0^1 f(y) \, dy$. Since the integrand $x \mapsto (f(x)-a)^2$ is continuous and non-negative, this implies
$$f(x)-a=0 \qquad \text{for all $x \in [0,1]$},$$
i.e.
$$f(x) = a = \int_0^1 f(y) \, dy \qquad \text{for all $x \in [0,1]$}.$$
Remark: More generally, if $f$ is a continuous function and $V$ strictly convex, then $$\int_0^1 V(f(x)) \, dx = V \left( \int_0^1 f(x) \, dx \right)$$ if and only if $f$ is constant, see this question; here, we have proved this statement for $V(x) = x^2$.

A: Fro the first mean value theorem for definite integrals follows that the exists $c \in (0, 1)$ such that
$$\int_{0}^{1}f(x)dx = f(c)$$
With the assumption above
$$\int_{0}^{1}(f(x)-f(c))^2dx = \int_{0}^{1}f^2(x)dx - \int_{0}^{1}f^2(c)dx = (\int_{0}^{1}f(x)dx)^2 - \int_{0}^{1}f^2(c)dx = 0$$
follows $f(x)-f(c) = 0$ on $(0,1)$.


Q: Ignoring leading whitespace when manipulating standard one-dimensional arrays We have to read from a file in this case called small.txt. The contents of the file look like the following:
NOT      11010011
AND      10010010  11001110
OR       10011001  11100101
CONVERT  10010110
LSHIFT   11001101  3
WRONG    01010100  10101010

Every word indicates the beginning of a new line in this file. The problem I'm having is getting my code to read in the last (3rd column). Each column is ten spaces in length. The following are the rules I have to follow:
Based on the commands in the file, perform operations on the operands following the command. Each command is independent from another, so one command cannot affect another.
The commands are all binary commands, but you can’t use C++’s built in commands for this. This means no: “~, &, |, << (when used as a binary operator)”. You can of course use && and ||, these are different. << Can be used for cout as always, just not as a binary operator.
you cannot use strings to read in the operands.
I have tried:
inputFile.ignore(20, '\n')

but if that is the right way. I'm not using it correctly.
Here is my code:
/*
       ====================================================================
                                                                                SUMMARY

Read commands which will require the program to perform some operation on either one or two bit
patterns, determine the result of the operation, and output accordingly.

NOT:

Takes 1 operand and performs a bitwise logical NOT. At each position, if the operand has a 0,
the result will contain a

1. If the operand has a 1, the result will contain a 0.

Eg. operand 11010011
result 00101100

In logical operations, a 1 represents TRUE and a 0 FALSE.

AND:

Takes 2 operands and performs a bitwise logical AND. At each position, if both operand 1 and
operand 2 contain a 1, the result will be a 1. Otherwise the result is 0.

Eg. operand 1 10010010
operand 2 11001110
result 10000010

OR:

Takes 2 operands and performs a bitwise logical OR. At each position, if either operand 1 or
2 or both contain a 1, the result will contain a 1. Otherwise the result will contain a 0
(inclusive OR).

Eg. operand 1 10011001
operand 2 11100101
result 11111101

CONVERT:

Takes 1 operand and converts it to a base 10 integer. Note: we will let every bit in these
binary numbers represent part of a positive binary integer, i.e. there is no "sign" bit.
Thus we can only represent positive integers in the range from 0 thru (28 - 1).

Eg. operand 10010110
result = (1 * 2**7) + (0 * 2**6) + (0 * 2**5) + (1 * 2**4)
+ (0 * 2**3) + (1 * 2**2) + (1 * 2**1) + (0 * 2**0) = 150 in base 10

LSHIFT:

Logical Shift to Left Takes 1 operand and an integer N as input. The bit values are shifted N
positions to the left. Data "pushed off" the left end is lost. Zeroes replace the lost bits.

Eg. operand 1 11001101 N = 3
result 01101000
You may assume N is valid, i.e. 0 <= N <= 8

   ======================================================================
                                                                                ASSUMPTIONS

The binary operands will contain exactly 8 bits, where a bit is a binary digit. A byte contains
8 bits.

Check for invalid command names. Assume that the binary operands are all correctly given in the
data file.

   ======================================================================
                                                                                INPUT

From the data file binaryData.txt.

   =======================================================================
                                                                                OUTPUT

Echo print all input values. Then output in a suitable fashion the results of the operation
performed, and any necessary error messages.

*/

/* ========================================================================================*/
/*                                           HEADER FILES                              */

#include <iomanip>                                 // needed for output manipulation
#include <iostream>                    // needed for standard I/O routines
#include <fstream>
#include <string>                                 // needed for reading data from files
using namespace std;

/* ====================================================================================*/
/*                   FUNCTION                                                         /* ================================================================== */
/*            NAMED GLOBAL CONSTANTS                                                   */

    const int ARRAY_SIZE = 8;                        // array size

/* =========================================================================== */
/*       MAIN FUNCTION                                                          */
    int main (){

int numbers[ARRAY_SIZE];                        // array with 8 elements
int secondArray[ARRAY_SIZE];                    // array two with 8 elements
int thirdArray[ARRAY_SIZE];                    // array three with 8 elements
int count = 0;                                 // loop counter variable

ifstream inputFile;                           // input file stream object

// open the file
inputFile.open ("small.txt");

// exit if a fatal error occurs opening the file
if( !inputFile ){

    cout << "Error: Data file could not be opened \n";
    system ("pause");
    return (EXIT_FAILURE);

} // end of not in file if statement

// read the array

string word;

while(inputFile){

    // stores the word read in by the file
    inputFile >> word;

    if(word == "NOT"){

   cout << word << "     ";

   // This allows you to be able to read in each number one by one
   for(int i = 0; i < ARRAY_SIZE; i++){

       char letter(20);

       inputFile >> letter;
       letter = letter - '0';
       numbers[i] = static_cast<int>(letter);

       if (letter == 0){

           numbers[i] = letter + 1;
       }
       else{

           numbers[i] = letter - 1;
       }

    } // end of first for loop

    for(int i = 0; i < ARRAY_SIZE; i++){

       cout << numbers[i];
     } // end of second for loop
    } // end of if word == not check

    if(word == "AND"){

   cout << "\n\n" << word << "     ";

   // This allows you to be able to read in each number one by one
   for(int i = 0; i < ARRAY_SIZE; i++){

       //inputFile.ignore(20, '\n');

       char letter;

       inputFile.ignore(10) >> letter;
       letter = letter - '0';
       secondArray[i] = static_cast<int>(letter);

    } // end of first for loop

    for(int i = 0; i < ARRAY_SIZE; i++){

       cout << secondArray[i];
     } // end of second for loop
    } // end of if word == not check
} // end of while inputFile loop

inputFile.clear ( );
inputFile.close ( );

cout << endl;
system ("pause");
return (0);

    } // end of main function

A: Your code has already consumed the first two columns from the stream and the position of the stream is past those columns.  In turn, it isn't necessary to call ignore to move the stream position past those columns.  Besides ignore ifstream provides some additional functions that you may find useful.


Q: How do you write a script that alerts you in the Terminal like mail's "You have mail" I guess I'm looking for how to make a script to run whenever you press ENTER in bash, so that it can alert you by echoing a line about some event if an event has occurred.

A: You can use the special PROMPT_COMMAND variable, look it up in man bash.
$ PROMPT_COMMAND='echo hello'
hello
$
hello
$

Set it at the end of ~/.bashrc. I suggest you write a function and call that function in the PROMPT_COMMAND.

A: There have been tools to do this for ages, starting with the venerable 'biff'. Gnubiff looks like the most capable (it does IMAP and POP3) option in ubuntu:
http://packages.ubuntu.com/natty/gnubiff


Q: JNI Global reference to PacketWriter in smack library, how to identify the cause JNI Global referece? I am using smack library to connect to Facebook XMPP server.
In my local enviroment debug mode, memory leak sometimes happened. I have:

*

*checked the heap dump,

*found that JNI Global reference always referred to PacketWriter object in smack library,

*PacketWriter contains one thread to do output work

Question:
what caused the JNI Global reference? (of course no JNI used in the server)
Is the JNI Glabal reference caused by debug mode of the server?
I already checked the question: How to identify the cause of a JNI global reference memory leak?.
This is smack source code view:
Update
the heap dump is very big, I post the screenshot of VisualVM about heap
http://sphotos-a.ak.fbcdn.net/hphotos-ak-ash3/21927_384581804957834_1241962037_n.jpg


Q: rails/ruby "and return false" syntax I've seen this code in a rails tutorial I'm doing
def access_denied
  redirect_to login_path, :notice => "Please log in to continue" and return false
end

Before learning rails, I did a large amount of ruby research and none of the books I read covered this "and return false" syntax going on here. I can't find any mention of it in the rails syntax, is anyone able to provide a link or any explanation that would clear this up?
I don't understand the need for the "and" in here as I thought ruby would always return the last evaluated expression.

A: redirect_to login_path, :notice => "Please log in to continue" is a normal expression in Ruby that does not return false (or nil, see the source code), so program execution continues (to check the second part after AND) and return false can be executed.

A: The and is there only for you to be able to write the return false at the same line as the previous statement.
It's equivalent of doing this:
redirect_to login_path, :notice => "Please log in to continue"
return false

it's not exactly the same because with the "and" it would only return false if the redirect_to method returns something that isn't nil or false but as it almost always returns something that is not nil nor false then the right side of the statement is always executed (and false is returned).
The and in Ruby is just an alias to && and behaves exactly like it with only one difference, it has a lower precedence than all other pieces of the statement, so first it evaluates whatever is on it's left and then gets applied. Ruby also has the or which is the same as || but with a lower precedence in expressions.

A: This kind of construct used to be used with a filter, when filter return values were expected. The false would halt normal request processing.
So if a controller looked like this:
class FooController < ActionController::Base
  before_filter :access_denied
  # etc.
end

None of the controller's actions would run; this method was likely designed to be called from a filter, like:
def check_access
  return access_denied unless current_user.has_access
end

These days filter return values are ignored.
It could be used as a normal method in an action to stop processing the action and return after the redirect, so no other logic/rendering/etc. is run inside the controller.

A: Documentation on operators: Under the "Defined?, And, Or, and Not" section
Using and is useful for chaining related operations together until one of them returns nil or false.  You can use it like you showed in your question or you can also use it to short-circuit the line of code.
# Short circuit example
blog = Blog.find_by_id(id) and blog.publish!

The blog only gets .publish! called on it if the find_by_id was successful.
In your example:
def access_denied
  redirect_to login_path, :notice => "Please log in to continue" and return false
end

They are just using it to write the code more compactly on one line.
However, it is also useful for a controller action where you may be rendering based on conditionals and you don't want to get Rails "multiple renders" warning:
def show
  if something
    render :partial => 'some_partial'
  end

  render :partial => 'some_other_partial'
end

Rails will give you a warning if something returns true since you have multiple render statements being evaluated in the action.  However, if you changed it to
if something
  render :partial => 'some_partial' and return
end

it would allow you to stop the action execution.


Q: Is there a way to compare four sets of lists and retrieve the exact value? I have a small large problem. Basically, I have some sets of lists that I need to compare and extract the value from it.
brand = ["brand_1", "brand_2"]
search_type = [4, 10]

brand_search = ["brand_1", "brand_2","brand_3"]
value_search = ["value1", "value_2","value_3"]

I hope that I can explain myself.
I would like to search the brand_search to find if there's a match with brand then I need to extract exactly the value_search so that I can use the search_type to retrieve a part of the value_search.
I think this is very tricky and sketchy to do. I tried many methods but failed to extract specifically the value_search.

A: Your question isn't very clear, but I'm guessing this is what you want.
Use enumerate() to iterate through brand_search along with the indexes. When you find a match, get the corresponding element of value_search.
for i, item in enumerate(brand_search):
    if item in brand:
        value = value_search[i]
        print(value[search_type[0]:search_type[1]])


Q: How do I compare a char array from a class with another char array using the overload == operator? I have a class called Airplane with a private data member thats a char array.
// char array variable in my class
char* name{nullptr};

my goal is to compare for equality this variable and an input variable of type const char [].
my overload function looks like this:
bool Airplane::operator==(const char input_name[]) const{
    if (this->name == input_name) {
         return true;
     }
return false;
}

By overloading the == operator, I want to be able to do the following:
Airplane plane("hello");
if (plane == "hellooo") {
   // do something
}

I want to be able to create a class with a text variable like "hello" and then be able to == it to any random text I want to compare equality. Right now my code just doesnt work, it runs and then ends in the console with no errors. basically I need to compare to char arrays, one within the class the overload function is built in, and another given as input by the user. Thank you for any help.

A: As @PaulMcKenzie has rightly said, char* is not an array.
I suggest using std::string instead of char* as well as in overload as follows:
const bool Airplane::operator==(const std::string& str_to_be_compared) const {
    return this->(whatever variable stores the name of the plane) == str_to_be_compared;
}


Q: Hiding/Reshowing jQuery Dialogues I'm trying to open a jQuery dialog using AJAX. The content of the dialog is loaded from a querystring and contains server controls inside a form tag.
I have a GridView where a link in each row spawns the dialog.
The first time, the dialog loads fine, but subsequently I need to open another dialog on the page, then the first dialog will load. I can't open the same dialog subsequent times. Inspecting the DOM in Firebug shows multiple 'containers' at the end of the page. I have a GridView where one column contains a link and an empty div. I've simplified the control IDs because they're mangled by ASP.NET, but this is my code:
$('#linkId').click(function() {
    $('#panelId').dialog({
            autoOpen: true,
            height: 600,
            width: 680,
            modal: true,
            show: 'blind',
            hide: 'blind',
            title: 'More Information',
            open: function () {
                $(this).load(url).parent().appendTo("form");
            },
            close(){
                // I've also tried using these (not both at the same time)
                $(this).dialog('destroy').remove();// dialog never opens again
                $(this).dialog('disable').remove();// dialog never opens again
            }
        });
        return false;
    });
});

I've tried adding the included functions to the close event, but I get the same effect. Otherwise, when the dialog eventually opens, everything works perfectly (despite there being multiple dialog containers at the end of the page).

A: From the jq dialog api documentation:

"If you want to reuse a dialog, the easiest way is to disable the
  "auto-open" option with: $(foo).dialog({ autoOpen: false }) and open
  it with $(foo).dialog('open'). To close it, use
  $(foo).dialog('close'). A more in-depth explanation with a full demo
  is available on the Nemikor blog"


Q: Providing a common interface to SVN and CVS SVN and CVS are two very different systems that aim to address the same basic issue - source control.
They both work in distinct ways, so it's probably difficult to deal with them exactly the same.
What I'm wondering is, would it be conceivable to develop a programming library or API that exposes the same interface, but under the hood, can be set up to work with either an SVN or CVS repository?
I'm aiming to develop such a library in either .NET or Java (most likely .NET), but I wanted to get some thoughts on how feasible this would be, and if there's a better way to approach the problem.
The context of this is: I'm building a web-based service that will involve source control hosting, and I want to support both SVN and CVS so as to serve the largest amount of developers possible.

A: Personally I would ignore CVS for a new product.  My feeling would be that the enormous extra effort to coerce it into looking like SVN would be better spent on other other stuff.  I don't know your market, so I might be wrong, but that's got to be worth thinking about.

A: The MSSCCI API does something very similar:
http://alinconstantin.homeip.net/webdocs/scc/msscci.htm
The MSSCCI tries to make all source controls look the same from the perspective of the IDE.

A: viewvc lets you browse svn and cvs repositories.  maybe there is an existing product which will already do what you want?


Q: Display BigInt DataType of length 10 in Excel Sheet using PHP I want to make a excel file by fetching data from database. Every thing works fine but the phone number field return unknown value in excel sheet but it displays correct value in browser.
<?php
 include('connection.php');
    header( "Content-Type: application/vnd.ms-excel" );
    header( "Content-disposition: attachment; filename=spreadsheet.xls" );
                        $q = mysql_query("select * from members order by id desc");

                        echo 'First Name' . "\t" . 'email' . "\t" . 'Phone' . "\t". 'address' . "\t". 'Membership Number' . "\t". 'Membership Category' . "\n";

                        while($r = mysql_fetch_array($q))
                        {
                            $name = $r['name'];
                            $email = $r['email'];
                            $phone = $r['phone'];
                            $address = $r['address'];
                            $mem_num = $r['mem_num'];
                            $mem_cat = $r['mem_category'];
                        echo "$name"."\t"."$email"."\t"."$phone"."\t"."$address"."\t"."$mem_num"."\t"."$mem_cat"."\n";
                        }
                    mysql_close($con);
?>

A: I believe you are confusing data-types here. A phone number for instance, is not a number. But it's called a number! Yeah I know, because it has a lot of numbers in it, but still, it isn't a number... Why?
A phone number is indeed constructed of a set of numerals - the symbols that represent a number - but that doesn't make it a number yet. Compare letters and words; a word is constructed of a set of letters, but not every set of letters is a word. For example: dfslkwpdjkcnj is not a word, not in a language I know of at least... And if it would be a number, how would you add-up two phone numbers? Or how would you divide a phone number by another one? Would that be something like [grandma's phonenumber] / [mom's phonenumber] = [my phonenumber]?
So, to store a phone number in a database, a varchar would be a more suitable column type. For example international phone numbers start with either a + sign, or double zero (00). Both of them can not be stored in a numeral field type. The + isn't a numeral sign, or is used to designate a positive number, and will be cut off. Leading zero's in a number have no function at all, and will be cut off as well...
So bottom line; in your database, use a varchar to store a phone number, and use conversion functions to format a phone number to your liking. There are almost certainly a dozen of algorithms to be found to format a phone number to some kind of a standardized format.
Then back to your excel: your aren't creating an excel file, but a csv file, and you're giving it an excel mime-type. But that would be the same to give someone a cd and say it is a dvd. If you put the cd in a dvd player, it will almost certainly be able to play it, but it is mere luck then wisdom that it does.
Creating an excel file isn't as easy as setting the mime-type, as you can't expect the browser to know how to convert text to an excel file, as it does not know about excel's internals. So if you reaaally want to create an excel file, and set the data types of certain columns, use a library like phpExcel or any other available, if you don't want to create a library yourself that is.

A: have you tried expanding(stretching) phone column in your excel file? sometime if column is small and numbers are big, excel displays number like(1.23+09) this.
If stretching column does not work. you can convert numbers into string and then put them in excel file
sorry i can't add this in comment as i don't have privilege to comment yet.

A: If with your API you are able to format cells, that's what you would need to do.  You are storing your phone number as a BigInt instead of as a String.  I have always stored phone numbers as Strings.
Excel is interpreting your data correctly--as a number, not as text.  If you wish to continue to store your phone number as a BigInt (which I don't recommend), you would need to convert it to a String before writing it out to Excel.  Or, if your API permits, write it out to Excel as a number, but then apply cell formatting to bring it to the formatting you expect.


Q: Don't show Title FlyoutItem Shell in Drawer - xamarin forms I want to have a Tab Bar and a Drawer in the form
In this form I use Shell
I do not intend to display any Tabbar items in Drawer
now
I created the Tabbar at the bottom of the page once with the following code:
<TabBar Title="Tab bar FlyoutItem"  FlyoutDisplayOptions="AsSingleItem"  >
    <Tab Title="T1" Icon="T1.png" >
        <ShellContent ContentTemplate="{DataTemplate views: page1}" />
    </Tab>
    <Tab Title="T2" Icon="T2.png" >
        <ShellContent ContentTemplate="{DataTemplate views: page2}"/>
    </Tab>

    <Tab Title="T3" Icon="T3.png" >
        <ShellContent ContentTemplate="{DataTemplate views: page3}"/>
    </Tab>
    <Tab Title="T4" Icon="T4.png" >
        <ShellContent ContentTemplate="{DataTemplate views: page4}"/>
    </Tab>
    <Tab Title="T5" Icon="Home.png" >
        <ShellContent ContentTemplate="{DataTemplate views: page5}"/>
    </Tab>
</TabBar>

Output :
View image
And once again I used Flyout instead of tabbar (code below):
< FlyoutItem Title=”Tab bar FlyoutItem”  FlyoutDisplayOptions=”AsSingleItem”  >
    <Tab Title=”T1” Icon=”T1.png” >
        <ShellContent ContentTemplate=”{DataTemplate views: page1}” />
    </Tab>
    <Tab Title=”T2” Icon=”T2.png” >
        <ShellContent ContentTemplate=”{DataTemplate views: page2}”/>
    </Tab>

    <Tab Title=”T3” Icon=”T3.png” >
        <ShellContent ContentTemplate=”{DataTemplate views: page3}”/>
    </Tab>
    <Tab Title=”T4” Icon=”T4.png” >
        <ShellContent ContentTemplate=”{DataTemplate views: page4}”/>
    </Tab>
    <Tab Title=”T5” Icon=”Home.png” >
        <ShellContent ContentTemplate=”{DataTemplate views: page5}”/>
    </Tab>
</ FlyoutItem >

OUTPUT :
View image
I created the Drawer using the following code :
    <FlyoutItem FlyoutDisplayOptions="AsMultipleItems">

    <Tab Title="T6" Icon="email.png" >
        <ShellContent ContentTemplate="{DataTemplate views:page6}" />
    </Tab>
    <Tab Title="T7" Icon="email.png" >
        <ShellContent ContentTemplate="{DataTemplate views:page7}"/>
    </Tab>
    <Tab Title="T8" Icon="email.png" >
        <ShellContent ContentTemplate="{DataTemplate views:page8}"/>
    </Tab>
    <Tab Title="T9" Icon="email.png" >
        <ShellContent ContentTemplate="{DataTemplate views:page9}"/>
    </Tab>

</FlyoutItem>

This time Drawer is displayed but its Title Of Tabbar is also displayed in Drawer as shown in the figure.
OUTPUT :
View image
Please help me how I can not display the Title in Drawer.
Thank

A: I'M find
The

Shell.FlyoutBehavior="Flyout"

must be added to the TabBar
I share the code below :
<TabBar Title="Tab bar FlyoutItem"  Shell.FlyoutBehavior="Flyout" FlyoutDisplayOptions="AsSingleItem"  >
    <Tab Title="T1" Icon="T1.png" >
        <ShellContent ContentTemplate="{DataTemplate views:T1}" />
    </Tab>
    <Tab Title="T2" Icon="T2.png" >
        <ShellContent ContentTemplate="{DataTemplate views:T2}"/>
    </Tab>

    <Tab Title="T3" Icon="T3.png" >
        <ShellContent ContentTemplate="{DataTemplate views:T3}"/>
    </Tab>
    <Tab Title="T4" Icon="T4.png" >
        <ShellContent ContentTemplate="{DataTemplate views:T4}"/>
    </Tab>
    <Tab Title="T5" Icon="Home.png" >
        <ShellContent ContentTemplate="{DataTemplate views:HomePage}"/>
    </Tab>

</TabBar>

<FlyoutItem FlyoutDisplayOptions="AsMultipleItems" Shell.TabBarIsVisible="True">

    <Tab Title="T6" Icon="email.png" >
        <ShellContent ContentTemplate="{DataTemplate views:T6}" />
    </Tab>
    <Tab Title="T7" Icon="email.png" >
        <ShellContent ContentTemplate="{DataTemplate views:T7}"/>
    </Tab>
    <Tab Title="T8" Icon="email.png" >
        <ShellContent ContentTemplate="{DataTemplate views:T8}"/>
    </Tab>
    <Tab Title="T9" Icon="email.png" >
        <ShellContent ContentTemplate="{DataTemplate views:T9}"/>
    </Tab>

</FlyoutItem>


Q: Azure portal bash file structure for ssh file I ran a bash command from my azure subscription on portal.azure to create a ssh key and it asked me to give the name of the new file but at a location that I am not able to find on my machine. It gave a default path as /home/username/.ssh/id_rsa
I cant seem to find a home directory on my machine.
It went ahead and created it but I am so confused as to where it placed it.
Can someone shed some light on this. Do the bash commands run on portal.azure know the file structure of my machine and if it didnt put it under my machine, where did it place it?
ssh-keygen -m PEM -t rsa -b 4096
Generating public/private rsa key pair.
Enter file in which to save the key (/home/username/.ssh/id_rsa):

A: When using the bash command line in the Azure portal, it means you use the Azure Cloud Shell, not your local machine. So the SSH key you created is stored in the cloud shell with the path /home/username/.ssh/, not the local machine.
Here is a screenshot that creates the SSH key in the Azure Cloud Shell:


Q: Why is JApplet showing a blank gray screen? So I've been trying to figure out why my JApplet is starting and giving no errors but nothing is showing up. I have an init() method that calls setup_layout(), but I think I may have done something wrong the layouts. Anyone help?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class Assignment8 extends JApplet implements ActionListener
{
    public static final int WIDTH = 500;
    public static final int HEIGHT = 500;
    public static final int NUMBER_OF_DIGITS = 30;

    private JTextArea operand, result;
    private double answer = 0.0;
    private JButton sevenB, eightB, nineB, divideB, fourB, fiveB, sixB, multiplyB, oneB, twoB, threeB, subtractB,
    zeroB, dotB, addB, resetB, clearB, sqrtB, absB, expB;

   /** public static void main(String[] args)
    {
        Assignment8 aCalculator = new Assignment8( );
        aCalculator.setVisible(true);
    }**/

    public void init( )
    {
        setup_layout();
    }

    private void setup_layout() {
        setSize(WIDTH, HEIGHT);

        JPanel MainPanel = new JPanel();
        JPanel buttonPanel = new JPanel();
        JPanel calcPanel = new JPanel();
        JPanel textPanel = new JPanel ();

        buttonPanel.setLayout(new GridLayout(3, 4));
        calcPanel.setLayout(new GridLayout(3, 3));
        textPanel.setLayout(new FlowLayout());
        MainPanel.setLayout(new BorderLayout());
        MainPanel.setBackground(Color.red);

        operand = new JTextArea();
        result = new JTextArea();
        operand.setEditable(false);
        result.setEditable(false);
        textPanel.add(operand);
        textPanel.add(result);

        sevenB = new JButton("7");
        eightB = new JButton("8");
        nineB = new JButton("9");
        divideB = new JButton("/");
        fourB = new JButton("4");
        fiveB = new JButton("5");
        sixB = new JButton("6");
        multiplyB = new JButton("*");
        oneB = new JButton("1");
        twoB = new JButton("2");
        threeB = new JButton("3");
        subtractB = new JButton("-");
        zeroB = new JButton("0");
        dotB = new JButton(".");
        addB = new JButton("+");
        resetB = new JButton("Reset");
        clearB = new JButton("Clear");
        sqrtB = new JButton("Sqrt");
        absB = new JButton("Abs");
        expB = new JButton("Exp");

        sevenB.addActionListener(this);
        eightB.addActionListener(this);
        nineB.addActionListener(this);
        divideB.addActionListener(this);
        fourB.addActionListener(this);
        fiveB.addActionListener(this);
        sixB.addActionListener(this);
        multiplyB.addActionListener(this);
        oneB.addActionListener(this);
        twoB.addActionListener(this);
        threeB.addActionListener(this);
        subtractB.addActionListener(this);
        zeroB.addActionListener(this);
        dotB.addActionListener(this);
        addB.addActionListener(this);
        resetB.addActionListener(this);
        clearB.addActionListener(this);
        absB.addActionListener(this);
        expB.addActionListener(this);
        sqrtB.addActionListener(this);

        buttonPanel.add(sevenB);
        buttonPanel.add(eightB);
        buttonPanel.add(nineB);
        buttonPanel.add(fourB);
        buttonPanel.add(fiveB);
        buttonPanel.add(sixB);
        buttonPanel.add(oneB);
        buttonPanel.add(twoB);
        buttonPanel.add(threeB);
        buttonPanel.add(zeroB);
        buttonPanel.add(dotB);

        calcPanel.add(subtractB);
        calcPanel.add(multiplyB);
        calcPanel.add(divideB);
        calcPanel.add(sqrtB);
        calcPanel.add(absB);
        calcPanel.add(expB);
        calcPanel.add(addB);
        calcPanel.add(resetB);
        calcPanel.add(clearB);

        MainPanel.add(buttonPanel);
        MainPanel.add(calcPanel);
        MainPanel.add(textPanel);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e)
    {
        try
        {
            assumingCorrectNumberFormats(e);
        }
        catch (NumberFormatException e2)
        {
            result.setText("Error: Reenter Number.");
        }
        catch (DivideByZeroException e1) {
            result.setText("Error: CANNOT Divide By Zero. Reenter Number.");
        }
    }

    //Throws NumberFormatException.
    public void assumingCorrectNumberFormats(ActionEvent e) throws DivideByZeroException
    {
        String actionCommand = e.getActionCommand( );

        if (actionCommand.equals("1"))
        {
            int num = 1;
            operand.append(Integer.toString(num));
        }
        else if (actionCommand.equals("2"))
        {
            int num = 2;
            operand.append(Integer.toString(num));
        }
        else if (actionCommand.equals("3"))
        {
            int num = 3;
            operand.append(Integer.toString(num));
        }
        else if (actionCommand.equals("4"))
        {
            int num = 4;
            operand.append(Integer.toString(num));
        }
        else if (actionCommand.equals("5"))
        {
            int num = 5;
            operand.append(Integer.toString(num));
        }
        else if (actionCommand.equals("6"))
        {
            int num = 6;
            operand.append(Integer.toString(num));
        }
        else if (actionCommand.equals("7"))
        {
            int num = 7;
            operand.append(Integer.toString(num));
        }
        else if (actionCommand.equals("8"))
        {
            int num = 8;
            operand.append(Integer.toString(num));
        }
        else if (actionCommand.equals("9"))
        {
            int num = 9;
            operand.append(Integer.toString(num));
        }
        else if (actionCommand.equals("0"))
            {
                int num = 0;
                String text = operand.getText();
                //double check = stringToDouble(text);
                if(text.isEmpty()||text.contains(".")) {
                    operand.append(Integer.toString(num));
                }
            }
        else if (actionCommand.equals("."))
        {
            String text = operand.getText();
            if(!text.contains(".")) {
                operand.append(".");
            }
        }

        else if (actionCommand.equals("+"))
        {
            answer = answer + stringToDouble(operand.getText( ));
            result.setText(Double.toString(answer));
            operand.setText("");
        }
        else if (actionCommand.equals("-"))
        {
            answer = answer - stringToDouble(operand.getText( ));
            result.setText(Double.toString(answer));
            operand.setText("");

        }
        else if (actionCommand.equals("*"))
        {
            answer = answer * stringToDouble(operand.getText( ));
            result.setText(Double.toString(answer));
            operand.setText("");

        }
        else if (actionCommand.equals("/"))
        {
            double check = stringToDouble(operand.getText());
            if(check >= -1.0e-10 && check <= 1.0e-10 ) {
                throw new DivideByZeroException();
            }
            else {
                answer = answer / stringToDouble(operand.getText( ));
                result.setText(Double.toString(answer));
                operand.setText("");
            }

        }
        else if (actionCommand.equals("Sqrt"))
        {
            double check = stringToDouble(result.getText());
            if(check < 0 ) {
                throw new NumberFormatException();
            }
            else {
                answer = Math.sqrt(stringToDouble(result.getText( )));
                result.setText(Double.toString(answer));
                operand.setText("");
            }

        }
        else if (actionCommand.equals("Abs"))
        {
            answer = Math.abs(stringToDouble(result.getText( )));
            result.setText(Double.toString(answer));
            operand.setText("");

        }
        else if (actionCommand.equals("Exp"))
        {
            answer = Math.pow(stringToDouble(result.getText( )),stringToDouble(operand.getText( )));
            result.setText(Double.toString(answer));
            operand.setText("");
        }
        else if (actionCommand.equals("Reset"))
        {
            answer = 0.0;
            result.setText("");
            operand.setText("");
        }
        else if (actionCommand.equals("Clear"))
        {
            operand.setText("");
        }
        else
            result.setText("Unexpected error.");
     }

    //Throws NumberFormatException.
    private static double stringToDouble(String stringObject)
    {
        return Double.parseDouble(stringObject.trim( ));
    }

   //Divide by Zero Exception Class
   public class DivideByZeroException extends Exception {
        DivideByZeroException() {
        }
   }

}

A: You never add MainPanel to the applet itself.
i.e.,
add(MainPanel);

Also, since MainPanel uses BorderLayout, you will need to add the subPanels with a BorderLayout.XXX constant. i.e.,
change this:
  MainPanel.add(buttonPanel);
  MainPanel.add(calcPanel);
  MainPanel.add(textPanel);

to:
  MainPanel.add(buttonPanel, BorderLayout.CENTER);
  MainPanel.add(calcPanel, BorderLayout.PAGE_END); // wherever you want to add this
  MainPanel.add(textPanel, BorderLayout.PAGE_START);

Note that your code can be simplified greatly by using arrays or Lists.
Or could simplify it in other ways, for instance:
public void assumingCorrectNumberFormats(ActionEvent e)
     throws DivideByZeroException {
  String actionCommand = e.getActionCommand();
  String numbers = "1234567890";

  if (numbers.contains(actionCommand)) {
     operand.append(actionCommand);

     // if you need to work with it as a number
     int num = Integer.parseInt(actionCommand);
  }

Myself, I'd use a different ActionListeners for different functionality, for instance one ActionListener for numeric and . entry buttons and another one for the operation buttons.


Q: Views not laying out properly for iPhone 4 I have laid out my ViewControllers in Storyboard using Auto Layout, and everything looks perfect on an iPhone 5. Now I'm testing for iPhone 4 and things are not in their correct position. For example, I placed a UIView at the bottom of its parent UIView. It's width is the screen width and its height is 100. It shows up nicely on an iPhone 5 but doesn't appear at all on an iPhone 4 (I think it's because it's drawn at the height it should for an iPhone 5 which is too far below the screen for a 4)
If I'm using Auto Layout, do I still need to make adjustments to my Views? If so, what's the point of using Auto Layout at all?

A: Here is the approach to make your layouts fit to retina & non retina form factors.
I am not saying these are the rules, but I follow this approach & hardly get any conflicts which is difficult to resolve.

*

*First & foremost : Always try to design your storyboard on non-retina form factor (I mean in your case design it on iPhone4 size & then apply retina-Form Factor & verify how it fits on iPhone5 size.).

*Definitely your view at the bottom of its parent will be having a fix constraint for "Y" position. Usually, you need to make a relative constraint. So when you show it up on iPhone4, the Y & the height might be going beyond the maximum Y axis value.

*Try checking these values for your layout in Assistant Editor like topSpace, leadingSpace, trailingSpace, bottomSpace .

*AutoLayout doesn't mean that it will fit to your needs, however it adjusts the component accordingly.

*In case of any warning in Storyboard, try using the help & suggestion provided like, add missing constraint or adjust frame to suggested
Storyboard will never behave in the same manner for each & every screen or view your design. You need to practise it more & more & you get to know how to add constraints.
Hope that helps.


Q: Print inner text of a HtmlContent in a razor view (MVC4) Using MVC, look at this example where we have the following HTML code:

Duma

Duma

I would like that print only the content of the tags, as: Duma Duma, removing the image, tags and showing only the text (as innerText)
I tried using Html.Raw() but it's not worked. Also I was reading about the class TabBuilder and creating a Html extension method, but I don't have idea about how to implemeted in my razor view.

A: You could make a string extension to strip the Html tags.
public static class StringExtensions
{
    public static string StripHtml (this string inputString)
    {
       return Regex.Replace
         (inputString, "<.*?>", string.Empty);
    }
}

Then use it in your view
@myHtmlString.StripHtml()

You might need to declaring a using statement for the StringExtensions class or add it to the Web.Config file in your Views folder
@using My.Extensions.Namespace

OR
<system.web>
    <pages>
      <namespaces>
        <add namespace="My.Extensions.Namespace" />
      </namespaces>
    </pages>
</system.web>

You could also make a Html Helper Extension
public static class HtmlExtensions
{
    public static string StripHtml (this System.Web.Mvc.HtmlHelper helper, string htmlString)
    {
       return Regex.Replace
         (htmlString, "<.*?>", string.Empty);
    }
}

You can use this in your view like this
@Html.StripHtml(myHtmlString)

You will still need to add a reference to the namespace for your extension methods like above. Either adding to your Web.Config in your Views folder or adding a using statement in your view. The differences here is that adding it to your Web.Config file you will be able to use this extension method in all your views without adding the using statement.


Q: Finding end-date of last sickness incident in R I have a file which records when someone was sick, and when they recovered. Some records have several incidents of sickness, and I am trying to add a new column to each row which is "date last sickness ended" (or "date record began" if NA). There are 10,000s of records, and there can be 10+ incidents of sickness. But in the simplest example, I am trying to go from this:
| ID      | RecordBegins | SickStartDate | SickEndDate |

| person1 | 1990-01-01 | 2017-03-04 | 2017-07-01 |

| person1 | 1990-01-01 | 2018-11-01 | 2019-02-04 |

to this:

| ID      | RecordBegins | SickStartDate | SickEndDate | EndLastSick

| person1 | 1990-01-01 | 2017-03-04 | 2017-07-01 | 1990-01-01

| person1 | 1990-01-01 | 2018-11-01 | 2019-02-04 | 2017-07-01

I'm new to R, and self-taught. I've been trying to stay in the tidyverse world, but am open to other approaches.
I can code for what I want when there's only one unique person in the dataset using the code below. I've tried extending it using group_by() when I expand the dataset to more than one person, but I can't think of a way to make it work.
sick <-tribble(
  ~ID, ~RecordBegins, ~SickStartDate, ~SickEndDate,
  "person1", as.Date("1990-01-01"), as.Date("2017-03-04"), as.Date("2017-07-01"),
  "person1", as.Date("1990-01-01"), as.Date("2018-11-01"), as.Date("2019-02-04"),
)

var1 <- sick$SickEndDate %>% sort(decreasing = TRUE) # place date of last sick at position [1]
var1[1] = sick$`RecordBegins`[1] # replace date of last sick with record start date
var1 <- sort(var1) # re-sort so in date order
sick <- mutate(sick, startExposure = var1)

However that feels pretty clunky, and I can't think of a way to get it to work for when scaling up to more than one person, for example:
sick <-tribble(
  ~ID, ~RecordBegins, ~SickStartDate, ~SickEndDate,
  "person1", as.Date("1990-01-01"), as.Date("2017-03-04"), as.Date("2017-07-01"),
  "person1", as.Date("1990-01-01"), as.Date("2018-11-01"), as.Date("2019-02-04"),
  "person2", as.Date("1995-01-01"), as.Date("2014-10-07"), as.Date("2017-01-04"),
  "person2", as.Date("1995-01-01"), as.Date("2017-11-01"), as.Date("2017-11-23"),
)

A: You can group by ID, and make use of lag, if I'm interpreting your question correctly!
library(dplyr)

sick %>%
    arrange(ID, SickStartDate) %>%
    group_by(ID) %>%
    mutate(EndLastSick = case_when(
        # if this is the first record for this person, use RecordBegins
        is.na(lag(SickEndDate)) ~ RecordBegins,
        # otherwise, get the most recent SicKEndDate
        TRUE ~ lag(SickEndDate)
    ))

## A tibble: 4 x 5
## Groups:   ID [2]
#  ID      RecordBegins SickStartDate SickEndDate EndLastSick
#  <chr>   <date>       <date>        <date>      <date>
#1 person1 1990-01-01   2017-03-04    2017-07-01  1990-01-01
#2 person1 1990-01-01   2018-11-01    2019-02-04  2017-07-01
#3 person2 1995-01-01   2014-10-07    2017-01-04  1995-01-01
#4 person2 1995-01-01   2017-11-01    2017-11-23  2017-01-04

Data:
sick <-tribble(
  ~ID, ~RecordBegins, ~SickStartDate, ~SickEndDate,
  "person1", as.Date("1990-01-01"), as.Date("2017-03-04"), as.Date("2017-07-01"),
  "person1", as.Date("1990-01-01"), as.Date("2018-11-01"), as.Date("2019-02-04"),
  "person2", as.Date("1995-01-01"), as.Date("2014-10-07"), as.Date("2017-01-04"),
  "person2", as.Date("1995-01-01"), as.Date("2017-11-01"), as.Date("2017-11-23"),
)

A: This is similar to @heds1's answer but using only lag function.
library(dplyr)

sick %>%
  arrange(ID, SickStartDate, SickEndDate) %>%
  group_by(ID) %>%
  mutate(EndLastSick = lag(SickEndDate, default = first(RecordBegins))) %>%
  ungroup

#   ID    RecordBegins SickStartDate SickEndDate EndLastSick
#  <chr>   <date>       <date>        <date>      <date>
#1 person1 1990-01-01   2017-03-04    2017-07-01  1990-01-01
#2 person1 1990-01-01   2018-11-01    2019-02-04  2017-07-01
#3 person2 1995-01-01   2014-10-07    2017-01-04  1995-01-01
#4 person2 1995-01-01   2017-11-01    2017-11-23  2017-01-04


Q: Error: [$injector:unpr] Unknown provider: GetOrdersProvider <- GetOrders <- OrderController I want to do get post actions on different URLs. When I tried to write different factories I guess it could recogine the other factory.
Service.js
var app = angular.module("ServiceApp", ["ngResource"]);

    app.factory('GetPortfolios', function ($resource) {
    return $resource("http://localhost:61347/api/PortfolioManager/GetPortfolios/", {}, {
    });

    app.factory('GetOrders', function ($resource) {
        return $resource("http://localhost:61347/api/PortfolioManager/GetPortfolioOrders/");
    });
});

App.js
var app = angular.module("UiApp", ["ServiceApp"]);

app.controller("PortFolioController", function ($scope, GetPortfolios) {
    $scope.Portfolios = GetPortfolios.query({ pmid: 2 });
    console.log($scope.Portfolios);
});

app.controller("OrderController", function ($scope, GetOrders) {
    $scope.Orders = GetOrders.query({ id: 25 });
    console.log(Orders);
});

A: Inside your Service.js, first factory is missing the closing }) paranthesis, check the updated Service.js
var app = angular.module("ServiceApp", ["ngResource"]);

app.factory('GetPortfolios', function ($resource) {
    return $resource("http://localhost:61347/api/PortfolioManager/GetPortfolios/", {}, {});
});

app.factory('GetOrders', function ($resource) {
    return $resource("http://localhost:61347/api/PortfolioManager/GetPortfolioOrders/");
});


Q: Java Generics: Can you instantiate an object of type parameter inside class constructor? In the code segment below, I want to create the array object inside the GenericStack class constructor.
I understand why this is a problem. As per my understanding, "T" can be any class as far as the compiler is concerned. This class T can be an abstract class and hence cannot be instantiated. For example, java.lang.Number class is an abstract class and I could very well pass java.lang.Number for T.
My question now is the following:
Is there a way to tell the compiler (by some bounded parameters or perhaps something else) that the class that I am going to pass in place of T will be a concrete class that can be instantiated ? I know that I could easily create the array inside the main and then pass a reference but I find that to be a bit cluttered approach to implementing such requirement.
public class GenericStack<T> {

    //Data for the stack is an array but can be changed to list.
    public static final int stackSize = 10;
    private T[] stackData;
    private int tos;

    public GenericStack(int size) {
        stackData = new T[size];  // This line will error out
        tos = -1;
    }

    public T pop() {
        try {
            return stackData[tos--];
        } catch (Exception e) {
            System.out.println("Stack empty.Cannot POP from an empty stack.");
            return null;
        }
    }

    public void push(T stackObj) {
        try {
            stackData[++tos] = stackObj;
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Stack is full. Cannot push a element into a full stack.");
        }
    }

    public static void main(String[] args) {
        GenericStack<Integer> intStack = new GenericStack<Integer>(GenericStack.stackSize);
        GenericStack<String> stringStack = new GenericStack<String>(GenericStack.stackSize);
    }
}

A: You have to do something like this.
public GenericStack(int size) {
      stackData = new Object[size];
      tos = -1;
 }

Then later
@SuppressWarning("unchecked")
public T pop() {
 // check stack state
 return (T)stackData[++tos];
}


Q: No kvm related group, but module exists I have installed qemu from source and /dev/kvm and kvm-intel module exist. However, there is no kvm or libvirt group in order to add users.
$ grep virt /etc/group
$ grep kvm /etc/group
$
$ ls -l /dev/kvm
crw-rw----+ 1 root root 10, 232 ژوئن  20 12:13 /dev/kvm
$ lsmod | grep kvm
kvm_intel             217088  0
kvm                   598016  1 kvm_intel
irqbypass              16384  1 kvm
$ sudo modprobe kvm_intel
$

Currently, when the user wants to use -enable-kvm, he gets a permission denied error
$ qemu-system-x86_64 -m 4000 -smp cores=2 -hda win7_64_snap_new.img -boot c -usbdevice tablet -enable-kvm
qemu-system-x86_64: -usbdevice tablet: '-usbdevice' is deprecated, please use '-device usb-...' instead
Could not access KVM kernel module: Permission denied
qemu-system-x86_64: failed to initialize KVM: Permission denied

A: It’s up to you to create the group and set it up for KVM.
sudo addgroup kvm

will create the group,
sudo adduser ${USER} kvm

will add you to the group, and creating a file in /etc/udev/rules.d containing
KERNEL=="kvm", GROUP="kvm", MODE="0660"

will ensure that members of the kvm group can access the KVM device node. (Name the file 40-permissions.rules to match the linked instructions.)
The udev rules might not be taken into account unless you unload and reload the KVM modules, but you don’t need to do that:
sudo chown root:kvm /dev/kvm
sudo chmod 0660 /dev/kvm

will set the device node up appropriately for the time being.


Q: java regex extract information out of brackets i cant figure out how i manage to solve the problem of getting information out of square brackets as well as the normal ones. I want the content of them both.
i tried:
Pattern p = Pattern.compile("\\[[^\\]]*\\]");
Pattern p1 = Pattern.compile("\\[|\\([^\\)]*|[^\\]]*\\]|\\)");
Pattern p2 = Pattern.compile("\\[|\\([^{\\]|\\)}]*\\]|\\)");

p works perfectly for the squared ones only and then i tried to add the normal braces, but no success.  a sample of a string would be
"(info1) something-uninteresting [info2] s.u. [info3] s.u. (info4)"

A: Try the following:
[\\[(][^\\])]*[\\])]

A: Try the following:
(\\(.*?\\)|\\[.*?\\])*?


Q: MVC Database to list with id reference I'm writing an MVC application and want to query my database with a search parameter and put all of the results into a list. Right now my code to try this looks like:
Character character = db.Characters.ToList().Find(User.Identity.GetUserId());

Which is throwing up a error. Is there a way I can do this? Break it down into two statements for example? I tried
Character character = db.Characters.Find(User.Identity.GetUserId());
character = character.ToList();

but that isn't working either.

A: When using the extension method Find() you must be sure that in your model you have the attribute [Key] in the property representing your Id (primary key in your table).
And you can try like this:
Character character = db.Characters.Find(User.Identity.GetUserId());

The line above will work but not this one character= character.ToList(); because you declare character as an object and you can't assign it to a list of object in your case Character
If you want it to work, you can do something like this:
 var myCharacters =db.Characters.Where(c=>c.someField=="someValue");
 List<Character> myList = myCharacters.ToList();

Hope it will help.


Q: knitted markdown displayed correctly on browser/viewer but not shown properly inside shiny I have learnt to write markdown in RStudio and able to preview using browser/viewer by compiling the code. But when the same MD is shown inside a shiny app, although most of them shown correctly (including plots), some features like tab, TOC, plot captions etc are not shown inside shiny app.
The minimal code is produced here:
---
title: "Title"
output:
html_document:
    toc: TRUE
    toc_float:
      collapsed: FALSE
      smooth_scroll: FALSE
---

# Data Analysis {.tabset .tabset-fade .tabset-pills}

## Sub data Analysis

This section provides ...

I display the above code inside a shiny app server using:
output$markdown <- renderUI({
    HTML(markdown::markdownToHTML('mymd.md'))
    #HTML(rmarkdown::render(knit('mymd.Rmd')))
    #includeHTML("shinybody.html")
    })

and in ui, I am using uiOutput:
 mainPanel(
       uiOutput('markdown'))

Although shiny app display plots and text correctly, features like toc, tabs are not appearing properly. I cross checked by directly compiling md inside viewer/browser it displays correctly.
Any hand please..

A: ---
title: '[®γσ, ENG LIAN HU](https://beta.rstudioconnect.com/content/3091/ryo-eng.html)'
subtitle: 'Personal Profile'
author: '[®γσ, Lian Hu](https://englianhu.github.io/)  ®'
date: "10/22/1984"
output:
      html_document:
        number_sections: yes
        toc: yes
        toc_depth: 4
        toc_float:
          collapsed: yes
          smooth_scroll: yes
        code_folding: hide
---

Changed yaml to below :
---
title: '[®γσ, ENG LIAN HU](https://beta.rstudioconnect.com/content/3091/ryo-eng.html)'
subtitle: 'Personal Profile'
author: '[®γσ, Lian Hu](https://englianhu.github.io/)  ®'
date: "10/22/1984"
    output:
      html_document:
        number_sections: yes
        toc: yes
        toc_depth: 4
        code_folding: hide
---

figure 1 shows the collapsable menu as a line

figure 2 shows the tittle content at top


Q: Maximizing a double integral under a PDE constraint The following problem appears in a model that I developed to try to find the optimal mechanism by which an international institution could reward developing countries for their efforts to subsidize renewable energies. We have an exogenously given probability density function $f(x,y)$ in whose support we have that $x>0$ and $y>1$. The problem consists of finding the real-valued functions $s(x,y), R(x,y)$ that maximize:
\begin{equation}
\int_{x=0}^{\infty} \int_{y=1}^{\infty} s(x,y)^{\frac{1}{y-1}} x f(x,y) \quad dy dx
\end{equation}
subject to the following three constraints. Firstly, there is a PDE constraint which must hold $\forall x>0$ and $\forall y>1$:
\begin{equation}
\frac{-x}{(y-1)} s^{\frac{1}{y-1}} (\frac{1}{(y-1)^{2}}log(s) \frac{\partial s}{\partial x} +\frac{\partial s}{\partial y})+ \frac{1}{(y-1)^{2}}log(s) \frac{\partial R}{\partial x}+\frac{\partial R}{\partial y}=0
\end{equation}
Secondly, there is the following pointwise constraint, which must also hold $\forall x>0$ and $\forall y>1$
\begin{equation}
    R(x,y) \geq \frac{x}{y} s(x,y)^{\frac{y}{y-1}}
\end{equation}
Thirdly, there is the following constraint:
\begin{equation}
\int_{x=0}^{\infty} \int_{y=1}^{\infty} R(x,y) f(x,y) \quad dy dx =G
\end{equation}
where $G$ is an exogenously given positive number.
Is there any literature studying this kind of problem? Is there any way to reduce the problem to a set of differential equations like the Euler-Lagrange equations in the calculus of variations or the Hamilton-Jacobi-Bellman equations in control theory?


Q: How to remove VIM as my Mac editor vs sublime How to remove VIM (completely) and change my mac command line editor to sublime?
I've spent the last three hours reading the same links on "how to remove VIM" only to get "how to remove MacVIM and reinstall it fresh" Or "How to remove Vim so I can reinstall it on Ubuntu"
My old laptop was fortunate to have a friend remove it but my new machine still has it installed.
I wish VIM would die in "words redacted to excessive profanity" dumpster fire while a hobo "words redacted to excessive profanity" to put out the fire
I've lost way too many hours trying to learn that outdated neckbeard elvish piece of UX trash so I want it gone. No, I'm not touching emacs.
Please tell me there is a way I can switch to sublime or am I permanently cursed to have this confusing black screen of death pop up when I try to git push or git tag stuff?
My original goal was to tag a git and push it but vim comes up and I can't figure out how to speak elvish.
I've been using PyCharm for a few years and love the interface but I need to dig deeper and a TDD Django book for class uses the terminal, it wants me to git -a "comments" so I need your advice.
So now I can't learn TDD Django because vim, MacVim and eMacs users flood the internet but I can't remove it nor figure out how to work it.
I've tried brew uninstall macvim which doesn't work because I have vim not macvim
I also tried sudo uninstall vim no luck as this is zsh mac not ubuntu
I tried brew uninstall vim to get No available formula or cask with the name "vim"
I've searched SO five times and keep getting the same links.
Alternates I've tried
brew uninstall ruby vim
per this post https://superuser.com/questions/1096438/brew-upgrade-broke-vim-on-os-x-dyld-library-not-loaded  I tried, no luck.
brew uninstall --ignore-dependencies perl
brew uninstall vim
brew install vim

I'm not installing an app to remove another one, thanks but no thanks Nektony.

I don't know how to sidestep VIM, my solution for most things is to google it for a while and try a few things. If that doesn't work I unwind the changes in git with PyCharm and look for more help on StackOverflow.
Unless you know how to solve this it's like telling someone to get to a village following the Hindi roadsigns when they speak Russian.
I per the comments I clicked How can I make Sublime Text the default editor for Git? I also tried git config --global core.editor "subl -n -w" which kinda helps as it flashes scrolls past a bunch of menus but it didn't open sublime.

A: You don't have to remove Vim from your machine. Instead, tell your system and your tools to use Sublime Text as default editor. After you have followed that tutorial, which I must point out is part of Sublime Text's documentation, you should have a system-wide subl command that you can use instead of vim. For that, you need to add those lines to your shell configuration file:
export EDITOR=subl
export VISUAL=subl

which will be honoured by basically every CLI program susceptible to open a file in a text editor.
You can even add the following for good measure:
export GIT_EDITOR=subl


Q: How do you decrement time for minutes seconds hundredths? Suppose you wanted to set a timer to whatever time you want will be displayed in the form 00:00:00 minutes, seconds, and hundredths. How would you go about doing so? Please any help is greatly appreciated.
Here is the link in JSFiddle:
https://jsfiddle.net/mxpuejvz/2/
  function decrement(){
           var time = 600;
           var mins = parseInt((time / 100) / 60);
           var secs = parseInt((time / 100) % 60);
           var hundredths = parseInt(time % 100);
           if(mins < 10) {
              mins = "0" + mins;
           }

           if(secs < 10) {
              secs = "0" + secs;
           }

           if(hundredths < 10) {
              hundredths = "0" + hundredths;
           }

           document.getElementById("output").innerHTML = mins + ":" + secs + ":" + hundredths;
           if (hundredths === 0){
              if(time ===0){
                 clearInterval(countdownTimer);
                 document.getElementById("output").innerHTML = "Time's Up.";
              }else{
                 time--;
              }
              var countdownTimer = setInterval('decrement()', 10)
      }
    }
  }

A: Three issues appear to need attention.

*

*"time to go" needs to be stored outside the screen update function and decremented or calculated each time the screen is updated.

*using parseInt to convert numbers to integer numbers is regarded as a hack by some. Math.floor() or integer calculation can be alternatives.

*Timer call backs are not guaranteed to made exactly on time: counting the number of call backs for a 10msec time does not give the number of 1/100ths of elapsed time.

The following code is an example of how it could work, minus any pause button action.
var countdownTimer;
var endTime;
var counter = 0;  // ** see reply item 3. **

function startCountDown( csecs)   // hundredths of a second
{   endTime = Date.now() + 10*csecs; // endTime in millisecs
    decrement();
    countdownTimer = setInterval(decrement, 10);
    counter = 0; // testing
}

function decrement()
{   var now, time, mins, secs, csecs, timeStr;

    ++ counter; // testing

    now = Date.now();
    if( now >= endTime)
    {   time = 0;
        timeStr = "Times up! counter = " + counter;
        clearInterval( countdownTimer);
    }
    else
    {   time = Math.floor( (endTime - now)/10); // unit = 1/100 sec
        csecs = time%100;
        time = (time-csecs)/100; // unit = 1 sec
        secs = time % 60;
        mins = (time-secs)/60;   // unit = 60 secs
        timeStr =
          ( (mins < 10)  ? "0" + mins : mins) + ":" +
          ( (secs < 10)  ? "0" + secs : secs) + ":" +
          ( (csecs < 10) ? "0" + csecs : csecs);
    }
    document.getElementById("output").innerHTML=timeStr;
}

The argument to startCountDown gives the number of 1/100ths of second for the count down. If the counter result is the same as the argument,try swapping browser tabs and back again during the countdown.

HTML to test:
<button type="button" onclick="startCountDown(600)">start</button>
<div id="output">
</div>


Q: OCaml's let polymorphism implementation I'm confused about let polymorphism in OCaml.
Consider the following code:
A:
let f = (fun v -> v) in
((f 3), (f true))

B:
let f = (fun v -> v) in
((fun g ->
    let f = g in
    f) f)

C:
let f = (fun v -> v) in
((fun g ->
    let f = g in
    ((f 3), (f true))) f)

For A and B, there is no problem. But for C, OCaml reports error:
Error: This expression has type bool but an expression was expected of type
         int

So for A, when evaluating ((f 3), (f true)), f's type is 'a -> 'a,
for B, when evaluating let f = g in f, f's type is 'a -> 'a.
But for C, when evaluating ((f 3), (f true)), f's type is int -> int.
Why C's f doesn't have type 'a -> 'a?
I have difficulty in understanding the implementation of OCaml's
let polymorphism, I'll appreciate it a lot if anyone can give a concise
description of it with respect to the question.

A: Your code is unnecessarily confusing because you're using the same name f for two different things in B and also two different things in C.
Inside C you have this function:
fun g -> let f = g in (f 3, f true)

Again this is unnecessarily complicated; it's the same as:
fun g -> (g 3, g true)

The reason this isn't allowed is that it only works if g is a polymorphic function. This requires rank 2 polymorphism, i.e., it requires the ability to define function parameters that are polymorphic.
I'm not exactly sure what you're trying to do, but you can have a record type whose field is a polymorphic function. You can then use this record type to define something like your function:
# type r = { f : 'a . 'a -> 'a };;
type r = { f : 'a. 'a -> 'a; }
# (fun { f = g } -> (g 3, g true)) { f = fun x -> x };;
- : int * bool = (3, true)

# let myfun { f = g } = (g 3, g true);;
val myfun : r -> int * bool = <fun>

# myfun { f = fun x -> x };;
- : int * bool = (3, true)

The downside is that you need to pack and unpack your polymorphic function.
As a side comment, your example doesn't seem very compelling, because the number of functions of type 'a -> 'a is quite limited.


Q: Flutter Provider/Consumer UI not Updating with Data Change I am new to Flutter and working on developing my first application. I an having trouble updating my UI based on data changes. I followed this tutorial: https://www.filledstacks.com/post/flutter-architecture-my-provider-implementation-guide/ (and added extra features with https://www.filledstacks.com/post/flutter-provider-architecture-sharing-data-across-your-models/), which walks through a MVVM setup using the GetIt library.
I have successfully passed the data through the viewmodels and services, but I can't get my UI to update. Essentially, I want a user to be able to tap the movie on their watchlist and remove it. This works in a data sense, but my Watchlist UI isn't updating when I pop back to it. My entire project is available at https://github.com/n0ahth0mas/movie_night, but the core files to this problem are listed here:
locator.dart
...
...
GetIt locator = GetIt.instance;

void setupLocator() {
  locator.registerLazySingleton(() => AuthenticationService());
  locator.registerLazySingleton(() => WatchlistService());
  locator.registerLazySingleton(() => Api());

  locator.registerLazySingleton(() => LoginModel());
  locator.registerFactory(() => HomeModel());
  locator.registerFactory(() => RemoveButtonModel());
  locator.registerFactory(() => WatchlistModel());
}

watchlist_service.dart
...
...
class WatchlistService {
  Api _api = locator<Api>();

  List<Movie> _watchlist = [];
  List<Movie> get watchlist => _watchlist;

  Future getUserWatchlist(User user) async {
    for (String id in user.watchlistId) {
      _watchlist.add(await _api.getMovie(id));
    }
  }

  bool inList(Movie movie) {
    return _watchlist.contains(movie);
  }

  void editList(Movie movie, bool remove) {
    if (remove) {
      _watchlist.remove(movie);
      print("removed " + movie.title + " from list in watchlist service");
    } else {
      _watchlist.add(movie);
      print("added " + movie.title + " to list in watchlist service");
    }
  }
}

watchlist_model.dart
...
...
class WatchlistModel extends BaseModel {
  WatchlistService _watchlistService = locator<WatchlistService>();

  List<Movie> get watchlist => _watchlistService.watchlist;

  Future getWatchlist(User user) async {
    setState(ViewState.Busy);
    await _watchlistService.getUserWatchlist(user);
    setState(ViewState.Idle);
  }
}

watchlist_view.dart
...
...
class WatchlistView extends StatelessWidget {
  Widget _createMovieCard(Movie movie, BuildContext context) {
    return CupertinoButton(
      onPressed: () => _getInfo(movie, context),
      child: Image.network(movie.getPoster(185)),
    );
  }

  _getInfo(Movie movie, BuildContext context) {
    Navigator.pushNamed(
      context,
      "details",
      arguments: movie,
    );
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<WatchlistModel>(
        onModelReady: (model) => model.getWatchlist(Provider.of<User>(context)),
        builder: (context, model, child) => Scaffold(
            body: model.state == ViewState.Idle
                ? CustomScrollView(
                    primary: false,
                    slivers: <Widget>[
                      CupertinoSliverNavigationBar(
                        largeTitle: Text("My Watchlist"),
                        trailing: Material(
                            color: Colors.transparent,
                            child: IconButton(
                                icon: Icon(CupertinoIcons.add_circled_solid),
                                onPressed: () =>
                                    Navigator.pushNamed(context, 'search'))),
                      ),
                      SliverGrid(
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 2,
                            childAspectRatio:
                                MediaQuery.of(context).size.width /
                                    (MediaQuery.of(context).size.height / 1.7)),
                        delegate: SliverChildBuilderDelegate(
                            (BuildContext context, int index) {
                          return _createMovieCard(
                              model.watchlist[index], context);
                        }, childCount: model.watchlist.length),
                      ),
                    ],
                  )
                : Center(child: CircularProgressIndicator())));
  }
}

removebtn_model.dart
...
...

class RemoveButtonModel extends BaseModel {
  WatchlistService _watchlistService = locator<WatchlistService>();

  //bool watchlistStatus()

  void removeMovie(Movie movie) {
    print("removed " + movie.title + " from list in remove button model");
    _watchlistService.editList(movie, true);
    notifyListeners();
  }

  void addMovie(Movie movie) {
    print("added " + movie.title + " to list in remove button model");
    _watchlistService.editList(movie, false);
    notifyListeners();
  }
}

details_view.dart
...
...
class DetailsView extends StatelessWidget {
  _makeStars(double voteAverage) {
    double trueRating = voteAverage / 2;
    print(trueRating);
    return GFRating(
      color: Colors.yellowAccent[700],
      value: trueRating,
      size: GFSize.SMALL,
      allowHalfRating: true,
    );
  }

  _backdrop(String link) {
    if (link != null) {
      return Image.network("http://image.tmdb.org/t/p/w780/$link");
    } else
      return Image.asset("assets/images/transparent.png");
  }

  @override
  Widget build(BuildContext context) {
    Movie movie = ModalRoute.of(context).settings.arguments;

    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          CupertinoSliverNavigationBar(
            largeTitle: Text(movie.title),
            trailing:
                Material(color: Colors.transparent, child: RemoveButton(movie)),
          ),
          SliverToBoxAdapter(
              child: Column(
            children: <Widget>[
              Padding(padding: EdgeInsets.only(top: 20)),
              Center(child: Image.network(movie.getPoster(342))),
              Center(
                  child: Container(
                padding: EdgeInsets.all(10),
                child: Center(
                    child: Text(movie.title,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            fontSize: 40, fontWeight: FontWeight.w800))),
              )),
              Container(
                padding: EdgeInsets.only(bottom: 10),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    _makeStars(movie.voteAverage),
                    Text("platform",
                        style: Theme.of(context).textTheme.headline5),
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.fromLTRB(20, 0, 10, 50),
                child: Text(movie.overview),
              ),
              _backdrop(movie.backdropPath)
            ],
          ))
        ],
      ),
    );
  }
}

remove_btn.dart
...
...
class RemoveButton extends StatelessWidget {
  final Movie movie;
  RemoveButton(this.movie);

  _showDialog(String id, bool inWatchlist, BuildContext context,
      RemoveButtonModel model) {
    if (inWatchlist) {
      showDialog(
          context: context,
          child: CupertinoAlertDialog(
              title: Text("Remove from your watchlist?"),
              actions: <Widget>[
                CupertinoDialogAction(
                  isDefaultAction: true,
                  onPressed: () =>
                      Navigator.of(context, rootNavigator: true).pop(),
                  child: Text("Cancel"),
                ),
                CupertinoDialogAction(
                  textStyle: TextStyle(color: Colors.red),
                  onPressed: () => _deletelist(id, context, model),
                  child: Text("Remove"),
                )
              ]));
    } else {
      showDialog(
          context: context,
          child: CupertinoAlertDialog(
              title: Text("Add to your watchlist?"),
              actions: <Widget>[
                CupertinoDialogAction(
                  onPressed: () =>
                      Navigator.of(context, rootNavigator: true).pop(),
                  child: Text("Cancel"),
                ),
                CupertinoDialogAction(
                  isDefaultAction: true,
                  onPressed: () => _addList(id, context, model),
                  child: Text("Add"),
                )
              ]));
    }
  }

  _deletelist(String id, BuildContext context, RemoveButtonModel model) {
    model.removeMovie(movie);
    Provider.of<User>(context).deleteFromWatchlist(id);
    //Navigator.pushNamed(context, 'watchlist');
    Navigator.popUntil(context, ModalRoute.withName('watchlist'));
  }

  _addList(String id, BuildContext context, RemoveButtonModel model) {
    model.addMovie(movie);
    Provider.of<User>(context).addToWatchList(id);
    Navigator.popUntil(context, ModalRoute.withName('watchlist'));
  }

  Widget _rightBtn(Movie movie, BuildContext context, RemoveButtonModel model) {
    if (Provider.of<User>(context).inWatchlist(movie)) {
      return IconButton(
          icon: Icon(Icons.remove_circle),
          color: Colors.blue,
          onPressed: () =>
              _showDialog(movie.id.toString(), true, context, model));
    } else {
      return IconButton(
          icon: Icon(Icons.add_circle),
          color: Colors.blue,
          onPressed: () =>
              _showDialog(movie.id.toString(), false, context, model));
    }
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<RemoveButtonModel>(
      builder: (context, model, child) => _rightBtn(movie, context, model),
    );
  }
}

Thanks for your help! I've been stuck on this for the past 3 days and cannot figure out what I'm doing wrong.