class: center, middle, inverse, title-slide # Lecture 6 ## Projection methods ### Ivan Rudik ### AEM 7130 --- # Roadmap 1. What is projection 2. How we approximate functions --- # Our basic dynamic model An arbitrary infinite horizon problem can be represented using a Bellman equation `$$V(S_t) = \max_{q_t} u(q_t) + \beta\,V(S_{t+1}(q_t))$$` -- We can start from any arbitrary initial state vector and simulate the optimal policy paths in deterministic or stochastic settings -- We know that this problem has a fixed point (solution) `\(V^*\)` from previous lectures, but *how* do we approximate `\(V^*\)`? --- # Our basic dynamic model One way to do this is via .hi-blue[projection] -- Or perturbation, or discretization, or some analytic approaches for specific models -- We'll focus on value functions here, but we can approximate policy functions as well --- # Projection methods .hi-blue[Main idea:] build some function `\(\hat{V}\)` indexed by coefficients that approximately solves the Bellman -- What do I mean by approximately? -- The coefficients of `\(\hat{V}\)` are selected to minimize some residual function that tells us how far away our solution is from solving the Bellman --- # Projection methods Rearrange the Bellman equation and define a new functional `\(H\)` that maps the problem into a more general framework `$$H(V) = V(S_t) - \max_{q_t} u(q_t) + \beta\,V(S_{t+1}(q_t))$$` -- We can find some function `\(V\)` that solves `\(H(V) = 0\)` --- # Projection methods How do we do this? -- We solve this by specifying some linear combination of **basis functions** `\(\Psi_i(\mathbf{S})\)` `$$V^j(\mathbf{S}|\theta) = \sum_{i=0}^j \theta_i \Psi_i(\mathbf{S})$$` with coefficients `\(\theta_0,...,\theta_j\)` --- # Projection methods We then define a residual `$$R(\mathbf{S}|\theta) = H(V^j(\mathbf{S}|\theta))$$` and select the coefficient values to minimize the residual, given some measure of distance -- This step of selecting the coefficients is called .hi-blue[projecting] `\(H\)` against our basis --- # Projection methods We still have some choices to make: What basis do we select? How do we project (select the coefficients)? --- # Projection methods At first this may be a pretty confusing concept -- Simple example to get intuition? -- Ordinary least squares linear regression -- We can think of the problem as searching for some unknown conditional expectation `\(E[Y|X]\)`, given outcome variable `\(Y\)` and regressors `\(X\)` --- # Projection methods We don't know the true functional form, but we can approximate it using the first two monomials on `\(X\)`: `\(1\)` and `\(X\)` `$$E[Y|X] \approx \theta_0 + \theta_1 X$$` -- These are the first two elements of the *monomial basis* -- One residual function is then: `\(R(Y,X|\theta_0,\theta_1) = abs(Y-\theta_0-\theta_1 X)\)` --- # Projection methods In econometrics we often minimize the square of this residual, which is just OLS -- So OLS is within the class of projection methods -- In OLS we use observed data, but in theory we use the operator `\(H(V)\)` --- # Projection classes are defined by metrics Projection methods are separated into several broad classes by the type of residual we're trying to shrink to zero -- We need to select some metric function `\(\rho\)`, that determines how we project -- `\(\rho\)` tells us how close our residual function is to zero over the domain of our state space --- # Example residuals given different projections Example: The figure shows two different residuals on some capital domain of `\([0,\bar{k}]\)`

 The residual based on the coefficient vector `\(\theta_1\)` is large for small values of capital but near-zero everywhere else -- The residual based on `\(\theta_2\)` has medium values just about everywhere -- Which is closer to zero over the interval? It will depend on our selection of `\(\rho\)` --- # We want to use weighted residuals We move from the plain residual to `\(\rho\)` because we want to set a *weighted residual* equal to zero (more general) -- Suppose we have some weight functions `\(\phi_i:\Omega \rightarrow \mathbb{R}\)` that map from our state space to the real line -- The one-dimensional metric is defined as `\begin{equation*} \rho(R\cdot|\theta,0) = \begin{cases} 0 & \text{if } \int_\Omega\phi_i(\mathbf{S})R(\cdot|\theta)d\mathbf{S} = 0, i=1,...,j+1\\ 1 &\text{otherwise} \end{cases} \end{equation*}` -- Where we want to solve for `\(\theta = \text{argmin} \, \rho(R(\cdot|\theta),0)\)` --- # We want to use weighted residuals We can then change our problem to simply solving a system of integrals ensuring the metric is zero `$$\int_\Omega\phi_i(\mathbf{S})R(\cdot|\theta)d\mathbf{S} = 0, i=1,...,j+1.$$` -- We can solve this using standard rootfinding techniques -- .hi-blue[Big remaining question:] how do we choose our `\(j+1\)` weight functions? -- First lets begin with a simple example before moving into the most commonly used weight functions --- # Least squares projection Suppose we selected the weight function to be `$$\phi_i(\mathbf{S}) = \frac{\partial R(\mathbf{S}|\theta)}{\partial \theta_{i-1}}$$` -- Then we would be performing least squares! Why? --- # Least squares projection Recall the objective of least squares is `$$\min_{\mathbf{\theta}} \int R^2(\cdot|\theta)d\mathbf{S}$$` -- The FOC for a minimum is `$$\int \frac{\partial R(\mathbf{S}|\theta)}{\partial \theta_{i-1}}R(\cdot|\theta)d\mathbf{S} = 0, i = 1,...,j+1$$` -- So the first order condition sets the weighted average residual to zero where the weights are determined by the partial derivatives of the residual -- The partial derivative weight function solves the least squares problem! --- # Collocation The most commonly used weight function gives us a methodology called .hi-blue[collocation] -- Here our weight function is `$$\phi_i(\mathbf{S}) = \delta(\mathbf{S}-\mathbf{S}_i)$$` Where `\(\delta\)` is the *Dirac delta function* and `\(\mathbf{S}_i\)` are the j+1 *collocation points* or *collocation nodes* selected by the researcher -- The Dirac delta function is zero at all `\(\mathbf{S}\)` except at `\(\mathbf{S} = \mathbf{S}_i\)` -- What does this weight function mean? --- # Collocation Before we even select our coefficients, this means that the residual can only be non-zero at a finite set of points `\(\mathbf{S_i}\)` -- So the solution to our problem must set the residual to zero at these collocation points -- Since we have a finite set of points we do not need to solve difficult integrals but only a system of equations `$$R(\mathbf{S}_i|\theta) = 0, i=1,...,j+1$$` --- # Rough idea of how we proceed Collocation methods aim to approximate the value function `\(V(S_t)\)` with some linear combination of known, and usually orthogonal `\((\int f(x)g(x)w(x)=0)\)`, basis functions -- One example of a possible class of basis functions is the monomial basis: `\(x, x^2, x^3,...\)` -- But how do we implement collocation? --- # Rough idea of how we proceed Recall we solve for coefficients `\(\theta\)` by setting the residual to be zero at all of our collocation points -- But the residual is a function of `\(V\)`, and thus will be a function of `\(\theta\)`, a loop seemingly impossible to escape -- We can solve this problem by *iterating* on the problem, continually setting the residuals equal to zero, recovering new `\(\theta\)`s, and repeating --- # Rough idea of how we proceed In any given iteration, we: -- - Begin with a vector of coefficients on the basis functions (e.g. a random guess) -- - Use a linear combination of the basis functions as an approximation to the value function on the right hand side of the Bellman --- # Rough idea of how we proceed - Solve the Bellman with the approximated value function in it, at our set of collocation points -- - Recover a set maximized continuation values at these points in our state space conditional on the previous value function approximant we used -- - Use these new maximized values to obtain updated coefficients solving the system of linear equations, and repeat the process until we have "converged" --- # Still have some questions By the contraction mapping theorem this is guaranteed to converge from any arbitrary initial set of coefficients! (conditional on satisfying the assumptions and there being no numerical error..) -- This still leaves several questions unanswered -- - Where in the state space do we place the collocation points? -- - What basis functions do we use? -- Do your answers to the previous two questions really matter? -- **Yes they are crucial** --- # Still have some questions Schemes exist to generate high quality approximations, and to obtain the approximation at low computational cost -- Once we have recovered an adequate approximation to the value function, we have effectively solved the entire problem! -- We know how the policymaker's expected discounted stream of future payoffs changes as we move through the state space --- # Still have some questions We can solve the Bellman at some initial state and know that solving the Bellman will yield us optimal policies -- Therefore we can simulate anything we want and recover optimal policy functions given many different sets of initial conditions or realizations of random variables --- # Interpolation What points in our state space do we select to be collocation points? -- We often have continuous states in economics (capital, temperature, oil reserves, technology shocks, etc.), so we must have some way to reduce the infinity of points in our state space into something more manageable -- We do so by selecting a specific finite number of points in our state space and use them to construct a *collocation grid* that spans the domain of our problem --- # Interpolation Using our knowledge of how the value function behaves at the limited set of points on our grid, we can interpolate our value function approximant at all points off the grid points, but *within* the domain of our grid -- **Note:** The value function approximant is not very good outside the grid's domain since that would mean extrapolating beyond whatever information we have gained from analyzing our value function on the grid --- # Basis functions Let `\(V\)` be the value function we wish to approximate with some `\(\hat{V}\)` -- `\(\hat{V}\)` is constructed as a linear combination of `\(n\)` linearly independent (i.e. orthogonal) basis functions `$$\hat{V}(x)= \sum_{j=1}^n c_j \psi_j(x)$$` -- Each `\(\psi_j(x)\)` is a basis function, and the coefficients `\(c_j\)` determine how they are combined at some point `\(\bar{x}\)` to yield our approximation `\(\hat{V}(\bar{x})\)` to `\(V(\bar{x})\)` --- # Basis functions The number of basis functions we select, `\(n\)`, is the degree of interpolation -- In order to recover `\(n\)` coefficients, we need at least `\(n\)` equations that must be satisfied at a solution to the problem -- If we have precisely `\(n\)` equations, we are just solving a simple system of linear equations: we have a perfectly identified system and are solving a collocation problem -- This is what happens we select our number of grid points in the state space to be equal to the number of coefficients (which induces a Dirac delta weighting function) --- # Basis functions Solve a system of equations, *linear in `\(c_j\)`* that equates the function approximant at the grid points to the recovered values `$$\Psi \mathbf{c} = \mathbf{y}$$` where `\(\Psi\)` is the matrix of basis functions, `\(c\)` is a vector of coefficients, and `\(y\)` is a vector of the recovered values -- We can recover `\(c\)` by left dividing by `\(\Psi\)` which yields `$$\mathbf{c} = \Psi^{-1}\mathbf{y}$$` --- # Basis functions If we have more equations, or grid points, than coefficients, then we can just use OLS to solve for the coefficients by minimizing the sum of squared errors -- `$$\mathbf{c} = (\Psi'\Psi)^{-1}\Psi'\mathbf{y}$$` --- # (Pseudo-)spectral methods Spectral methods apply all of our basis functions to the entire domain of our grid: they are global -- When using spectral methods we virtually always use polynomials -- **Why?** --- # (Pseudo-)spectral methods The Stone-Weierstrass Theorem which states (for one dimension) *Suppose `\(f\)` is a continuous real-valued function defined on the interval `\([a,b]\)`. For every `\(\epsilon > 0, \,\, \exists\)` a polynomial `\(p(x)\)` such that for all `\(x \in [a,b]\)` we have `\(||f(x) - p(x)||_{sup} \leq \epsilon\)`* -- What does the SW theorem say in words? --- # (Pseudo-)spectral methods For any continuous function `\(f(x)\)`, we can approximate it arbitrarily well with some polynomial `\(p(x)\)`, as long as `\(f(x)\)` is continuous -- This means the function can even have kinks -- Unfortunately we do not have infinite computational power so solving kinked problems with spectral methods is not advised -- Note that the SW theorem *does not* say what kind of polynomial can approximate `\(f\)` arbitrarily well, just that some polynomial exists --- # Basis choice What would be your first choice of basis? -- Logical choice: the monomial basis: `\(1, x, x^2,...\)` -- It is simple, and SW tells us that we can uniformly approximate any continuous function on a closed interval using them --- # Basis choice ## Practice code up a function `project_monomial(f, n, lb, ub)` that takes in some function `f`, degree of approximation `n`, lower bound `lb` and upper bound `ub`, and constructs a monomial approximation on an evenly spaced grid via collocation -- We will be plotting stuff, see [http://docs.juliaplots.org/latest/generated/gr/](http://docs.juliaplots.org/latest/generated/gr/) for example code using the `GR` backend --- # The monomial basis Let's approximate `sin(x)` ```julia using Plots gr(); f(x) = sin.(x); Plots.plot(f, 0, 2pi, line = 4, grid = false, legend = false, size = (500, 250)) ```  --- # Approximating sin(x) ```julia function project_monomial(f, n, lb, ub) # solves Ψc = y → c = Ψ\y # Ψ = matrix of monomial basis functions evaluted on the grid coll_points = range(lb, ub, length = n) # collocation points y_values = f(coll_points) # function values on the grid basis_functions = [coll_points.^degree for degree = 0:n-1] # vector of basis functions basis_matrix = hcat(basis_functions...) # basis matrix coefficients = basis_matrix\y_values # c = Ψ\y return coefficients end; coefficients_4 = project_monomial(f, 4, 0, 2pi); coefficients_5 = project_monomial(f, 5, 0, 2pi); coefficients_10 = project_monomial(f, 10, 0, 2pi) ``` ``` ## 10-element Array{Float64,1}: ## 0.0 ## 0.9990725797458863 ## 0.004015857153649684 ## -0.1738437387373486 ## 0.007075663351639969 ## 0.004040763230876247 ## 0.0016747985983553285 ## -0.0006194667844101428 ## 6.485272688203222e-5 ## -2.293696012495368e-6 ``` --- # Approximating sin(x) Now we need to construct a function `f_approx(coefficients, plot_points)` that takes in the `coefficients` vector, and an arbitrary vector of points to evaluate the approximant at (for plotting) -- ```julia function f_approx(coefficients, points) n = length(coefficients) - 1 basis_functions = [coefficients[degree + 1] * points.^degree for degree = 0:n] # evaluate basis functions basis_matrix = hcat(basis_functions...) # transform into matrix function_values = sum(basis_matrix, dims = 2) # sum up into function value return function_values end; ``` --- # Approximating sin(x) ```julia plot_points = 0:.01:2pi; f_values_4 = f_approx(coefficients_4, plot_points); f_values_5 = f_approx(coefficients_5, plot_points); f_values_10 = f_approx(coefficients_10, plot_points) ``` ``` ## 629×1 Array{Float64,2}: ## 0.0 ## 0.009990953610597868 ## 0.019981668333012258 ## 0.029971103713554246 ## 0.03995822109623334 ## 0.04994198367415802 ## 0.05992135654204973 ## 0.06989530674983996 ## 0.07986280335732032 ## 0.0898228174898161 ## ⋮ ## -0.08303623493742407 ## -0.0730710101597829 ## -0.06309900382681377 ## -0.05312124622683001 ## -0.04313876967565733 ## -0.03315260846174084 ## -0.023163798791941304 ## -0.01317337873884128 ## -0.0031823881890886696 ``` --- # Plot  --- # Plot  --- # Plot  --- # Plot  --- # Cool! We just wrote some code that exploits Stone-Weierstrauss and allows us to (potentially) approximate any continuous function arbitrarily well as `n` goes to infinity -- To approximate any function we'd need to feed in some basis function `g(x, n)` as opposed to hard-coding it like I did in the previous slides -- Turns out we never use the monomial basis though --

 --- # Cool! Turns out we never use the monomial basis though -- Why? -- Try approximating **Runge's function**: `f(x) = 1/(1 + 25x^2)` --- # Runge's function ```julia runge(x) = 1 ./ (1 .+ 25x.^2); coefficients_5 = project_monomial(runge, 5, -1, 1); coefficients_10 = project_monomial(runge, 10, -1, 1); plot_points = -1:.01:1; runge_values_5 = f_approx(coefficients_5, plot_points); runge_values_10 = f_approx(coefficients_10, plot_points); ``` --- # Runge's function  --- # Runge's function  --- # Runge's function  --- # Maybe we can just crank up n?  --- # Maybe we can just crank up n?  --- # Monomials are not good What's the deal? -- The matrix of monomials, `\(\Phi\)`, is often ill-conditioned, especially as the degree of the monomials increases -- The first 6 monomials can induce a condition number of `\(10^{10}\)`, a substantial loss of precision -- Second, they can vary dramatically in size, which leads to scaling/truncation errors --- # Monomials are not good ```julia runge(x) = 1 ./ (1 .+ 25x.^2); coefficients_10 = project_monomial(runge, 10, -1, 1); points = rand(10); n = length(coefficients_10) - 1; basis_functions = [coefficients_10[degree + 1] * points.^degree for degree = 0:n]; basis_matrix = hcat(basis_functions...); println("Condition number: $(cond(basis_matrix))") ``` ``` ## Condition number: 2.6207888700137328e20 ``` -- Example: `\(x^11\)` goes from `\(1e-4\)` to about 90 when moving x from 0.5 to 1.5 -- Ideally we want an .hi-blue[orthogonal basis:] when we add another element of the basis, it has sufficiently different behavior than the elements before it so it can capture features of the unknown function that the previous elements couldn't --- # The Chebyshev basis Most frequently used is the **Chebyshev basis** -- It has nice approximation properties: 1. They are easy to compute -- 2. They are orthogonal -- 3. They are bounded between `\([-1,1]\)` --- # The Chebyshev basis Chebyshev polynomials are often selected because they minimize the oscillations that occur when approximating functions like Runge's function -- The Chebyshev polynomial closely approximates the *minimax polynomial*: the polynomial, given degree `\(d\)`, that minimizes any approximation error to the true function --- # The Chebyshev basis Chebyshev polynomials are defined by a recurrence relation, `\begin{gather} T_0(x) = 1 \\ T_1(x) = x \\ T_{n+1} = 2xT_n(x) - T_{n-1}(x) \end{gather}` and are defined on the domain `\([-1,1]\)` -- In practice this is easy to expand to any interval `\([a,b]\)` -- Chebyshev polynomials look similar to monomials but have better properties that are visually distinctive --- # The Chebyshev basis Chebyshev polynomials are defined by a recurrence relation, `\begin{gather} T_0(x) = 1 \\ T_1(x) = x \\ T_{n+1} = 2xT_n(x) - T_{n-1}(x) \end{gather}` Write two functions: `cheb_polys(n, x)` and `monomials(n, x)` with a degree of approximation `n` and vector of points `x`, that return the values of the approximant at `x` If you can't get the recurrence relation to work, you can use an alternative: `$$T_n(x) = cos(n \, arccos(x))$$` --- # The Chebyshev basis Next, a plotting function `plot_function(basis_function, x, n)` that takes an arbitrary basis function `basis_function` and plots all basis functions up to degree `n` --- # The two basis functions ```julia # Chebyshev polynomial function function cheb_polys(x, n) if n == 0 return x./x # T_0(x) = 1 elseif n == 1 return x # T_1(x) = x else cheb_recursion(x, n) = 2x.*cheb_polys.(x, n - 1) .- cheb_polys.(x, n - 2) return cheb_recursion(x, n) # T_n(x) = 2xT_{n-1}(x) - T_{n-2}(x) end end; # Monomial function monomials(x, n) = x.^n; ``` --- # The plotting function ```julia function plot_function(basis_function, x, n) for i = 1:n-1 f_data = basis_function(x, i) if i == 1 plot(x, f_data, linewidth = 4.0, xlabel = "x", ylabel = "Basis functions", label = "", tickfontsize = 14, guidefontsize = 14, grid = false); else plot!(x, f_data, linewidth = 4.0, label = ""); end end f_data = basis_function(x, n) plot!(x, f_data, linewidth = 4.0, label = "") end; x = -1:.01:1; ``` --- # Monomials up to degree 5 ```julia plot_function(monomials, x, 5) ```  --- # Chebyshev polynomials up to degree 5 ```julia plot_function(cheb_polys, x, 5) ```  --- # Monomials up to degree 10 ```julia plot_function(monomials, x, 10) ```  --- # Chebyshev polynomials up to degree 10 ```julia plot_function(cheb_polys, x, 10) ```  --- # Chebyshev polynomials rule Chebyshev polynomials span the space -- Monomials clump together --- # Chebyshev polynomials rule Chebyshev polynomials are nice for approximation because they are *orthogonal* and they form a basis with respect to the weight function `\(\phi(x) = 1/\sqrt{1-x^2}\)` -- They span the polynomial vector space -- This means that you can form any polynomial of degree equal to less than the Chebyshev polynomial you are using -- It also guarantees that `\(\Phi\)` has full rank and is invertible --- # Chebyshev zeros and alternative rep Also note that the Chebyshev polynomial of order `\(n\)` has `\(n\)` zeros given by `$$x_k = cos\left(\frac{2k-1}{2n}\pi \right), \,\,\, k=1,...,n$$` which tend to cluster quadratically towards the edges of the domain -- You can think about this as projecting sequentially finer uniform grids from a hemicircle onto the x-axis --- # Two important theorems There are two important theorems to know about Chebyshev polynomials -- **Chebyshev interpolation theorem:** *If `\(f(x) \in \mathbb{C}[a,b]\)`, if `\(\{\psi_i(x), i=0,...\}\)` is a system of polynomials (where `\(\psi_i(x)\)` is of exact degree i) orthogonal with respect to `\(\phi(x)\)` on `\([a,b]\)` and if `\(p_j = \sum_{i=0}^j \theta_i \psi_i(x)\)` interpolates `\(f(x)\)` in the zeros of `\(\psi_{n+1}(x)\)`, then: `$$\lim_{j\rightarrow\infty} \left(|| f-p_j||_2 \right)^2 = \lim_{j\rightarrow\infty}\int_a^b \phi(x) \left(f(x) - p_j \right)^2 dx = 0$$`* -- What does this say? --- # Two important theorems If we have an approximation set of basis functions that are exact at the roots of the `\(n^{th}\)` order polynomials, then as `\(n\)` goes to infinity the approximation error becomes arbitrarily small and converges at a quadratic rate -- This holds for any type of polynomial, but if they are Chebyshev then convergence is uniform -- Unfortunately we cant store an infinite number of polynomials in our computer, we would like to know how big our error is after truncating our sequence of polynomials --- # Two important theorems **Chebyshev truncation theorem:** The error in approximating `\(f\)` is bounded by the sum of all the neglected coefficients -- Since Chebyshev polynomials satisfy Stone-Weierstrauss, an infinite sequence of them can perfectly approximate any continuous function -- Since Chebyshev polynomials are bounded between `\([-1,1]\)`, the sum of the omitted terms is bounded by the sum of the magnitude of the coefficients -- So the error in the approximation is as well! --- # Two important theorems We often also have that Chebyshev approximations geometrically converge which give us the following convenient property: `$$|f(x) - f^j(x|\theta)| \sim O(\theta_j)$$` The truncation error by stopping at polynomial `\(j\)` is of the same order as the magnitude of the coefficient `\(\theta_j\)` on the last polynomial -- Thus in many situations we can simply check the size of the last polynomial to gauge how accurate our approximation is --- # Boyd's moral principle Chebyshev polynomials are the most widely used basis -- This is not purely theoretical but also from practical experience --- # Boyd's moral principle John Boyd summarizes decades of experience with function approximation with his moral principle: - When in doubt, use Chebyshev polynomials unless the solution is spatially periodic, in which case an ordinary fourier series is better - Unless you are sure another set of basis functions is better, use Chebyshev polynomials - Unless you are really, really sure another set of basis functions is better use Chebyshev polynomials --- # Grid point selection We construct the basis function approximant by evaluating the function on a predefined grid in the domain of `\(V\)` -- If we have precisely `\(n\)` nodes, `\(x_i\)`, we then have $$\sum_{j=1}^n c_j \phi_j(x_i) = V(x_i) \,\, \forall i=1,2,...,n \tag{interpolation conditions} $$ --- # Grid point selection We can write this problem more compactly as `$$\Phi c = y \tag{interpolation equation}$$` where - `\(y\)` is the column vector of `\(V(x_i)\)` - `\(c\)` is the column vector of coefficients `\(c_j\)` - `\(\Phi\)` is an `\(n\times n\)` matrix of the `\(n\)` basis functions evaluated at the `\(n\)` points -- If we recover a set of values at our interpolation nodes, `\(V^*(x_i)\)`, we can then simply invert `\(\Phi\)` and right multiply it by `\(y\)` to recover our coefficients -- **How do we select our set of nodes `\(x_i\)`?** --- # Chebyshev strikes again A good selection of points are called *Chebyshev nodes* -- These are simply the roots of the Chebyshev polynomials above on the domain `\([-1,1]\)` -- They are given by `$$x_k = cos\left(\frac{2k-1}{2n}\pi\right),\,\, k = 1,...,n$$` for some Chebyshev polynomial of degree `\(n\)` --- # Chebyshev strikes again `$$x_k = cos\left(\frac{2k-1}{2n}\pi\right),\,\, k = 1,...,n$$` Mathematically, these also help reduce error in our approximation -- We can gain intuition by looking at a graph of where Chebyshev nodes are located, plot them yourself! --- # Chebyshev node function ```julia cheb_nodes(n) = cos.(pi * (2*(1:n) .- 1)./(2n)) ``` ``` ## cheb_nodes (generic function with 1 method) ``` --- # Chebyshev node locations  --- # Chebyshev node locations  --- # Chebyshev node locations  --- # Chebyshev node locations The nodes are heavily focused near the end points, why is that? -- Imagine areas of our approximant near the center of our domain but not at a node -- These areas benefit from having multiple nodes on both the left and right --- # Chebyshev node locations This provides more information for these off-node areas and allows them to be better approximated because we know whats happening nearby in several different directions -- If we moved to an area closer to the edge of the domain, there may only one node to the left or right of it providing information on what the value of our approximant should be -- Therefore, it's best to put more nodes in these areas to shore up this informational deficit and get good approximation quality near the edges of our domain --- # Discrete states How do we handle a discrete state `\(S_d\)` when trying to approximate `\(V\)`? -- Just like you might expect, we effectively have a different function approximant over the continuous states for each value of `\(S_d\)` --- # Multi-dimensional approximation Thus far we have displayed the Chebyshev basis in only one dimension -- We approximate functions of some arbitrary dimension `\(N\)` by taking the tensor of vectors of the one-dimensional Chebyshev polynomials -- Ex: if we wanted to approximate a two dimensional function with a degree 3 polynomial, implying 3 grid points for each dimension, we could do the following: Construct a vector of polynomials `\([\phi_{1,1}, \, \phi_{1,2}, \, \phi_{1,3}]\)` for dimensions 1 -- Construct a vector of polynomials `\([\phi_{2,1}, \, \phi_{2,2}, \, \phi_{2,3}]\)` for dimension 2 --- # Multi-dimensional approximation The tensor is just the product of every possibly polynomial pair which results in: `$$[\phi_{1,1}\phi_{2,1} ,\, \phi_{1,1}\phi_{2,2}, \, \phi_{1,1}\phi_{2,3}, \\ \phi_{1,2}\phi_{2,1}, \, \phi_{1,2}\phi_{2,2}, \, \phi_{1,2}\phi_{2,3}, \\ \phi_{1,3}\phi_{2,1}, \, \phi_{1,3}\phi_{2,2}, \, \phi_{1,3}\phi_{2,3}]$$` -- We can then solve for the 9 coefficients on these two dimensional polynomials --- # Multi-dimensional approximation The computational complexity here grows exponentially: `\(\text{total # points} = (\text{points per state})^{\text{# states}}\)` -- Exponential complexity is costly, often called the **Curse of dimensionality** -- We will cover smart ways to deal with this later --- # Finite element methods An alternative to pseudo-spectral methods is the class of **finite element methods** -- Finite element methods use basis functions that are non-zero over *subintervals* of the domain of our grid -- For example, we can use **splines** (piecewise polynomials) over segments of our domains where they are spliced together at prespecified breakpoints, which are called knots --- # Finite element methods The higher the order the polynomial we use, the higher the order of derivatives that we can preserve continuity at the knots -- For example, a linear spline yields an approximant that is continuous, but its first derivatives are discontinuous step functions unless the underlying value function happened to be precisely linear -- If we have a quadratic spline, we can also preserve the first derivative's continuity at the knots, but the second derivative will be a discontinuous step function --- # Finite element methods As we increase the order of the spline polynomial, we have increasing numbers of coefficients we need to determine -- To determine these additional coefficients using the same number of points, we require additional conditions that must be satisfied -- These are what ensure continuity of higher order derivatives at the knots as the degree of the spline grows --- # Finite element methods With linear splines, each segment of our value function approximant is defined by a linear function -- For each of these linear components, we need to solve for 1 coefficient and 1 intercept term -- Each end of a linear segment must equal the function value at the knots --- # Finite element methods We have two conditions and two unknowns for each segment: this is a simple set of linear equations that we can solve -- In numerical models we typically don't use linear splines because we often care about the quality of approximation of higher order derivatives, cubic splines are more common --- # Cubic splines Suppose we wish to approximate using a cubic spline on `\(N+1\)` knots -- We need `\(N\)` cubic polynomials when entails `\(4N\)` coefficients to determine -- We can obtain `\(3(N-1)\)` equations by ensuring that the approximant is continuous at all interior knots, and its first and second derivatives are continuous at all interior knots `\([3\times(N+1-1-1)]\)` -- This means that the value of the left cubic polynomial equals the value of the right cubic polynomial at each interior knot --- # Cubic splines Ensuring the the approximant equals the function's value at all of the nodes adds another `\(N+1\)` equations -- We therefore have a total of `\(4N-2\)` equations for `\(4N\)` coefficients -- We need two more conditions to solve the problem -- What is often used is that the approximant's first or second derivative matches that of the function at the end points --- # Splines can potentially handle lots of curvature If the derivative is of interest for optimization, or to recover some variable of economic meaning, then we may need to have these derivatives preserved well at the knots -- One large benefit of splines is that they can handle kinks or areas of high curvature -- **How?** -- By having the modeler place many knots in a concentrated region --- # Splines can potentially handle lots of curvature If the knots are stacked on top of one another, this actually allows for a *kink* to be explicitly represented in the value function approximant, but the economist must know precisely where the kink is -- Useful spline packages out there: `Dierckx`, `Interpolations`, `QuantEcon` --- # Code it up! Let's code up our own linear spline approximation function `linear_spline_approx(f, knots)`, where `f` is the function we are approximating and `knots` are the knots Have it return a function a function `spline_eval` that takes in `evaluation_points` as an argument where `evaluation_points` are the points we want to evaluate the spline approximant at **Hint:** Linear splines are pretty easy, given two points `\((x_{i+1}, y_{i+1})\)` and `\((x_i, y_i)\)`, the spline in between these points is given by `$$y(x) = y_i + \frac{y_{i+1} - y_i}{x_{i+1} - x_{i}}(x - x_i)$$` --- # Spline approximator ```julia function linear_spline_approx(f, knots) function spline_eval(evaluation_points) prev_knot = knots[1] # initialize previous knot if !(typeof(evaluation_points) <: Number) # if using multiple points y_eval = similar(evaluation_points) y_index = 1 for knot in knots[2:end] current_points = evaluation_points[prev_knot .<= evaluation_points .< knot] y_eval[y_index:y_index + length(current_points) - 1] = f(prev_knot) .+ (f(knot) - f(prev_knot))/(knot - prev_knot)*(current_points .- prev_knot) prev_knot = knot y_index += length(current_points) end else # if using just a single point for knot in knots[2:end] if prev_knot .<= evaluation_points .< knot y_eval = f(prev_knot) + (f(knot) - f(prev_knot))/(knot - prev_knot)*(evaluation_point - prev_knot) end prev_knot = knot end end return y_eval end return spline_eval end ``` ``` ## linear_spline_approx (generic function with 1 method) ``` --- # Plot ```julia f(x) = sin(x) ``` ``` ## f (generic function with 1 method) ``` ```julia knots_coarse = 0:pi/2:2pi; spline_func_coarse = linear_spline_approx(f, knots_coarse); knots_fine = 0:pi/4:2pi; spline_func_fine = linear_spline_approx(f, knots_fine); knots_superfine = 0:pi/12:2pi; spline_func_superfine = linear_spline_approx(f, knots_superfine); x_vals =0:.05:2pi; y_vals_coarse = spline_func_coarse(x_vals); y_vals_fine = spline_func_fine(x_vals); y_vals_superfine = spline_func_superfine(x_vals); ``` --- # Plot  --- # Plot  --- # Plot  --- # Plot


Serializing XML¶
The XML version of the typed dictionary might look like this:
from datetime import datetime
from typing import List, Optional, TypedDict, Union
from typing_extensions import Annotated
from jetblack_serialization.xml import XMLEntity, XMLAttribute
class Book(TypedDict, total=False):
book_id: Annotated[int, XMLAttribute("bookId")]
title: str
author: str
publication_date: datetime
keywords: Annotated[List[Annotated[str, XMLEntity("Keyword")]], XMLEntity("Keywords")]
phrases: List[str]
age: Optional[Union[datetime, int]]
pages: Optional[int]
Note we have introduced some annotations to control the serialization. For XML we have used pascal-case to serialized the keys and snake-case for deserialization.
Create some data:
book: Book = {
'author': 'Chairman Mao',
'book_id': 42,
'title': 'Little Red Book',
'publication_date': datetime(1973, 1, 1, 21, 52, 13),
'keywords': ['Revolution', 'Communism'],
'phrases': [
'Revolutionary wars are inevitable in class society',
'War is the continuation of politics'
],
'age': 24,
'pages': None
}
Serializing¶
To serialize we need to provide the containing tag Book
:
from stringcase import pascalcase, snakecase
from jetblack_serialization import SerializerConfig
from jetblack_serialization.xml import serialize
text = serialize(
book,
Annotated[Book, XMLEntity("Book")],
SerializerConfig(pascalcase, snakecase)
)
print(text)
Producing:
<Book bookId="42">
<Title>Little Red Book</Title>
<Author>Chairman Mao</Author>
<PublicationDate>1973-01-01T21:52:13.00Z</PublicationDate>
<Keywords>
<Keyword>Revolution</Keyword>
<Keyword>Communism</Keyword>
</Keywords>
<Phrase>Revolutionary wars are inevitable in class society</Phrase>
<Phrase>War is the continuation of politics</Phrase>
<Age>24</Age>
</Book>'
The annotations are more elaborate here. However, much of the typed dictionary requires no annotation.
First we needed the outer document wrapper XMLEntity("Book")
.
Next we annotated the book_id
to be an XMLAttribute
.
Finally we annotated the two lists differently. The keywords
list used
a nested structure, which we indicated by giving the list a different
XMLEntity
tag to the list items. For the phrases we used the default
in-line behaviour.
Deserializing¶
We can deserialize the XML as follows:
from stringcase import pascalcase, snakecase
from jetblack_serialization import SerializerConfig
from jetblack_serialization.xml import deserialize
dct = deserialize(
text,
Annotated[Book, XMLEntity("Book")],
SerializerConfig(pascalcase, snakecase)
)


Argument '{0}' must be an object
The argument passed should be an object. Check the value that was passed to the function where this error was thrown.


acpid-2.0.32
Introduction to acpid
The acpid (Advanced Configuration
and Power Interface event daemon) is a completely flexible, totally
extensible daemon for delivering ACPI events. It listens on netlink
interface and when an event occurs, executes programs to handle the
event. The programs it executes are configured through a set of
configuration files, which can be dropped into place by packages or
by the user.
This package is known to build and work properly using an LFS-9.1
platform.
Package Information
User Notes: http://wiki.linuxfromscratch.org/blfs/wiki/acpid
Installation of acpid
Install acpid by running the
following commands:
./configure --prefix=/usr \
--docdir=/usr/share/doc/acpid-2.0.32 &&
make
This package does not come with a test suite.
Now, as the root
user:
make install &&
install -v -m755 -d /etc/acpi/events &&
cp -r samples /usr/share/doc/acpid-2.0.32
Configuring acpid
acpid is configured by user
defined events. Place event files under /etc/acpi/events
directory. If an event occurs,
acpid recurses
through the event files in order to see if the regex defined after
"event" matches. If they do, action is executed.
The following brief example will suspend the system when the laptop
lid is closed (it requires pm-utils-1.4.1):
cat > /etc/acpi/events/lid << "EOF"
event=button/lid
action=/etc/acpi/lid.sh
EOF
cat > /etc/acpi/lid.sh << "EOF"
#!/bin/sh
/bin/grep -q open /proc/acpi/button/lid/LID/state && exit 0
/usr/sbin/pm-suspend
EOF
chmod +x /etc/acpi/lid.sh
Unfortunately, not every computer labels ACPI events in the same
way. To determine how your buttons are recognized, use the
acpi_listen tool.
Also, look in the samples
directory
under /usr/share/doc/acpid-2.0.32
for
more examples.
Boot Script
To automatically start acpid when the system is
rebooted, install the /etc/rc.d/init.d/acpid
boot script from the
blfs-bootscripts-20191204 package.
make install-acpid
Contents
Installed Programs:
acpid, acpi_listen, and kacpimon
Installed Libraries:
None
Installed Directories:
/etc/acpi and
/usr/share/doc/acpid-2.0.32
Short Descriptions
|
acpid
|
is a program that listens for ACPI events and executes
the rules that match the received event.
|
|
acpi_listen
|
is a simple tool which connects to acpid and listens for
events.
|
|
kacpimon
|
is a monitor program that connects to three sources of
ACPI events (events file, netlink and input layer) and
then reports on what it sees while it is connected.
|
Last updated on 2020-02-15 22:23:35 -0600


Implementing Switches - Flexbox Style
My gender is
Male
Female
My favourite social media is
Twitter
Facebook


The docx reference document
As explained in section 3.4 of R Markdown: The Definitive Guide, the first step in creating a reference document is to produce a .docx file using rmarkdown or Pandoc. The formatting and layout of this document can then be edited and saved. The resulting reference document is then used in the YAML metadata of each R Markdown file.
This vignette is intended to track all the changes made to the rub_reference.docx file, so that these changes are reproducible and documented.
Page Layout
Margins
- Top: 2,5 cm
- Left: 1,5 cm
- Bottom: 2 cm
- Right: 2 cm
- Gutter: 0 cm
- Gutter position: Left
Layout
- Different first page (x)
- From edge: Header: 1 cm
- From edge: Footer: 1,1 cm
Styles
Title
- Style type: Paragraph
- Style based on: Normal
- Style for following paragraphs: Body Text
- Font: RubFlama, 26 pt, Bold, Font color: Custom Color(RGB(0;53;96)), Small caps
- Right: 1cm, Centered
- Space Before: 256 pt, After: 12pt, Keep with next, Keep lines together
Author
- Style type: Paragraph
- Style based on: (no style)
- Style for following paragraphs: Body Text
- Font: RubFlama, 26 pt, Font color: Custom Color(RGB(141;174;16)), All caps
- Right: 1 cm, Centered
- Line spacing: single
- Space After: 10 pt, Widow/Orphan control, Keep with next, Keep lines together
Date
- Style type: Paragraph
- Style based on: (no style)
- Style for following paragraphs: Body Text
- Font: RubFlama, 16 pt, Font color: Custom Color(RGB(0;53;96)), Small caps
- Right: 1 cm, Right
- Line spacing: single
- Space Before: 256 pt, After: 10 pt, Widow/Orphan control, Keep with next, Keep lines together
TOC Heading
- Style type: Paragraph
- Style based on: Heading 1
- Style for following paragraphs: Body Text
- Indent left: 0 cm
- Indent first line: 0 cm
- Line spacing: Multiple 1,08 li
- Space Before: 12 pt, After: 12 pt, None, No bullets or numbering
TOC 1
- Style type: Paragraph
- Style based on: Normal
- Style for following paragraphs: Normal
- Right: 1 cm, Left,
- Space After: 5 pt
- Tab stops: 0,85 cm, Left + 17,48 cm, Right, Leader: …
Heading 1
- Style type: Paragraph
- Style based on: Normal
- Style for following paragraphs: Body Text
- Font: RubFlama, 14 pt, Bold, Font color: Custom Color(RGB(0;53;96)), All caps
- Indent:
- Left: 0 cm
- Hanging: 1,02 cm, Left
- Space After: 6 pt, Page break before, Keep with next, Keep lines together
- Level 1, Outline numbered + Level: 1 + Numbering Style: 1, 2, 3, … + Start at: 1 + Alignment: Left + Aligned at: 0 cm + Indent at: 1,02 cm
Heading 2
- Style type: Paragraph
- Style based on: Normal
- Style for following paragraphs: Body Text
- Font: RubFlama, 14 pt, Font color: Custom Color(RGB(0;53;96))
- Indent:
- Left: 0 cm
- Hanging: 1,02 cm, Left
- Space Before: 10 pt, After: 0 pt, Keep with next, Keep lines together, Level 2, Outline numbered + Level: 2 + Numbering Style: 1, 2, 3, … + Start at: 1 + Alignment: Left + Aligned at: 0 cm + Indent at: 1,02 cm
Heading 3
- Style type: Paragraph
- Style based on: Normal
- Style for following paragraphs: Body Text
- Font: (Default) RubFlama, 14 pt, Font color: Custom Color(RGB(141;174;16)), Left
- Space Before: 10 pt, After: 0 pt, Keep with next, Keep lines together
- Level 3
Heading 4
- Style type: Paragraph
- Style based on: Normal
- Style for following paragraphs: Body Text
- Font: RubFlama, Font color: Custom Color(RGB(141;174;16)), Left
- Space Before: 10 pt, After: 0 pt, Keep with next, Keep lines together
- Level 4
Heading 6
- Style type: Paragraph
- Style based on: Normal
- Style for following paragraphs: Body Text -Font: (Default) RUB Scala MZ, 9 pt, Italic, - Space After: 18 pt, Keep lines together
- Level 6
Image Caption
- Style type: Paragraph
- Style based on: Caption
- Style for following paragraphs: Image Caption
- Font: 12 pt, Not Italic, Font color: Custom Color(RGB(0;53;96))
- Space After: 0 pt, Keep with next, Keep lines together
First Paragraph
- Style type: Paragraph
- Style based on: Body Text
- Style for following paragraphs: Body Text
Body Text
- Style type: Linked (paragraph and character)
- Style based on: Normal
- Style for following paragraphs: Body Text
- Space Before: 9 pt, After: 9 pt
Hyperlink
- Style type: Character
- Style based on: Caption Char
- Font: RUB Scala TZ, 12 pt, Not Italic, Font color: Accent 1
Compact
- Style type: Paragraph
- Style based on: Body Text
- Style for following paragraphs: Compact
- Space Before: 1,8 pt, After: 1,8 pt


Click here for separating alphabets from digits.
Click here for the keyDown exercise.
Click here for random stars.
Click here for bouncing balls.


All Posts
{% if posts %} {% for post_id, post_info in posts.items() %}{{ post_info[1] }} {{ post_info[2] }} (@{{ post_info[0] }}) · {{ post_info[4] }} {{ post_info[3] }}
{% if post_info[0] != username and post_id not in reposts %} {% endif %}{{ post_info[1] }} {{ post_info[2] }} (@{{ post_info[0] }}) · {{ post_info[4] }} {{ post_info[3] }}
{% if post_info[0] != username and post_id not in reposts %} {% endif %}


Who’s through, who has work to do? How things stand for British teams in Europe
There is only one round of group fixtures left in the Champions League and Europa League.
The Champions League and Europa League are both rapidly approaching the knockout stages.
Just one round of group fixtures remain in each competition before the draw for the respective rounds of 16 and 32 on December 16.
Here, the PA news agency takes a look at the implications surrounding the British clubs involved in the two competitions.
Liverpool (Champions League)
Manchester City (Champions League)
City are unbeaten in Group C, with Tuesday night’s 1-1 draw with Shakhtar Donetsk putting them five points clear at the top and securing their place in the round of 16. They are one of eight clubs to make it through to the knockout stages already, with Real Madrid and Tottenham so far emerging as potential opponents after finishing second in their respective groups. Paris St Germain, Bayern Munich, Barcelona, Juventus and RB Leipzig are the other teams to confirm their places in the final 16.
Chelsea (Champions League)
The reigning Europa League champions are currently second in Group H behind Ajax, but are relying on the Dutch giants’ final group game to advance to the knockout stages. Frank Lampard’s side face Lille, where a win would see them through as long as either Ajax are victorious or if their own winning margin is greater than Valencia’s. If they lose or draw, they need Valencia to have the same outcome.
Tottenham (Champions League)
Manchester United (Europa League)
While United have already qualified for the round of 32, their 2-1 loss to Astana on Thursday means they must wait until next week to confirm themselves as Group L winners. A win or draw against AZ Alkmaar would see them top the group, however a defeat would mean they finish second behind the Dutch side.
Arsenal (Europa League)
Wolves (Europa League)
Wolves have already secured their spot in the round of 32 but still have the chance to top Group K. They currently sit just one point behind leaders Braga after drawing 3-3 with the Portuguese club on Thursday. A win over Besiktas next week could see them advance in first place, but only if Braga lose or draw against Slovan Bratislava.
Celtic (Europa League)
A 3-1 win over Rennes on Thursday means Celtic will advance to the round of 32 as Group E winners. Four wins and a draw sees them currently four points clear of second place CFR Cluj, who they will face in their final group game next week. Neil Lennon’s side are one of nine teams to confirm their place so far.


Sudhanshu Dubey
24th August 2019
nginx [engine x] is an HTTP and reverse proxy server, a mail proxy server, and a generic TCP/UDP proxy server, originally written by Igor Sysoev.
Userdir
means that each user has it’s own public_html directory.root
.


I'm Sebastián Alejo Iglesias, a software engineer and teacher based in Argentina, who speaks English and Spanish. I've been working in the tech industry for over 6 years, and I've had the opportunity to work for both big tech companies and startups. I'm a full stack engineer, and I'm proficient in a variety of languages and technologies, including Java, Scala, Typescript, and React. I'm passionate about building innovative and user-friendly software. I'm also a lifelong learner, and I'm always eager to learn new things. In my free time, I enjoy testing machine learning tools, 3D printing, ham radio, hydroponics, soccer, gaming, and traveling. My goal is to be happy with myself and with my work. I hope to one day start my own company, but I'm unsure as to what that company will do. For now, I'm focused on learning and growing as a software engineer.
ITBA University
Data Science Specialization.
Austral University
Software Engineering
Universidad Austral
Preparing and giving classes and assignments to software engineer students. Introduction to Programming 1 (1st-year students): Basic Python and programming principles, use of a standard POSIX terminal, git, and GitHub. Laboratory I (3rd-year students): This course provides the fundamental knowledge required to develop a software project, covering all stages from conception to implementation and testing. Students work in groups and propose real-life software projects, using use case analysis to define requirements and create an implementation schedule. The course evaluates progress through two partial deliveries, where each group showcases their use case implementations using the developed software.
Caribou.
At Caribou, we are building healthcare cost prediction and optimization software for the finance industry. Financial advisors and wealth managers across the US are using our software for proactive healthcare planning, protecting their clients’ wealth and building stronger client relationships. Every feature we release or conversation we have fits our mission of creating a world where healthcare does not get in the way of living.
MuleSoft, a Salesforce company.
Worked on Mulesoft RPA development adapting a legacy codebase to the way of coding in MuleSoft. Worked with Java + Spring microservices that interacted with Postgresql Databases whose migrations where managed by Liquibase. Performed performance and functionality tests as well.
MuleSoft, a Salesforce company.
Worked on Anypoint’s Datagraph in an engineering team following agile methodologies, developing front and back- end services. The product was developed from scratch and maintained in production later on. In conjunction with my team, we developed REST Services using Java and Spring as well as web clients with React, Redux and Typescript. Developed integration tests using Testcafe. Helped and provided guide for junior and intern employees.
MuleSoft.
Worked on the Monitoring Platform inside MuleSoft’s Anypoint Platform in an engineering team following agile methodologies, developing front and backend services. The product was developed from scratch and maintained in production later on. In conjunction with my team, we developed REST Services using Scala, Akka and Java and several types of databases as well as web clients with React, Angular and Typescript. Which where deployed in the AWS cloud via tools such as Terraform, Salt, Spinnaker and Jenkins. For Monitoring purposes, I’ve worked with the Elasticsearch stack and set up scripts on Python and bash.
MuleSoft.
Maintained a legacy VCS system and developed new features using Raml, Java, Junit, Spring Framework, Docker and Kubernetes.
Informatica Solidaria
Founded Informatica Solidaria, an organization that received old electronics, repaired and donated them to educational organizations in Pilar, Buenos Aires, Argentina.
FINES.
Worked as a teacher in IT for an accelerated high school course for adults under the FINES plan. I planned and gave night classes to both adults and teenagers.


The Building Company assurance begins with our initial contact with our customer and the advice we provide. Every stage of our work is set to high qualified standards.
The Building Company have one mission in life and that is to make our client's dream homes a reality.
Whether we start with an existing house and transform it to meet the client's needs or build a new one from scratch, the aim is the same; A beautiful home of the highest standard at an affordable price.
We pride ourselves on having high standards, whether it's simply a new bathroom you require or a whole refurbishment. We are proud of the work we do and invite you to browse our website.


Directions
Press and hold the left mouse button to draw a number on the canvas.
When you are done, click the "Make a Guess" button. The network's guess along with some statistics will be displayed.
Press and hold the left mouse button to draw a number on the canvas.
When you are done, click the "Make a Guess" button. The network's guess along with some statistics will be displayed.
7


Presenting animated statistics for deaths per one million population, starting from January 22nd till today. * All countries with less than 1 million inhabitants are excluded.


hello and welcome
CEO & Founder
"hello fish in the time of evil i will help you out".
<EMAIL_ADDRESS>Contact


HM Chief Inspector, Sir Michael Wilshaw, confirmed that Ofsted has already conducted inspections in several faith and non-faith schools in other areas to probe issues similar to those uncovered in a number of schools in Birmingham.
Sir Michael has asked his team of Regional Directors to respond swiftly to any further concerns that are brought to their attention – using Ofsted’s existing powers to mount unannounced inspections where necessary.
The move follows this week’s publication of the advice note sent by Sir Michael to the Secretary of State alongside Ofsted’s inspection reports into 21 state-funded, non-faith schools in Birmingham.
The advice note set out evidence of some governors exerting inappropriate influence on the day to day running of their schools. In the most serious cases, HM inspectors found evidence that a number of headteachers - including those with a proud record of raising standards - had been marginalised or forced out of their jobs.
Sir Michael also said that in some of the Birmingham schools inspected, leaders had not adequately addressed the safeguarding issues specific to their community – particularly the potential risks associated with extremism and radicalisation.
Inspectors also found that in a number of schools, the curriculum had become too narrow - reflecting the personal views of a small number of governors and leaving children vulnerable to ‘emotional dislocation’ from the wider community.
Sir Michael Wilshaw said:
What inspectors found in a number of schools in Birmingham is deeply disturbing. We should all be concerned if a school - of any kind - is failing to encourage children to develop tolerant attitudes towards other faiths and cultures or allowing governors to exert inappropriate influence on the curriculum or other aspects of school life.
It’s vitally important that we remain vigilant for such problems developing in any part of the country.
Under Ofsted’s regional structure, our inspectors are now closer to the ground and to those we inspect than ever before. I have asked them to make sure they are using their local knowledge and contacts to identify where these type of problems may be taking hold.
Where we hear of concerns, we will respond swiftly in order to reassure parents and the wider community that children are receiving the good, safe and well-rounded education to which they are entitled.
Note to editors
Under section 8 of the Education Act 2005, Her Majesty’s Chief Inspector (HMCI) may inspect any school in England in circumstances where he is not required to do so by section 5 of the Act. Ofsted may undertake a section 8 inspection in order to follow up concerns about a school which may have been brought to Ofsted’s attention, for example through a qualifying complaint made to Ofsted under section 11A-C of the Act, or by other means. Depending on the particular circumstances, inspectors can conduct these section 8 inspections on a no notice basis – for example if the inspection resulted from serious concerns about safeguarding, behaviour or discipline.
Following the publication of the Birmingham school inspection reports and advice note, the Prime Minister and Secretary of State have asked HMCI to look at the practicalities of moving to a system of routine no notice school inspections and yesterday Sir Michael confirmed his intention to take this issue forward as part of Ofsted’s wider review of the future of school inspection.
Read
HMCI’s advice note to the Secretary of State
.
Ofsted’s regional structure has been in place since 2013. Eight Regional Directors are responsible for the quality of inspection and the improvement of providers in their region. They report directly to HM Chief Inspector, Sir Michael Wilshaw. The Regional Directors lead teams of Senior HM Inspectors and HM Inspectors (HMI), to promote improvement through inspection. The Regional Directors are:
-
North West Regional Director – Jo Morgan
-
North East, Yorkshire and Humber – Nick Hudson
-
South East – Sir Robin Bosher
-
London – Debbie Jones
-
South West – Bradley Simmons
-
East of England – Sean Harford
-
East Midlands – Louise Soden
-
West Midlands – Lorna Fitzjohn


The patch decorators are used for patching objects only within the scope of the function they decorate. They automatically handle the unpatching for you, even if exceptions are raised. All of these functions can also be used in with statements or as class decorators.
Note
patch is straightforward to use. The key is to do the patching in the right namespace. See the section where to patch.
patch acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the target is patched with a new object. When the function/with statement exits the patch is undone.
If new is omitted, then the target is replaced with a MagicMock. If patch is used as a decorator and new is omitted, the created mock is passed in as an extra argument to the decorated function. If patch is used as a context manager the created mock is returned by the context manager.
target should be a string in the form ‘package.module.ClassName’. The target is imported and the specified object replaced with the new object, so the target must be importable from the environment you are calling patch from. The target is imported when the decorated function is executed, not at decoration time.
The spec and spec_set keyword arguments are passed to the MagicMock if patch is creating one for you.
In addition you can pass spec=True or spec_set=True, which causes patch to pass in the object being mocked as the spec/spec_set object.
new_callable allows you to specify a different class, or callable object, that will be called to create the new object. By default MagicMock is used.
A more powerful form of spec is autospec. If you set autospec=True then the mock with be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise a TypeError if they are called with the wrong signature. For mocks replacing a class, their return value (the ‘instance’) will have the same spec as the class. See the create_autospec() function and Autospeccing.
Instead of autospec=True you can pass autospec=some_object to use an arbitrary object as the spec instead of the one being replaced.
By default patch will fail to replace attributes that don’t exist. If you pass in create=True, and the attribute doesn’t exist, patch will create the attribute for you when the patched function is called, and delete it again afterwards. This is useful for writing tests against attributes that your production code creates at runtime. It is off by by default because it can be dangerous. With it switched on you can write passing tests against APIs that don’t actually exist!
Patch can be used as a TestCase class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set. patch finds tests by looking for method names that start with patch.TEST_PREFIX. By default this is test, which matches the way unittest finds tests. You can specify an alternative prefix by setting patch.TEST_PREFIX.
Patch can be used as a context manager, with the with statement. Here the patching applies to the indented block after the with statement. If you use “as” then the patched object will be bound to the name after the “as”; very useful if patch is creating a mock object for you.
patch takes arbitrary keyword arguments. These will be passed to the Mock (or new_callable) on construction.
patch.dict(...), patch.multiple(...) and patch.object(...) are available for alternate use-cases.
patch as function decorator, creating the mock for you and passing it into the decorated function:
>>> @patch('__main__.SomeClass')
... def function(normal_argument, mock_class):
... print mock_class is SomeClass
...
>>> function(None)
True
Patching a class replaces the class with a MagicMock instance. If the class is instantiated in the code under test then it will be the return_value of the mock that will be used.
If the class is instantiated multiple times you could use side_effect to return a new mock each time. Alternatively you can set the return_value to be anything you want.
To configure return values on methods of instances on the patched class you must do this on the return_value. For example:
>>> class Class(object):
... def method(self):
... pass
...
>>> with patch('__main__.Class') as MockClass:
... instance = MockClass.return_value
... instance.method.return_value = 'foo'
... assert Class() is instance
... assert Class().method() == 'foo'
...
If you use spec or spec_set and patch is replacing a class, then the return value of the created mock will have the same spec.
>>> Original = Class
>>> patcher = patch('__main__.Class', spec=True)
>>> MockClass = patcher.start()
>>> instance = MockClass()
>>> assert isinstance(instance, Original)
>>> patcher.stop()
The new_callable argument is useful where you want to use an alternative class to the default MagicMock for the created mock. For example, if you wanted a NonCallableMock to be used:
>>> thing = object()
>>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
... assert thing is mock_thing
... thing()
...
Traceback (most recent call last):
...
TypeError: 'NonCallableMock' object is not callable
Another use case might be to replace an object with a StringIO instance:
>>> from StringIO import StringIO
>>> def foo():
... print 'Something'
...
>>> @patch('sys.stdout', new_callable=StringIO)
... def test(mock_stdout):
... foo()
... assert mock_stdout.getvalue() == 'Something\n'
...
>>> test()
When patch is creating a mock for you, it is common that the first thing you need to do is to configure the mock. Some of that configuration can be done in the call to patch. Any arbitrary keywords you pass into the call will be used to set attributes on the created mock:
>>> patcher = patch('__main__.thing', first='one', second='two')
>>> mock_thing = patcher.start()
>>> mock_thing.first
'one'
>>> mock_thing.second
'two'
As well as attributes on the created mock attributes, like the return_value and side_effect, of child mocks can also be configured. These aren’t syntactically valid to pass in directly as keyword arguments, but a dictionary with these as keys can still be expanded into a patch call using **:
>>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
>>> patcher = patch('__main__.thing', **config)
>>> mock_thing = patcher.start()
>>> mock_thing.method()
3
>>> mock_thing.other()
Traceback (most recent call last):
...
KeyError
patch the named member (attribute) on an object (target) with a mock object.
patch.object can be used as a decorator, class decorator or a context manager. Arguments new, spec, create, spec_set, autospec and new_callable have the same meaning as for patch. Like patch, patch.object takes arbitrary keyword arguments for configuring the mock object it creates.
When used as a class decorator patch.object honours patch.TEST_PREFIX for choosing which methods to wrap.
You can either call patch.object with three arguments or two arguments. The three argument form takes the object to be patched, the attribute name and the object to replace the attribute with.
When calling with the two argument form you omit the replacement object, and a mock is created for you and passed in as an extra argument to the decorated function:
>>> @patch.object(SomeClass, 'class_method')
... def test(mock_method):
... SomeClass.class_method(3)
... mock_method.assert_called_with(3)
...
>>> test()
spec, create and the other arguments to patch.object have the same meaning as they do for patch.
Patch a dictionary, or dictionary like object, and restore the dictionary to its original state after the test.
in_dict can be a dictionary or a mapping like container. If it is a mapping then it must at least support getting, setting and deleting items plus iterating over keys.
in_dict can also be a string specifying the name of the dictionary, which will then be fetched by importing it.
values can be a dictionary of values to set in the dictionary. values can also be an iterable of (key, value) pairs.
If clear is True then the dictionary will be cleared before the new values are set.
patch.dict can also be called with arbitrary keyword arguments to set values in the dictionary.
patch.dict can be used as a context manager, decorator or class decorator. When used as a class decorator patch.dict honours patch.TEST_PREFIX for choosing which methods to wrap.
patch.dict can be used to add members to a dictionary, or simply let a test change a dictionary, and ensure the dictionary is restored when the test ends.
>>> from mock import patch
>>> foo = {}
>>> with patch.dict(foo, {'newkey': 'newvalue'}):
... assert foo == {'newkey': 'newvalue'}
...
>>> assert foo == {}
>>> import os
>>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
... print os.environ['newkey']
...
newvalue
>>> assert 'newkey' not in os.environ
Keywords can be used in the patch.dict call to set values in the dictionary:
>>> mymodule = MagicMock()
>>> mymodule.function.return_value = 'fish'
>>> with patch.dict('sys.modules', mymodule=mymodule):
... import mymodule
... mymodule.function('some', 'args')
...
'fish'
patch.dict can be used with dictionary like objects that aren’t actually dictionaries. At the very minimum they must support item getting, setting, deleting and either iteration or membership test.  It takes the object to be patched (either as an object or a string to fetch the object by importing) and keyword arguments for the patches:
with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
...
Use DEFAULT as the value if you want patch.multiple to create mocks for you. In this case the created mocks are passed into a decorated function by keyword, and a dictionary is returned when patch.multiple is used as a context manager.
patch.multiple can be used as a decorator, class decorator or a context manager. The arguments spec, spec_set, create, autospec and new_callable have the same meaning as for patch. These arguments will be applied to all patches done by patch.multiple.
When used as a class decorator patch.multiple honours patch.TEST_PREFIX for choosing which methods to wrap.
If you want patch.multiple to create mocks for you, then you can use DEFAULT as the value. If you use patch.multiple as a decorator then the created mocks are passed into the decorated function by keyword.
>>> thing = object()
>>> other = object()
>>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
... def test_function(thing, other):
... assert isinstance(thing, MagicMock)
... assert isinstance(other, MagicMock)
...
>>> test_function()
patch.multiple can be nested with other patch decorators, but put arguments passed by keyword after any of the standard arguments created by patch:
>>> @patch('sys.exit')
... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
... def test_function(mock_exit, other, thing):
... assert 'other' in repr(other)
... assert 'thing' in repr(thing)
... assert 'exit' in repr(mock_exit)
...
>>> test_function()
If patch.multiple is used as a context manager, the value returned by the context manger is a dictionary where created mocks are keyed by name:
>>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
... assert 'other' in repr(values['other'])
... assert 'thing' in repr(values['thing'])
... assert values['thing'] is thing
... assert values['other'] is other
...
All the patchers have start and stop methods. These make it simpler to do patching in setUp methods or where you want to do multiple patches without nesting decorators or with statements.
To use them call patch, patch.object or patch.dict as normal and keep a reference to the returned patcher object. You can then call start to put the patch in place and stop to undo it.
If you are using patch to create a mock for you then it will be returned by the call to patcher.start.
>>> patcher = patch('package.module.ClassName')
>>> from package import module
>>> original = module.ClassName
>>> new_mock = patcher.start()
>>> assert module.ClassName is not original
>>> assert module.ClassName is new_mock
>>> patcher.stop()
>>> assert module.ClassName is original
>>> assert module.ClassName is not new_mock
A typical use case for this might be for doing multiple patches in the setUp method of a TestCase:
>>> class MyTest(TestCase):
... def setUp(self):
... self.patcher1 = patch('package.module.Class1')
... self.patcher2 = patch('package.module.Class2')
... self.MockClass1 = self.patcher1.start()
... self.MockClass2 = self.patcher2.start()
...
... def tearDown(self):
... self.patcher1.stop()
... self.patcher2.stop()
...
... def test_something(self):
... assert package.module.Class1 is self.MockClass1
... assert package.module.Class2 is self.MockClass2
...
>>> MyTest('test_something').run()
Caution
If you use this technique you must ensure that the patching is “undone” by calling stop. This can be fiddlier than you might think, because if an exception is raised in the setUp then tearDown is not called. unittest2 cleanup functions make this easier.
>>> class MyTest(TestCase):
... def setUp(self):
... patcher = patch('package.module.Class')
... self.MockClass = patcher.start()
... self.addCleanup(patcher.stop)
...
... def test_something(self):
... assert package.module.Class is self.MockClass
...
>>> MyTest('test_something').run()
As an added bonus you no longer need to keep a reference to the patcher object.
It is also possible to stop all patches which have been started by using patch.stopall.
Stop all active patches. Only stops patches started with start.
All of the patchers can be used as class decorators. When used in this way they wrap every test method on the class. The patchers recognise methods that start with test as being test methods. This is the same way that the unittest.TestLoader finds test methods by default.
It is possible that you want to use a different prefix for your tests. You can inform the patchers of the different prefix by setting patch.TEST_PREFIX:
>>> patch.TEST_PREFIX = 'foo'
>>> value = 3
>>>
>>> @patch('__main__.value', 'not three')
... class Thing(object):
... def foo_one(self):
... print value
... def foo_two(self):
... print value
...
>>>
>>> Thing().foo_one()
not three
>>> Thing().foo_two()
not three
>>> value
3
If you want to perform multiple patches then you can simply stack up the decorators.
You can stack up multiple patch decorators using this pattern:
>>> @patch.object(SomeClass, 'class_method')
... @patch.object(SomeClass, 'static_method')
... def test(mock1, mock2):
... assert SomeClass.static_method is mock1
... assert SomeClass.class_method is mock2
... SomeClass.static_method('foo')
... SomeClass.class_method('bar')
... return mock1, mock2
...
>>> mock1, mock2 = test()
>>> mock1.assert_called_once_with('foo')
>>> mock2.assert_called_once_with('bar')
Note that the decorators are applied from the bottom upwards. This is the standard way that Python applies decorators. The order of the created mocks passed into your test function matches this order.
Like all context-managers patches can be nested using contextlib’s nested function; every patching will appear in the tuple after “as”:
>>> from contextlib import nested
>>> with nested(
... patch('package.module.ClassName1'),
... patch('package.module.ClassName2')
... ) as (MockClass1, MockClass2):
... assert package.module.ClassName1 is MockClass1
... assert package.module.ClassName2 is MockClass2
...
patch works by (temporarily) changing the object that a name points to with another one. There can be many names pointing to any individual object, so for patching to work you must ensure that you patch the name used by the system under test.
The basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined. A couple of examples will help to clarify this.
Imagine we have a project that we want to test with the following structure:
a.py
-> Defines SomeClass
b.py
-> from a import SomeClass
-> some_function instantiates SomeClass
Now we want to test some_function but we want to mock out SomeClass using patch. The problem is that when we import module b, which we will have to do then it imports SomeClass from module a. If we use patch to mock out a.SomeClass then it will have no effect on our test; module b already has a reference to the real SomeClass and it looks like our patching had no effect.
The key is to patch out SomeClass where it is used (or where it is looked up ). In this case some_function will actually look up SomeClass in module b, where we have imported it. The patching should look like:
@patch(‘b.SomeClass’)
However, consider the alternative scenario where instead of from a import SomeClass module b does import a and some_function uses a.SomeClass. Both of these import forms are common. In this case the class we want to patch is being looked up on the a module and so we have to patch a.SomeClass instead:
@patch(‘a.SomeClass’)
Since version 0.6.0 both patch and patch.object have been able to correctly patch and restore descriptors: class methods, static methods and properties. You should patch these on the class rather than an instance.
Since version 0.7.0 patch and patch.object work correctly with some objects that proxy attribute access, like the django setttings object.
Note
In django import settings and from django.conf import settings return different objects. If you are using libraries / apps that do both you may have to patch both. Grrr...


Others
inversely
believed
that
it
was
fundamental
to
eliminate
useless
works
They
invaded
the
hexagons
showed
credentials
which
were
not
always
false
leafed
through
a
volume
with
displeasure
and
condemned
whole
shelves
their
hygienic
ascetic
furor
caused
the
senseless
perdition
of
millions
of
books
Their
name
is
execrated
but
those
who
deplore
the
treasures
destroyed
by
this
frenzy
neglect
two
notable
facts
One
the
Library
is
so
enormous
that
any
reduction
of
human
origin
is
infinitesimal
The
other
every
copy
is
unique
irreplaceable
but
since
the
Library
is
total
there
are
always
several
hundred
thousand
imperfect
facsimiles
works
which
differ
only
in
a
letter
or
a
comma
Counter
to
general
opinion
I
venture
to
suppose
that
the
consequences
of
the
Purifiers
depredations
have
been
exaggerated
by
the
horror
these
fanatics
produced
They
were
urged
on
by
the
delirium
of
trying
to
reach
the
books
in
the
Crimson
Hexagon
books
whose
format
is
smaller
than
usual
all
powerful
illustrated
and
magical
.


Galleries: Journaling:
Affirmations Gratitude Journaling Gratitude Lists
Search feature to find and add to Interactive input feature via form
Inspirational Quotes Mood Tracker
Search feature to find and add to Interactive input feature via form
Inspirational Photos/Images
Search feature to find and add to
Appointment Calendar and Reminder
Organizations and Other Resources Interactive input feature via form
Initially populated with a sample ? Calendar/Alarm Interface with Device
set.
Include search and input feature so user
can add their own resources


% layout('base') %> <%- partial('header') %>
Your account is in paused mode
and your current case
will be held for you for
Your account has no longer a current case
and it's back in the queue
Just click the button below to get a new case


We develop encryption and IT security solutions and find answers to questions on how to design digitalization to the benefit of companies and society.
We are known for the development of Cryptomator, our open-source cloud encryption software, which won the CeBIT Innovation Award.
We adapt our security solutions individually for our customers, advise them on security issues, and educate on the subjects such as “digital self-defense”.
At Skymatic, expertise from software and app development, cryptography, and psychology come together. We keep a sharp eye on the development of digitization with its opportunities and risks from our different perspectives and develop solutions where they are most needed.
We are participants in BSI's Alliance for Cyber Security, and member of the Cyber Security Cluster Bonn.


Did you spot these Death Stranding celebrity cameos?
by Jordan OlomanWhat celebrities make up the Death Stranding cast? Death Stranding is full of surprises, with numerous celebrity appearances among them. Norman Reedus, Lea Seydoux, Mads Mikkelsen and co. were all revealed way ahead of the game’s release, so their part in Death Stranding should be common knowledge by now.
But what other household names can be found across the wastes of this post-apocalyptic America? These famous folks play in-game 'Preppers', characters who live alone in bunkers with their families awaiting your deliveries. In the real world, they are famous friends of Kojima 3D-scanned into the game at his company's studio. There are a number of unexpected guests to get through, so read on for the definitive list of every celebrity cameo in Death Stranding.
All Death Stranding cameos
Ludens Fan: Geoff Keighley
Geoff Keighley is a journalist and media personality in the videogames industry, famous for his 'The Final Hours of…' making of reports and most recently as the face of The Game Awards.
Musician: Daichi Miura
Daichi Miura is a Japanese singer and dancer known for the opening theme of Kamen Rider Ex-Aid “EXCITE” and Dragon Ball Super: Broly’s “Blizzard”. in the game he gives Sam a harmonica to soothe BB.
Engineer: Junji Ito
Junji Ito is a popular manga artist behind iconic works of horror such as Tomie, Gyo, and Uzumaki, itself a deeply unnerving series about a town full of citizens driven insane by symbolic spirals.
Craftsman: Herman Hulst
Herman Hulst is the Managing Director of Guerrilla Games, creators of console-exclusive series Horizon: Zero Dawn and Killzone. The engine used for Zero Dawn, Decima, was used by Kojima Productions to create Death Stranding. Hulst provides Horizon-themed holograms including Aloy and a giant Tallneck.
The Wandering MC: Conan O’ Brien
Conan O’ Brien is an American talk show host, comedian, and writer most famous for his work on The Simpsons. His TV show Conan regularly features up-and-coming videogames and related industry personalities.
Thomas Southerland: Edgar Wright
Edgar Wright is the esteemed English director of the hilarious Three Flavours Cornetto trilogy featuring Shaun of the Dead, Hot Fuzz, and The World’s End. His later work includes the Michael Cera-led film adaptation of Scott Pilgrim vs. The World, Marvel’s Ant-Man, and most recently, Baby Driver.
Collector: Hirokazu Hamamura
Hirokazu Hamamura is the former editor of Japanese magazine Famitsu Weekly and the President & CEO of Enterbrain and Famitsu group, who publish videogames magazines and software like RPG Maker in Japan.
Death Stranding on PC
(Image credit: Kojima Productions)
The Death Stranding PC release date isn't until early summer 2020, but we're getting a head start with the console version to give you the best advice ahead of the PC launch.
Film Director: Jordan Vogt-Roberts
Jordan Vogt-Roberts is a TV and film director with an excellent beard and responsible for the charming indie flick The Kings of Summer, and Kong: Skull Island. He has created videogame adverts and currently serves as the director of the upcoming Metal Gear Solid movie, which is currently without a cast.
Alex Weatherstone: Errolson Hugh
Errolson Hugh is the fashion designer behind Berlin studio ACRONYM. He created a number of pieces related to Death Stranding ahead of its launch, including the J1A-GT Jacket based on Sam’s in-game outfit.
Veteran Porter: Sam Lake
Sam Lake is a prolific videogame writer and founding member of Finnish studio Remedy Entertainment. Lake contributed his skills in scriptwriting and design to Max Payne, Alan Wake, Quantum Break, and Control. This is clearly Kojima’s Remedy-related Easter egg after he contributed voice work to a secret in Control earlier in 2019.
Phillip North: Tommy Wirkola
Tommy Wirkola is a Norwegian director famous for the horror comedy Dead Snow and 2013’s Hansel & Gretel: Witch Hunters. He is currently writing the film adaptation of Mark Ward’s dark comic series Irredeemable with Adam McKay in the director’s seat.
The Novelist’s Son: Manabu Makime
Manabu Makime is a Japanese novelist and essayist famous for his books The Fantastic Deer-Man and Princess Toyotomi, works which have since been adapted for film and TV.


Get Started
Login
Login
Forgot?
Remember me
Login
Don't have an account?
Create account
Login using a social network
Reset Password
Back to login


Contents:
LASED
LASED.constants
LASED.decay_constant
LASED.density_matrix
LASED.detuning
LASED.generate_sub_states
LASED.half_rabi_freq
LASED.index
LASED.laser_atom_system
LASED.matrix_methods
LASED.rotation
LASED.save_to_csv
LASED.state
LASED.symbolic_print
LASED.time_evolution
LASED.time_evolution_matrix


Effective Python: 90 Specific Ways to write better Python
- (PYTHONIC THINKING) Know which version of Python you're using
- Follow the PEP 8 Style guide
- Know the differences between bytes and str
- Prefer interpolated f-strings over C-style format strings and str.format
- Write helper functions instead of complex expressions
- Prefer multiple assignment unpacking over indexing
- Prefer enumerate over range
- Use zip to process iterators in parallel
- Avoid else blocks after for and while loops
- Prevent repetition with assignment expressions (use the walrus operator)
- (LISTS AND DICTIONARIES) Know how to slice sequences
- Avoid striding and slicing in a single expression
- Prefer catch-all unpacking over slicing
- Sort by complex criteria using the key parameter
- Be cautious when relying on dict insertion ordering
- Prefer
get
over in
and KeyError to handle missing dictionary keys
- Prefer defaultdict over setdefault to handle missing items in internal state
- Know how to construct key-dependent default values with __missing__
- (FUNCTIONS) Never unpack more than three variables when functions return multiple values
- Prefer raising exceptions to returning None
- Know how closures interact with variable scope
- Reduce visual noise with variable positional arguments
- Provide optional behavior with keyword arguments
- Use None and docstrings to specify dynamic default arguments
- Enforce clarity with keyword-only and positional-only arguments
- Define function decorators with functools.wraps
- (COMPREHENSIONS AND GENERATORS) Use comprehensions instead of map and filter
- Avoid more than two control subexpressions in comprehensions
- Avoid repeated work in comprehensions by using assignment expressions
- Consider generators instead of returning lists
- Be defensive when iterating over arguments
- Consider generator expressions for large list comprehensions
- Compose multiple generators with yield from
- Avoid injecting data into generators with send
- Avoid causing state transitions in generators with throw
- Consider itertools for working with iterators and generators
- (CLASSES AND INTERFACES) Compose classes instead of nesting many levels of built-in types
- Accept functions instead of classes for simple interfaces
- Use @classmethod polymorphism to construct objects generically
- Initialize parent classes with super
- Consider composing functionality with mix-in classes
- Prefer public attributes over private ones
- Inherit from collections.abc for custom container types
- (METACLASSES AND ATTRIBUTES) Use plain attributes instead of getter and setter methods
- Consider @property instead of refactoring attributes
- Use descriptors for reusable @property methods
- Use __getattr__, __getattribute__, and __setattr__ for lazy attributes
- Validate subclasses with __init_subclass__
- Register class existence with __init_subclass__
- Annotate class attributes with __set_name__
- Prefer class decorators over metaclasses for composable class extensions
- (CONCURRENCY AND PARALLELISM) Use subprocess to manage child processes
- Use threads for blocking I/O, avoid for parallelism
- Use
Lock
to prevent data races in threads
- Use
Queue
to coordinate work between threads
- Know how to recognize when concurrency is necessary
- Avoid creating new Thread instances for on-demand fan-out
- Understand how using Queue for concurrency requires refactoring
- Conside ThreadPoolExecutor when threads are necessary for concurrency
- Achieve highly concurrent I/O with coroutines
- Know how to port threaded I/O to asyncio
- Mix threads and coroutines to ease the transition to asyncio
- Avoid blocking the asyncio event loop to maximize responsiveness
- Consider concurrent.futures for true parallelism
- (ROBUSTNESS AND PERFORMANCE) Take advantage of each block in try/except/else/finally
- Consider contextlib and with statements for reusable try/finally behavior
- Use datetime instead of time for local clocks
- Make pickle reliable with copyreg
- Use decimal when precision is paramount
- Profile before optimizing
- Prefer deque for producer-consumer queues
- Consider searching sorted sequences with bisect
- Know how to use heapq for priority queues
- Consider memoryview and bytearray for zero-copy interactions with bytes
- (TESTING AND DEBUGGING) Use repr strings for debugging output
- Verify related behaviors in TestCase subclasses
- Isolate tests from each other with setUp, tearDown, setUpModule, and tearDownModule
- Use mocks to test code with complex dependencies
- Encapsulate dependencies to facilitate mocking and testing
- Consider interactive debugging with pdb
- Use tracemalloc to understand memory usage and leaks
- (COLLABORATION) Know where to find community-built modules
- Use virtual environments for isolated and reproducible dependencies
- Write docstrings for every function, class, and module
- Use packages to organize modules and provide stable APIs
- Consider module-scoped code to configure deployment environments
- Define a root Exception to insulate callers from APIs
- Know how to break circular dependencies
- Consider
warnings
to refactor and migrate usage
- Consider static analysis via
typing
to obviate bugs


This Mock Banking application was created as part of our fourth year final year project in Computing in Software Development in Galway-Mayo Institute of Technology.
Alan Niemiec
Age : 22
Nationality : Polish
County: Galway
Main area of expertise: Back-end, middleware, authentication
Worked with: API (NodeJS), AngularJS, Mongodb, Heroku, Auth0


|
ElfPSP_ParallelABC
Protein Structure Prediction using Parallel Artificial Bee Colony Optimization
|
Routines for manipulating the configuration YML file. More...
Go to the source code of this file.
Functions | |
| void | initialize_configuration () |
| Initializes configuration based on the configuration file. More... | |
Variables | |
| char * | HP_CHAIN |
| Check configuration.yml for documentation. More... | |
| int | EPS_HH |
| Check configuration.yml for documentation. More... | |
| int | EPS_HP |
| Check configuration.yml for documentation. More... | |
| int | EPS_HB |
| Check configuration.yml for documentation. More... | |
| int | EPS_PP |
| Check configuration.yml for documentation. More... | |
| int | EPS_PB |
| Check configuration.yml for documentation. More... | |
| int | EPS_BB |
| Check configuration.yml for documentation. More... | |
| int | PENALTY_VALUE |
| Check configuration.yml for documentation. More... | |
| int | N_CYCLES |
| Check configuration.yml for documentation. More... | |
| int | COLONY_SIZE |
| Check configuration.yml for documentation. More... | |
| double | FORAGER_RATIO |
| Check configuration.yml for documentation. More... | |
| int | IDLE_LIMIT |
| Check configuration.yml for documentation. More... | |
| int | N_HIVES |
| Check configuration.yml for documentation. More... | |
| int | RANDOM_SEED |
| Check configuration.yml for documentation. More... | |
Routines for manipulating the configuration YML file.
| void initialize_configuration | ( | ) |
Initializes configuration based on the configuration file.
| int COLONY_SIZE |
Check configuration.yml for documentation.
| int EPS_BB |
Check configuration.yml for documentation.
| int EPS_HB |
Check configuration.yml for documentation.
| int EPS_HH |
Check configuration.yml for documentation.
| int EPS_HP |
Check configuration.yml for documentation.
| int EPS_PB |
Check configuration.yml for documentation.
| int EPS_PP |
Check configuration.yml for documentation.
| double FORAGER_RATIO |
Check configuration.yml for documentation.
| char* HP_CHAIN |
Check configuration.yml for documentation.
| int IDLE_LIMIT |
Check configuration.yml for documentation.
| int N_CYCLES |
Check configuration.yml for documentation.
| int N_HIVES |
Check configuration.yml for documentation.
| int PENALTY_VALUE |
Check configuration.yml for documentation.
| int RANDOM_SEED |
Check configuration.yml for documentation.


new Client(email, apiKey)
Parameters:
| Name | Type | Description |
|---|---|---|
email |
string | Zulip account address |
apiKey |
string | Zulip API key |
Methods
-
getEvents(watchOptsopt)
-
Gets events from the subscribed queue
Parameters:
Name Type Attributes Description watchOpts
Object <optional>
Optional set of options to override defaults Properties
Name Type Attributes Default Description queueId
String <optional>
this.queueId The ID of a queue that you registered via registerQueue(). lastEventId
String <optional>
this.lastEventId The highest event ID in this queue that you've received and wish to acknowledge. dontBlock
String <optional>
false set to “true” if the client is requesting a nonblocking reply. If not specified, the request will block until either a new event is available or a few minutes have passed, in which case the server will send the client a heartbeat event. -
getUsers(callback)
-
Gets a list of all Zulip users in the realm
Parameters:
Name Type Description callback
function Callback function with (err, users) params -
registerQueue(opts, event_types, watchopt, watchOptsopt)
-
Register to receive Zulip events
Parameters:
Name Type Attributes Default Description opts
Object Register options per https://zulip.com/api/endpoints/ event_types
Array A JSON-encoded array indicating which types of events you're interested in. Values include message, subscriptions, realm_user, watch
Boolean <optional>
false If true, will automatically poll for events watchOpts
Object <optional>
Optional set of options to be passed to getEvents while polling -
sendMessage(opts, callbackopt)
-
Send a message
Parameters:
Name Type Attributes Description opts
Object Message options per https://zulip.com/api/endpoints/ Properties
Name Type Description type
String One of {private, stream} content
String The content of the message. Maximum message size of 10000 bytes. to
String In the case of a stream message, a string identifying the stream. In the case of a private message, a JSON-encoded list containing the usernames of the recipients. subject
String The topic for the message (Only required if type is “stream”). Maximum length of 60 characters. callback
function <optional>
Optional callback function with (err, results) params -
sendPrivateMessage(opts, callback)
-
Send a private message
Parameters:
Name Type Description opts
Object Message options per https://zulip.com/api/endpoints/ Properties
Name Type Description content
String The content of the mssage. Maximum message size of 10000 bytes. to
String A JSON-encoded list containing the usernames of the recipients. callback
function Optional callback function with (err, results) params -
sendStreamMessage(opts, callback)
-
Send a stream message
Parameters:
Name Type Description opts
Object Message options per https://zulip.com/api/endpoints/ Properties
Name Type Description content
String The content of the message. Maximum message size of 10000 bytes to
String A string identifying the stream. subject
String The topic for the message. Maximum length of 60 characters. callback
function Optional callback function with (err, results) params


Hi I'm Peter Jiang
This is my uid: 35543601
This is the template: retro
This is my email: peterbjiang@yahoo.com


Cuba Exhibits Lowest HIV/AIDS Prevalence of the Region (+Graphics)
by RHCCuba today exhibits the lowest prevalence of HIV/AIDS in Latin America and the Western Hemisphere, an official from the Ministry of Public Health (MINSAP) said.
Havana, Cuba.- The island maintains control in mother-to-child transmission, in children under 14, in heterosexual men and women, as well as in early detection and rigorous monitoring of cases diagnosed with the disease, Bárbara Venegas, an official from the Department of STIs/AIDS and Hepatitis of the Epidemiology Department said.
According to the specialist, of the total of 26,952 people living with HIV in the country, 80 % are male and 82% are between 20 and 54 years of age, while 87 % were diagnosed at an early stage of the disease, which allowed them to offer timely treatment.
LEARN MORE
HIV AND AIDS IN LATIN AMERICA THE CARIBBEAN REGIONAL OVERVIEW
According to Prensa Latina, Venegas highlighted men who have sex with men (5.6%) and transgender women (19.7%). are the most affected segments.
She noted that currently cases can be diagnosed anywhere in the country, which allows optimization of resources and faster and more effective medical care.
And although this year the number of cases decreased considerably, compared to 2018, there was an increase in the provinces of Cienfuegos, Las Tunas and Guantánamo.
With respect to the goal 90-90-90 set by Cuba for 2020 (that 90 percent of patients know their serological status, the same figure has access to treatment and eliminate almost 100 percent of transmission, with a minimum viral load) said that it has already reached 87-86-73.8, respectively.
In 2015 Cuba was declared the first country to eliminate mother-to-child transmission of HIV, and congenital syphilis and the sustained work in controlling the disease further demonstrates that it is possible to have future generations free of HIV. Achieving control of the epidemic is one of WHO's goals. (RHC)


R/response-functional.R
analyze_graph.Rd
The graph must contain edge attributes named "leftside" and "lrconnect" that takes values 0 and 1. Only one edge may have a value 1 for lrconnect. The shiny app returns a graph in this format.
analyze_graph(graph, constraints, effectt)
| graph | An aaa-igraph-package object that represents a directed acyclic graph |
|---|---|
| constraints | A vector of character strings that represent the constraints |
| effectt | A character string that represents the causal effect of interest |
A list with the following components. This list can be passed to optimize_effect which interfaces with Balke's code:
Character vector of variable names of potential outcomes, these start with 'q' to match Balke's notation
Character vector of parameter names of observed probabilities, these start with 'p' to match Balke's notation
Character vector of parsed constraints
Character string defining the objective to be optimized in terms of the variables
Matrix of all possible values of the observed data vector, corresponding to the list of parameters.
Matrix of all possible values of the response function form of the potential outcomes, corresponding to the list of variables.
### confounded exposure and outcome b <- igraph::graph_from_literal(X -+ Y, Ur -+ X, Ur -+ Y) V(b)$leftside <- c(0,0,0) V(b)$latent <- c(0,0,1) E(b)$rlconnect <- E(b)$edge.monotone <- c(0, 0, 0) analyze_graph(b, constraints = NULL, effectt = "p{Y(X = 1) = 1} - p{Y(X = 0) = 1}")#> $variables #> [1] "q00" "q01" "q02" "q03" "q10" "q11" "q12" "q13" #> #> $parameters #> [1] "p00_" "p10_" "p01_" "p11_" #> attr(,"key") #> [1] "XY_" #> attr(,"rightvars") #> [1] "X" "Y" #> attr(,"condvars") #> character(0) #> #> $constraints #> [1] "q00 + q01 + q02 + q03 + q10 + q11 + q12 + q13 = 1" #> [2] "q00 + q02 = p00_" #> [3] "q10 + q11 = p10_" #> [4] "q01 + q03 = p01_" #> [5] "q12 + q13 = p11_" #> #> $objective #> [1] "q02 + q12 - q01 - q11" #> #> $p.vals #> X Y #> 1 0 0 #> 2 1 0 #> 3 0 1 #> 4 1 1 #> #> $q.vals #> X Y #> 1 0 0 #> 2 1 0 #> 3 0 1 #> 4 1 1 #> 5 0 2 #> 6 1 2 #> 7 0 3 #> 8 1 3 #>