-
Can computers acquire all the major capabilities used by mathematicians and the
mathematics community in the discovery and proof of
mathematical results and concepts?
- When? How?
- Computers are already used in several ways.
- Advances in Theorem Proving and capabilities in other cognitive domains that suggests they can do much more.
- Automated theorem proving is closely related to computer verification of
proofs.
A concrete prediction
-
Open bet by Christian Szegedy, Google Research.
-
By the year 2029:
"A diverse set of 100 graduate text books are automatically formalized/verified in a popular proof assistant (eg Lean). 10% of problems from a preselected 100 open human conjectures is proved completely autonomously."
Ingredients for Automation
Universal deducer?
- A universal deducer is a program which, given a
mathematical statement, either proves it is true or proves it is false.
- By results of Church, Gödel, Turing, such a program is impossible.
- We can seek to build ever more powerful systems that (help in) finding (and verifying) ever more powerful proofs.
- This will involve advances of many different kinds in combination.
Algorithms
- Numerical computation.
- Enumeration: a large number of problems of the same form.
- Symbolic and computational algebra.
- Compact enumeration.
- Exact real number arithmetic.
- Linear programming.
- Decidability of real semi-algebraic geometry.
- Many algorithms for specific mathematical questions based on mathematical theorems.
Deduction Engines
- SAT solvers can solve logical problems with finitely many Boolean variables.
- Many finite problems can be reduced to SAT.
- SMT solvers extend SAT solvers with various algorithms.
- Resolution Theorem Provers can in principle solve any problem in first-order logic, which encodes all of mathematics.
- In practice, all these have difficulty handling mathematics in the large.
Interactive Theorem Provers
- In Interactive Theorem Provers, proofs are
obtained by human-machine
collaboration.
- The computer both finds (parts of) proofs and verifies
correctness.
- The ease of proving in such systems depends on how concise
and composable proofs are and
the strength of its automation.
- The power and ease of use also depends on the library – the results that are already in the system.
- The system thus accumulates knowledge and ways to use it effectively.
Artificial Intelligence
- Manage tasks for which we depend on experience, tacit knowledge.
- Work with limited or unstructured data.
- Learn and use composable representations.
- Use analogies.
- Share learning between tasks.
- Handle long range dependencies.
- Work with a small number of task-specific examples.
- But: will give some nonsensical answers.
Some computer-assisted proofs
- Four-colour problem: Any map can be coloured with at most $4$
colours.
- Kepler Conjecture: The most efficient way to pack spheres is
the hexagonal close packing.
- Boolean Pythagorean triples problem: Is it possible to colour
the
positive integers either red or blue, so that if three integers $a$, $b$, $c$,
satisfy $a^{2}+b^{2}=c^{2}$, they are not all the same colour?
- Smale conjecture for hyperbolic $3$-manifolds.
Robbins conjecture
- Robbins conjecture was a conjectural characterization of
Boolean algebras in
terms of
associativity and commutativity of $\vee$ and the Robbins equation
$\neg(\neg(a\vee b)\vee \neg(a \vee \neg b)) = a$.
- This was conjectured in the 1930s, and finally proved in 1996 using the
automated theorem prover EQP.
- So far, this seems to be the only major success of fully
autonomous deductive theorem provers.
The $N-$Queens problem
-
The $N-$queens puzzle is the problem of placing $N$ chess queens on an $N\times N$ chessboard
so that no two queens threaten each other.
-
Thus, a solution requires that no two queens share the same row, column, or diagonal.
- We formulate this as a so called Boolean satisfiability (SAT) problem.
- A SAT solver solves SAT problems.
- A very large class of problems can be formulated as SAT problems.
$N$-Queens as SAT
- We associate to each square a boolean variable $Q_{i,j}$ which is true iff the
square is occupied.
- We construct logical formulas for the constraints of the $N-$queens puzzle from the
$Q_{i,j}$'s using operators $\neg$ (not), $\vee$(or) and $\wedge$(and).
- For example, the $i$th row has a queen is the formula $Q_{i,1}\vee Q_{i,2}\vee\dots\vee Q_{i,n}$
- Similarly, pairs of queens not threatening each other gives formulas such as $\neg Q_{1, 1}\vee
\neg Q_{2, 2}$.
SAT Problems
- We are given finitely many boolean variables $P$, $Q$, ... and finitely many
constraints on them.
-
Constraints are logical statements built from the variables using logical operators such as
$\neg$ (not), $\vee$(or), $\wedge$(and),
$\Rightarrow$(implies) and $\Leftrightarrow$ (equivalent).
-
The SAT (boolean satisfiability) problem asks whether we can assign
truth values to these (i.e., declare each of $P$, $Q$ , ... to be $true$ or $false$) so that all
the constraints are satisfied.
SAT and $P\overset{?}=NP$
-
Given a solution to a SAT problem, it is easy to see that it satisfies all the constraints.
-
However, finding a solution may be hard.
-
Algorithmic problems that can be solved in polynomial time form the class
$P$ (polynomial).
-
Algorithmic problems whose solution, if it exists, can be checked in polynomial
time form the class $NP$ (non-deterministic polynomial).
- A fundamental question is whether $P = NP$.
Cook-Levine theorem
- The Cook-Levine theorem from the early 1970s showed that if SAT can be solved in
polynomial time
then so can every problem in $NP$.
-
There are a large class of problems that are known to be $NP$, making $P=NP$ a very important
question.
-
In practice, computer scientists have focussed efforts on making practically fast SAT solvers,
which are
used to solve (components of) many different problems by mapping them to SAT.
Resolution and the DPLL algorithm
-
The formulation of $N$-Queens above was as a collection of clauses, i.e., in CNF.
- Any SAT problem can be formulated in CNF.
- Davis and Putnam showed that a deduction rule called Resolution is refutation complete for SAT, and indeed for First-Order Logic.
-
The DPLL algorithm refines the algorithm of Davis-Putnam for SAT.
-
Together with Robinson's unification, the Davis-Putnam work gives Resolution Theorem Provers, which can deduce any provable theorem.
SAT Solver-Prover in Lean 4
-
In Lean 4,
we can have a program with output one of
-
a solution together with a proof that this is a solution, or
-
a proof that there is no solution.
-
Furthermore, the compiler verifies that the program terminates for any valid input, and has
correct output of one of the above two forms.
- I implemented this in a program SATurn.
- This was the first time in my experience that such a complex program ran correctly straight away.
Z3 Demo: Sudoku
Euclidean Geometry via SMT?
-
In the 1950s, Tarski proved that whether a collection of polynomial equations and inequations has solutions that are real numbers is decidable.
- Statements in Euclidean geometry can be translated to such problems.
- Tarski’s algorithm has been greatly improved, and algorithms of a more algebraic nature have also been developed, improved and implemented.
-
However, I could not find any examples of using SMT solvers for such problems.
Pappus hexagon theorem
Theorem: $P$, $Q$ and $R$ are collinear.
-
Points with coordinates $(x_1, y_1)$, $(x_2, y_2)$ and $(x_3, y_3)$, which we assume to be distinct, are collinear if and only if $(y_2 - y_1)(x_3 - x_1) = (y_3 - y_1)(x_2 - x_1).$
- As a warm up, we show that for $P= (x, y)$, $P$, $O=(0, 0)$ and $-P$ are collinear.
- To do this, we seek $x$ and $y$ so that $P$, $O$ and $-P$ are not collinear, and check for solutions.
-
Indeed Z3 and CVC4 concluded instantly that there is no solution, i.e., the points are collinear.
- We scale and rotate to obtain nice coordinates
-
We can take $a=(1, 0)$, $b= (1 + u, 0)$, $c = (1 + u + v, 0)$ with $u, v > 0$.
- Let $A = (x_A, y_A)$, then $B = (x_A(1+ U), y_A(1 + U))$ and $C = (x_A(1+ U + V), y_A(1 + U + V))$ with $U, V, y_A > 0$.
- We let $P=(P_x, P_y)$, $Q=(Q_x, Q_y)$ and $R= (R_x, R_y)$, giving $12$ variables in all.
- We get $6$ equations for collinearity, e.g. of $A$, $P$ and $b$.
-
We also have various positivity inequations.
- We negate the equation for $P$, $Q$ and $R$ being collinear and ask if there is a solution.
-
Unfortunately when I ran Z3 with this system it did not give a result.
- I blogged about this formulation and result.
- A couple of days later Anand Rao Tadipatri emailed me that he had got Z3 to prove Menelaus’s Theorem along similar lines.
-
Strangely, I could not replicate his result.
-
It turns out that Z3 can solve both theorems if only asked for an answer, but neither if asked for a proof.
Computer Verification for Mathematics
Rigour and Proofs
- While in principle mathematical proofs are logical deductions, in practice they are semi-formal.
- The level of rigour is a compromise between being correct (or at least fixable) a large fraction of the time and advancing knowledge.
- Mathematics has various error-correcting mechanisms that keep the error rate fairly low, but this gets harder with growing complexity.
- And indeed, even at the highest level errors are not uncommon.
- Around 2002, a very interesting theorem was proved showing that $s^5$ had a certain structure.
- This was published in the Annals of Mathematics.
- In a sequel some years later, the authors constructed a family of such structures.
- The referee of the sequel observed that the space on which the structures were constructed, including the original one, was not $S^5$.
- This is not an isolated example – there are papers in the Annals contradicting each other.
Interactive Theorem Provers
- Interactive Theorem Provers are software systems where proofs are
obtained by human-machine
collaboration.
- The computer both finds (parts of) proofs and verifies
correctness.
- Using these one would obtain a super-human level of correctness.
- With advances in such systems and their libraries, especially Lean and Mathlib, one hopes this is without super-human effort.
Who guards the guards?
-
A computer verified proof is only as trustworthy as the system that verified the proof.
-
Following the de Bruijn principle, proofs are verified by a small trusted
kernel, which can be thoroughly checked.
-
For example, the lean theorem prover has three (small) proof checkers written in three
languages.
-
In a specific case, one only has to check that the definitions and the statement are correct, which is typically not hard especially if they use a library.
The Liquid Tensor experiment
- In December 2020, Peter Scholze challenged the formalization community to computer verify a foundational result he had proved, part of Clausen-Scholze's Condensed Mathematics.
- This was taken up by the Lean community led by Johann Commelin, with active collaboration from Scholze.
— I want to make the strong claim that in the foundations of mathematics, one should replace topological spaces with condensed sets ... This claim is only tenable if condensed sets can also serve their purpose within real functional analysis.
— with this theorem, the hope that the condensed formalism can be fruitfully applied to real functional analysis stands or falls. I think the theorem is of utmost foundational importance, so being 99.9% sure is not enough.
— if it stands, the theorem gives a powerful framework for real functional analysis, making it into an essentially algebraic theory... Generally, whenever one is trying to mix real functional analysis with the formalism of derived categories, this would be a powerful black box. As it will be used as a black box, a mistake in this proof could remain uncaught.
— I spent much of 2019 obsessed with the proof of this theorem, almost getting crazy over it. In the end, we were able to get an argument pinned down on paper, but I think nobody else has dared to look at the details of this, and so I still have some small lingering doubts.
— as I explain below, the proof of the theorem has some very unexpected features. In particular, it is very much of arithmetic nature. It is the kind of argument that needs to be closely inspected.
— while I was very happy to see many study groups on condensed mathematics throughout the world, to my knowledge all of them have stopped short of this proof. (Yes, this proof is not much fun…)
— I have occasionally been able to be very persuasive even with wrong arguments. (Fun fact: In the selection exams for the international math olympiad, twice I got full points for a wrong solution. Later, I once had a full proof of the weight-monodromy conjecture that passed the judgment of some top mathematicians, but then it turned out to contain a fatal mistake.)
— the Lean community has already showed some interest in formalizing parts of condensed mathematics, so the theorem seems like a good goalpost.
— I think this may be my most important theorem to date. (It does not really have any applications so far, but I’m sure this will change.) Better be sure it’s correct…
Results of the Experiment
-
In about six months, a major step, Theorem 9.4 of the notes was proved.
-
Scholze said this was the part where he was worried about, and that he was now satisfied that the correctness of his result was checked.
-
About an year later, the origin goal, Theorem 9.1 was proved in Lean.
Sums of reciprocals
-
In December 2021, Thomas Bloom proved that any set of natural numbers of positive upper density contains a finite subset whose reciprocals add up to $1$, answering a question of Erdős and Graham.
-
While his paper was still under review, Thomas Bloom
learnt Lean, and,
along with Bhavik Mehta, formalized this theorem in Lean.
Kaplansky's Unit Conjecture
-
About an year ago, Giles Gardam disproved the long-standing Kaplansky's Unit Conjecture, which asserted that group rings of torsion-free groups over fields do not have non-trivial units.
-
Gardam used a SAT solver to find such non-trivial units for a specific group and the field $\mathbb{F}_2$.
-
Anand and I formalized the proof in Lean 4 using its integration of programs and proofs.
-
We proved some results that were not formally needed, such as the ring properties of the group ring, as an extra check on our definitions.
Formal methods
Mathematical proofs elsewhere
Formal methods
- We specify (describe) software, hardware etc. in precise
mathematical terms.
- We give mathematical proofs of correct behavior, which are
computer
verified.
- This gives a much greater certainty of correctness.
- However, proofs are much harder than tests.
- Formal proofs use interactive theorem provers; with better provers we can
prove more often.
Do we need completely correct always?
| |
Pentium FDIV Bug |
Fixing an error is very costly |
| |
Therac 25 radiation machine |
Safety critical |
| |
WhatsApp Pegasus attack |
A bug is a vulnerability |
Some users of formal methods
| |
Intel Chips |
Fixing an error is very costly |
| |
Paris driverless metro |
Safety critical |
| |
Scala dotty compiler |
A bug is a vulnerability |
Programming a Computer for Playing Chess
- Playing Chess can be based on
- judging the value of a fixed players position.
- a policy: sequences of moves to consider.
- We compute (and use) the value at the end of sequences moves we consider.
- We recursively decide the best moves
by minimax — alternately maximizing and minimizing.
- We refine using various heuristics, such as quiescence search
and
$\alpha-\beta$ pruning.
- Openings give a policy, as do
endgame tables.
Kasparov vs Deep Blue
- In 1997, a computer Deep Blue defeated the Chess world champion Gary Kasparov.
- Deep Blue was based on extending the above methods to elaborate (rule
based) values and policies (chess theory), and improved heuristics.
- However, Deep Blues was very limited in certain capabilities.
- The value and policy functions of Kasparov were far better, but compensated
for by Deep Blue being able to consider far more move sequences.
AlphaGo vs Lee Sedol
- In the chinese game Go, the number of legal moves is much larger, so
trying everything means we cannot look many moves ahead.
- More importantly, it is very hard to describe a good value function (we use
tacit knowledge).
- This makes it far harder for computers.
- Yet, in March 2016, a Go playing system AlphaGo defeated 18-time world
champion Lee Sedol.
- In January 2017, AlphaGo defeated the world number one Ke Jie
comprehensively.
AlphaGo and Learning
- The policy and value functions of AlphaGo are deep neural networks
that were
trained.
- The policy network was initially trained by learning to predict the next move
from
games
of expert players (behaviour cloning).
- The value network was trained by AlphaGo playing against versions of itself.
- AlphaGo considered fewer sequences of moves than Deep Blue.
- AlphaGo came up with unexpected moves.
AlphaGo Zero and Alpha Zero
- AlphaGo was succeeded (and defeated) by AlphaGo Zero, which learnt
purely by
self play.
- Its successor, AlphaZero, could master a variety of similar games
starting with
just the rules.
- AlphaZero took just 4 hours to become the strongest chess player on the planet
(beating a traditional chess program, Stockfish).
- AlphaZero “had a dynamic, open style”, and “prioritizes
piece
activity over material, preferring positions that looked risky and aggressive.”
Artificial Intelligence elsewhere
Word Embeddings
-
To give words a structure and capture relations, words are embedded as points
in space.
- To do this, (in Word2Vec) we set up the problem of predicting a word given its
neighbours.
- We look for solutions of this problem that involve mapping words into space, and predicting from
neighbours using the points.
- Analogies such as Paris is to France as Madrid is to
Spain are captured by vector operations.
Generative Adversarial Network
- These consist of a pair of networks, contesting with
each other.
- One network generates candidates (generative) and
the other evaluates them (discriminative).
- For example the discriminative network tries to
distinguish between real images and synthetic ones
generated by the generative network.
Attention is all you need
- The meaning of a word depends on the context, i.e., other words surrounding it.
- In the transformer architecture, this is captured by learning
to which other words to pay attention for determining the next representation.
- The encoding of words includes position vectors, defined by using harmonics.
- This has lead to revolutionary improvements, including forming the basis for GPT
3.
- Attention networks are used in AlphaFold 2.
Artificial Intelligence
for
Mathematical Proofs?
-
First-order logic theorem provers (based on Resolution, SAT solvers) are very powerful at deducing consequences of a small set of premises.
- The main limitation is premise selection – choosing the already proved results from which to deduce.
- In DeepMath, deep learning is used effectively for this task.
LLMs/Foundation models
- These are based on the Transformer architecture.
- They are pre-trained on a huge dataset and may be fine-tuned on a more specific one.
- For a specific task, often a small prompt (typically some examples) is enough.


By Jen Strickland
Only through keyboard for now :(
* Ctrl or Shift actually. Only Shift works in Opera.
TL;DR
Bonus: it’s more efficient and cost-effective to have accessibility figured out before development or launch, opposed to hacking add-on’s or addressing a lawsuit.
A great experience is performant, usable, and ought to be so for all.
This talk outlines a design process prioritizing performance and accessibility from the beginning of your project, including:
“Design in the browser” methodology

First Level Heading

Second Level Heading

Admittedly, a simplistic example.

“Design in the browser” methodology
<form> Label <input type="text" id="sample" name="sample" /> </form>
QA for accessibility and performance throughout


Jan 2018 - Ongoing
Demonstrate my expertise as a designer, through a fully customizable and reliable platform.
After spending hours trying to use a website service to create my portfolio, there was a glitch and suddenly, those hours disappeared and I lost everything! Feeling betrayed, I decided coding my own website might be a more reliable route. Thanks to Github Pages and their Student Developer Pack, I can have full control over both design and development of my personal website.
Also, I'm interested in becoming a UX designer, but I would also like to see what it's like from a developer standpoint, as I will likely be working with coders who will implement my designs. Stepping into the role of both designer and developer has not been easy, but every day, I allot a bit of time to practice HTML, CSS, and Bootstrap.
I am a big fan of using the "inspect" tool as well, so when I'm visiting a website I am inspired by, I will see exactly what their CSS and HTML looks like to achieve similar results.
Lastly, inspiration is a way that I keep myself motivated to work on my website. Seeing successful website design drives me to not only continue learning to code, but also keeps me excited about experts impletment the latest UX trends. Awwwards and CSS Design Awards are my go-to's for inspiration.
For qualitative research, I am constantly seeking feedback from my peers, professors, and friends. Some helpful insights I have gathered through these conversations include:
For quantitative research, I have been using Google Analytics to see site behavior. Though I am still learning how it works, I am hoping to analyze and transform findings from click data into a more user-friendly website design.
By placing a thin boarder around each card on the homepage, I establish a cleaner, more unified look for the cards with various colors and projects.
By default, hyperlinks will simply underline the text to indicate clickability, but I used a highlighting roll-over animation for each portfolio piece. This further adds to the overall theme of my website.
Additionally, to make the project pages quicker to digest, I included overview cards at the top of each page with important contextual information. (Timeline, Task, Toolbox, and sometimes Team).
Lastly, I have decreased the average line length for the bodycopy for each paragraph. To create a comfortable reading experience, I shoot for about 8 - 12 words per line.
It's been difficult, but the more I practice, the more I see web design as an expression of creativity, and a medium for creating whatever your heart desires.
My goal for this personal project are:
This is an ongoing project, so stay tuned to see this website evolve!


Here is the famicity tree. Click
help
to show the help slides.
Create your tree by adding and inviting your family
Use their email or phone number to invite them
Press to add a love one
Let's go!
●
●
●
●


Searching for someone to hire as a freelance developer on your project, or looking to fill a spot at your company, you'll find what you need right here.
View Resume/CV Portfolio Examples Request a QuoteIn my implementation of the famous fizz buzz challenge, I removed redundancy as much as I could to demonstrate the DRY principle.
githubIn my implementation of the famous fizz buzz challenge, I removed redundancy as much as I could to demonstrate the DRY principle.
githubIn my implementation of the famous fizz buzz challenge, I removed redundancy as much as I could to demonstrate the DRY principle.
githubIn my implementation of the famous fizz buzz challenge, I removed redundancy as much as I could to demonstrate the DRY principle.
github


English
My Page
Logout
ITC
Home
About
Program
Join
Sponsor
News
CC Campaign
Join the fight against Prejudice!!
Help stop the disinformation and the killing of grandfathers
Join The Movement


browsers perfs
A - Rendering process
Rendering: repaint, reflow/relayout, restyle - www.phpied.com - 2009
- reading HTML -> DOM tree
- reading CSS -> CSS model
- they are both merged in the render model (or render tree)
- the render model is paint (or draw) in the browser viewport
reflow
Parts of the render tree (or the whole tree) will need to be revalidated and the node dimensions recalculated.
Reflow is also named layout, relayout, or layouting.
repaint
Parts of the screen will need to be updated, either because of changes in geometric properties of a node or because of stylistic change, such as changing the background color.
Repaint is also named repaint.
repaint / reflow triggers
- Adding, removing, updating DOM nodes
- Hiding a DOM node with
display: none
(reflow and repaint) orvisibility: hidden
(repaint only, because no geometry changes) - Moving, animating a DOM node on the page
- Adding a stylesheet, tweaking style properties
- User action such as resizing the window, changing the font size, or (oh, OMG, no!) scrolling
browsers optimization
They batch the changes has much as they can.
But sometimes the script may prevent the browser from optimizing the reflows, and cause it to flush the queue and perform all batched changes. This happens when you request style information, such as
offsetTop
,offsetLeft
,offsetWidth
,offsetHeight
scrollTop
/Left/Width/HeightclientTop
/Left/Width/HeightgetComputedStyle()
, orcurrentStyle
in IE
Because the browser has to give you the most up-to-date value.
minimizing repaints and reflows
- Don’t change individual styles, one by one.
- Batch DOM changes and perform them “offline”. Offline means not in the live DOM tree.
- using (
documentFragment
) - using
display: none
before making the changes then restore the display
- using (
- Don’t ask for computed styles excessively. (var caches)
- In general, think about the render tree and how much of it will need revalidation after your change.
B - Layout trashing
Preventing ‘layout thrashing’ - wilsonpage.co.uk - 20130919
Explain how to optimize repaints / reflows.
Introduce fastdom lib to industrialize optimizations.


|
|
#include <pantheios/util/memory/auto_buffer_selector.hpp>
stlsoft::auto_buffer
.
There are two reasons for this:
stlsoft::auto_buffer
. Using pantheios::auto_buffer_selector makes Pantheios code independent of such compilers' behavioural odities.Public Types | |
| typedef stlsoft::auto_buffer < T, A, N > | type |
| The generated type. |
| typedef stlsoft::auto_buffer<T, A, N> type |
The generated type.
|
|
|
| pantheios Library documentation © Matthew Wilson & Synesis Software, 2006-2011 |


tools
for all your shitposting needs
clap post generator
owo text genyewatow
I am very smart text generator


Component allows to choose a value from a limited range
formControl.disable()
)
TuiSliderModule
in the same module where you want
to use our component:
Declare a form (FormGroup
) or a control
(FormControl
) in your component:
Add to the template:


| MATLAB 文件帮助: cv.calcHist | 查看 cv.calcHist 的代码 | Index |
calcHist Calculates a histogram of a set of arrays
H = cv.calcHist(images, ranges)
H = cv.calcHist(..., 'OptionName',optionValue, ...)
uint8
, uint16
,
or single
) and the same row/column size. Each of them can have an
arbitrary number of channels. Note that passing {img1, img2, ...}
as
input is similar to using cat(3, img1, img2, ...)
, i.e the function
computes the histogram from channels of input arrays.N
(histogram dimensionality) of the
histogram bin boundaries in each dimension.Uniform=true
), then for each
dimension i
it is enough to specify the lower (inclusive) boundary
L(1) = ranges{i}(1)
of the first histogram bin and the upper
(exclusive) boundary U(n) = ranges{i}(end)
for the last histogram
bin HistSize(i)
. That is, in case of a uniform histogram each of
ranges{i}
is an array of 2 elements forming an interval [L,U)
which is automatically divided according to HistSize(i)
.Uniform=false
), then each of
ranges{i}
contains HistSize(i)+1
elements, specifying the bin
edges of dimension i
: L(1), L(2), ..., L(n), U(n)
forming the
half-open intervals:
[L(1), U(1)), [L(2), U(2)), ..., [L(n-1), U(n-1)), [L(n), U(n))
where U(1)==L(2), U(2)==L(3), ..., U(n-1)==L(n)
, and n
is the
histogram size of the current dimension (n = HistSize(i)
). The
array elements, that are not between L(1)
and U(n)
, are not
counted in the histogram.single
(N
is the histogram dimensionality that must be
positive and not greater than 32 in the current OpenCV version). The
size of the output N-D array is
HistSize(1)-by-HistSize(2)-by-...-by-HistSize(N)
.N
. The first array channels are numerated from 0
to
size(images{1},3)-1
, the second array channels are counted from
size(images{1},3)
to size(images{1},3) + size(images{2},3)-1
, and
so on. By default, all channels from all images are used to compute
the histogram, i.e default is 0:sum(cellfun(@(im)size(im,3), images))-1
when input images
is a cell array, and 0:(size(images,3)-1)
when
input images
is a numeric array.images{i}
. The non-zero
mask elements mark the array elements (pixels) counted in the
histogram. Not set by default.Uniform
flag. Default is cellfun(@numel,ranges)-1
.ranges{i}
is
divided into HistSize(i)
uniform bins. The interval is divided into
bins using equally-spaced boundaries defined as:
ranges{i} = linspace(ranges{i}(1), ranges{i}(end), HistSize(i)+1)
.ranges{i}
is used as is for the
bin boundaries without considering HistSize
.H
. If it is set, the output histogram is
initialized with it instead of being cleared in the beginning when it
is allocated. This feature enables you to compute a single histogram
from several sets of arrays, or to update the histogram in time.
Not set by default.The function cv.calcHist calculates the histogram of one or more arrays. The elements of a tuple used to increment a histogram bin are taken from the corresponding input arrays at the same location.
The sample below shows how to compute a 2D Hue-Saturation histogram for a color image:
hsv = cv.cvtColor(img, 'RGB2HSV');
edges = {linspace(0,180,30+1), linspace(0,256,32+1)};
H = cv.calcHist(hsv(:,:,1:2), edges);
Here is another example showing the different options:
% read some image, and convert to HSV colorspace
imgRGB = imread(fullfile(mexopencv.root(),'test','img001.jpg'));
imgHSV = cv.cvtColor(imgRGB, 'RGB2HSV');
% quantize the hue to 30 levels, and the saturation to 32 levels
histSize = [30, 32];
hranges = linspace(0, 180, histSize(1)+1); % hue varies from 0 to 179
sranges = linspace(0, 256, histSize(2)+1); % sat varies from 0 to 255
ranges = {hranges, sranges};
% one way
H = cv.calcHist(imgHSV(:,:,[1 2]), ranges);
% another way
H = cv.calcHist(imgHSV, ranges, 'Channels',[1 2]-1, 'HistSize',histSize);
% or similarly
H = cv.calcHist({imgHSV(:,:,1), imgHSV(:,:,2)}, {[0,180], [0,256]}, ...
'HistSize',histSize, 'Uniform',true);
% show H-S histogram
imagesc(H, 'YData',[0 180], 'XData',[0 256])
axis image; colormap gray; colorbar
ylabel('Hue'); xlabel('Saturation'); title('Histogram')


{% extends "base.html" %} {% load i18n %} {% load gravatar %} {% block title %}{% trans "Sustainability" %}{% endblock %} {% block content %} {% include 'donate/progress.html' with done=True %}
We will continue to keep donations open in case you missed your initial chance. That money will go to the next set of work after this 3 month trial.
Read the Docs has grown substantially since its beginning as a weekend project. Today, we:
We host projects from all languages and programming communities. Some examples of projects that we host include:
Because of the growth and popularity of the service, the associated technical and operational support demands a good deal of labor. Where development can be sustained with community contributions, consistent support for users, maintenance, and on-call procedures require accountability and dedicated engineers. These types of roles are hard to accomplish on a volunteer basis.
To make sure these roles were filled, we decided to treat the project as a job – we formed a company and dedicated ourselves full-time to the project. Now, we would like to make sure that the service is sustainable and its costs are covered.
We are asking for your contributions to ensure continued operational and technical support for our community, as well as continued development.
Our primary goal is to cover the costs of supporting and maintaining Read the Docs for the next three months. We hope to account for the cost of at least one full-time engineer, which, at the rate of $50/hour, would cost $24,000 over the next three months. Covering labor costs would allow us to spend time supporting the site instead of seeking income elsewhere.
Our servers are graciously sponsored by Rackspace, at a value of $2,000 each month. They are our single largest sponsor, and Read the Docs wouldn't be possible without their generous support. You can view the full list of past sponsors in our documentation.
If you are a company that shares our passion for documentation, or if you want to support our mission, contact us for more information on sponsoring Read the Docs.
Below is a list of all the wonderful people who have supported our vision.
This program is modeled after the fantastic Django Fellowship. Thanks for the inspiration.
{% endblock %}


WHAT LIES BENEATH RATING: 8/10 --> Great Movie
For more reviews and movie screensavers, visit http://www.joblo.com/
So where the heck has Robert Zemeckis been? Ever since 1994's Oscar triumph of FORREST GUMP, the man only managed to deliver one other flick onto the world via Jody Foster and her CONTACT with aliens in 1997. Now comes the new millennium, and Bobby decides to spring two big flicks our way. The first is this film, a thriller starring two major stars in Harrison Ford and Michelle Pfeiffer and come Christmas, expect to see Zemeckis buddy Tom Hanks star in the highly anticipated CAST AWAY. And if this film is any indication, Zemeckis should always take this much time between movies.
PLOT: The life of a happily married couple living in Vermont is suddenly jarred from its foundation when an entity (yes, that's right people, a ghost!) invades their home. The haunting is particularly geared towards the wife, who just can't seem to figure out what the heck is going on. The workaholic husband is also worried, but mostly because he thinks that his wife is going bonkers. Together, the couple attempt to solve the mystery of their haunted home.
CRITIQUE: A well-crafted thriller, this movie delivers on various fronts including the creepy suspense, the cheap scares via the excellent camerawork, the superior score, the even better use of silence, the solid acting card punched in by one Michelle Pfeiffer and the ending which grabbed me by the nuts and refused to let go. Does anybody remember a director by the name of Alfred Hitchcock? (sarcasm, folks). Well, Robert Zemeckis sure does and he's made certain to watch every single one of his movies in order to recreate a lot of that superb Hitchcockian feel, and by golly, it seems to have worked. But before I unwillingly make this film feel like a thrill-ride, please understand that it isn't one by any means, in fact, the only real "action" in the film takes place during its final half hour. This film works in a different way. It's slow, methodical and even a little longer than it should be, but once it gets going, I was hooked with a line and a sinker. Even Ford manages to make us forget RANDOM HEARTS for a couple of hours, and effectively emotes more than one feeling in this film (hey, it's a start!). And the story, you may ask?
Well, I can't honestly say that this film is original. In fact, it's not. I recognized various elements from other suspense features roaming around in this one, with the strongest vibes resounding from REAR WINDOW, FATAL ATTRACTION and PSYCHO. Okay, the last one is probably because the "bathtub" scene in this film is comparable to the shower scene in the latter, but only because it might actually instill a fear in some people to take more baths. Actually, there is a more than obvious homage to PSYCHO as well, so I don't think Zemeckis is trying to fool anybody here. But unoriginality aside, the film does work and work very well indeed. I personally am not a very jumpy person, but Mrs. JoBlo was bouncing off the walls at every other "boo!" moment presented in the film, and so were quite a few others. The film is extremely effective in that non-teen horror flick kinda way because it actually manages to creep you out before deafening the room with its deadly silence, and then boom! Fun stuff. The last thirty minutes also slapped me silly with appreciation for the work of the man behind the camera, and an excellent ending which had its twists and turns, some very tense moments and a satisfying resolution.  This lady is bursting with talent, secures you in the film with her appearance as an everyday woman, and is completely gorgeous to boot! Wow. Give her an Oscar already, goddamit!
Don't go see this movie if you're the type of person who is gonna be asking your cinema partner the same question every two minutes "why don't they just leave the house if it's haunted?". Listen friends, this is a movie. Work with a little suspension of disbelief (or naivete in this scenario) and enjoy the movie for the creeps that it does manage to sway in you. It's kinda like the movie that THE HAUNTING was billed as being, but wasn't even close. And this one might actually scare you crapless if sitting at home alone in the dark. Take a friend, squeeze an arm (or whatever else is close) and enjoy the first great thriller of the summer.
PS: Pooh on the damn marketing people at Dreamworks for spoiling a good chunk of this film for everyone. It would've been nice NOT to know some of the things that they give away in the trailer, but alas, tis the business of show, and I guess that's all part of the biz.
Review Date: July 13, 2000 Director: Robert Zemeckis Writer: Clark Gregg Producers: Robert Zemeckis, Steve Starkey and Jack Rapke Actors: Michelle Pfeiffer as Claire Harrison Ford as Norman Genre: Thriller Year of Release: 2000 ------------------------------------ JoBlo's Movie Emporium http://www.joblo.com/ ------------------------------------ (c) 2000 Berge Garabedian
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object coins.simd.Util
Utility class for SIMD optimization classes.
| Constructor Summary | |
(package private) |
Util()
|
| Method Summary | |
static void |
abort(java.lang.String s)
Prints an error message and aborts. |
static void |
assert2(boolean p,
java.lang.String s)
Tests a condition, and prints messages and exits if it is false. |
static void |
assert2(boolean p,
java.lang.String s,
int lineno)
Tests a condition, and prints messages and exits if it is false. |
static java.util.Vector |
blkToVecs(BasicBlk blk)
|
(package private) BiList |
findTargetLir(LirNode root,
int opCode,
BiList l)
Search and find the LIR nodes which has the specified operation code. |
static void |
printBlk(BasicBlk blk)
|
static void |
revV(java.util.Vector v)
|
static void |
sorry(boolean p,
java.lang.String s)
Tests a condition, and prints a message and exits if it is true. |
static void |
vecsToBlk(BasicBlk blk,
java.util.Vector vs)
|
static void |
warn(java.lang.String s)
Prints an error message. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Constructor Detail |
Util()
| Method Detail |
BiList findTargetLir(LirNode root, int opCode, BiList l)
root
- The root node of the searchopCode
- The specified operation codel
- The list which is stored in the found LIR node
public static void assert2(boolean p, java.lang.String s, int lineno) throws SimdOptException
p
- boolean which represents a condition.s
- String which represents a description of the condition.lineno
- int which represents a line number.
SimdOptException
public static void assert2(boolean p, java.lang.String s) throws SimdOptException
p
- boolean which represents a condition.s
- String which represents a description of the condition.
SimdOptException
public static void abort(java.lang.String s) throws SimdOptException
s
- Strint which represents an error message.
SimdOptException
public static void sorry(boolean p, java.lang.String s) throws SimdOptException
p
- boolean which represents a condition.s
- String which represents an error message.
SimdOptException
public static void warn(java.lang.String s)
s
- String which represents an error message.public static void printBlk(BasicBlk blk)
public static java.util.Vector blkToVecs(BasicBlk blk)
public static void vecsToBlk(BasicBlk blk, java.util.Vector vs)
public static void revV(java.util.Vector v)
|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |


Courses
Products
Code Bytes
Love to Code!
Be a Full Stack Developer!
Encrypt data's with Easy Algorithms!
❮
❯
Basics Of Programming
DSA
Competative Codings
C-Programming
Java
Python
Html
JavaScript
SQL
Design your own Idea!
SteveJobs said,"Be a yardstick of quality. Some people aren't used to an environment where excellence is expected.."

CodeGeeks
Use to code with Pyhton And train your IoT's with it.
Trends
Update your app AI with Make a chatbot with AI.


IVote is an interface for contracts that implements a voting system. IVote contract should allow voters to chose M Winning Propositions among N Candidates Propositions (M smaller than N). Propositions are represented by numbers going from 1 to N. 0 proposition is the default proposition and represent the blank vote. Voting choices can be clear or hashed with a bytes32 salt in order to prevent voters that hasn't voted yet from being influenced by oders voter's voting choices. If votes are hashed, voters should validate their vote after the voting period is over, by submiting their clear voting choice with the corresponding salt. Serverals voting sessions with different parameters can be hold at the same time for various use case. Each new ballot should be provided with the address of a "Voter register" contract that contain a whitelist of account allowed to vote and with the function selector of a "Voter register" contract function that allow to check whether an account is allowed to vote or not.
Functions
Creates a new voting session
| Name | Type | Description |
|---|---|---|
| key | bytes32 | Id of the new voting session. It's up to caller to define one. |
| Voters_Register_Address | address | address of the contract that store account that are allowed to vote in this voting session |
| Check_Voter_Selector | bytes4 | Function Selector of a Voters_Register_Address contract's function in charge of checking whether an address belongs to accounts allowed to vote. The function should take an address in parameters and return a boolean. |
| Vote_Duration | uint256 | Duration of the stage in which members are allowed to vote |
| Vote_Validation_Duration | uint256 | Duration of the stage in which accounts who have voted have to validate their voting choice. |
| Propositions_Number | uint256 | Number N of candidats Propositions |
| Max_Winning_Propositions_Number | uint256 | Number M of places. |
Returns:
No parameters
End the validation stage if it is over. Votes are tailled and we should have access to winning propositions
| Name | Type | Description |
|---|---|---|
| key | bytes32 | Id of the voting session |
Returns:
No parameters
End the voting stage if it is over. If votes are hashed then we start the validation stage, else votes are tailled and we should have access to winning propositions
| Name | Type | Description |
|---|---|---|
| key | bytes32 | Id of the voting session |
Returns:
No parameters
Get the number of accounts that have voted in the Voting session
| Name | Type | Description |
|---|---|---|
| key | bytes32 | Id of the voting session |
Returns:
| Name | Type | Description |
|---|---|---|
| voter_num | uint256 |
Get a winning proposition by it's rank. Only callable if the ballot have been tailled (after End_Vote of End_Validation_Vote call).
| Name | Type | Description |
|---|---|---|
| key | bytes32 | Id of the voting session |
| Id | uint256 | Rank (index) of the proposition we want to get in the List of winning propositions. |
Returns:
| Name | Type | Description |
|---|---|---|
| Winning_Propositions | uint256 |
Get winning propositions list of a voting session. Only callable if the ballot have been tailled (after End_Vote of End_Validation_Vote call).
| Name | Type | Description |
|---|---|---|
| key | bytes32 | Id of the voting session |
Returns:
| Name | Type | Description |
|---|---|---|
| Winning_Propositions_List | uint256[] |
Check whether an account has Validated his vote or not.
| Name | Type | Description |
|---|---|---|
| key | bytes32 | Id of the voting session |
| voter_address | address | Address of the account |
Returns:
| Name | Type | Description |
|---|---|---|
| Validated | bool | |
| Choice | bytes32 |
Check whether an account has voted or not.
| Name | Type | Description |
|---|---|---|
| key | bytes32 | Id of the voting session |
| voter_address | address | Address of the account |
Returns:
| Name | Type | Description |
|---|---|---|
| hasvoted | bool |
Allows voter to validate their hashed voting choice by submitting it coupled with the salt bytes32 value that has been used to hash it. nly callable during Validation stage of a voting session.
| Name | Type | Description |
|---|---|---|
| key | bytes32 | Id of the voting session |
| Choices | uint256[] | Array of propositions Ids that correspond to voter choice |
| salt | bytes32 | bytes32 value that has been used to hash the "Choice" value. |
Returns:
No parameters
Allows a voter to vote clear in a voting session. Only callable during Voting stage of a voting session.
| Name | Type | Description |
|---|---|---|
| key | bytes32 | Id of the voting session |
| Choices | uint256[] | Array of propositions Ids that correspond to voter choice |
Returns:
No parameters
Allows a voter to vote in a voting session with an hashed voting choice in order to keep it secret until the vote validation stage. Only callable during Voting stage of a voting session.
| Name | Type | Description |
|---|---|---|
| key | bytes32 | Id of the voting session |
| Choice | bytes32 | Hash of the Array of propositions Ids that correspond to voter's choice with a salt bytes32 value created by the voter. |
Returns:
No parameters


Ally McCoist delivers emphatic Celtic and Rangers verdict as he hails Europa League heroics
The Ibrox legend has been thrilled watching the Premiership sides on the continent so far this term.
by Liam Bryce, https://www.dailyrecord.co.uk/authors/liam-bryce/Ally McCoist believes Celtic and Rangers have been "a breath of fresh air" in the Europa League this season.
The Glasgow giants are both in contention to qualify for the knock out stage after big performances against Lazio and Porto last time out.
Neil Lennon's side came from behind to stun the Italians at Parkhead and a repeat result at the Stadio Olimpico on Thursday could see Celtic through if results elsewhere go their way.
Rangers, meanwhile, are bidding to follow up an impressive draw in Portugal with three points against the Primeira Liga big guns.
And Ibrox icon McCoist insists those exploits have provided a timely boost for Scottish football, with each result influencing the all-important UEFA coefficient.
"Celtic and Rangers have been a breath of fresh air," McCoist told talkSPORT.
"Celtic got a great result against Lazio at home, now that'll be very, very tough for them (in Rome).
"Rangers, I thought, were excellent in Porto and they've got a tough one at home.
"I think both teams are flying the flag, which is good to see - because we need a little bit of a boost, don't we?"
Celtic currently sit top of Group E on seven points, and victory in Rome combined with anything but a Rennes win against Cluj would clinch qualification.
Rangers' task is taller, with all four teams in Group G within three points of each other.
Steven Gerrard's side sit second with four points, two behind leaders Young Boys and level with Porto.
Feyenoord currently prop up the group with just three points.


Pharms - Paroxetine, LSD, Alcohol, Cannabis, Mushrooms, MDMA, Methamphetamine, Cocaine, & Ketamine
I am a 20 year old male who has been taking paroxetine four months now at a dose of 20 mg/day. I have been using cannabis and speed recreationally for over five years now, but my usage of other drugs has only occurred over the past year or so. The account below represents my experience of paroxetine in combination with the following drugs:
Speed - No real change in effects apart from a noticeable increase in sweating. Comedown seems much less harsh.
Cannabis - extreme increase in effects, once to the point of confusion and fear. Basically like being incredibly stoned off very little weed - the effects of a heavy night's smoke from less than half a joint.
 As has been widely reported I found paroxetine reduces the effect of ecstasy to nothing - yes nothing! No jaw clenching, no wide pupils, no rushes, no euphoria, no increase in energy, no love. The only effects I have noticed are nausea (actually less than usual with ecstasy alone) and a long-lasting prickly tingling feeling in the skin. Also in my experience it appears that no matter how many pills are taken it is impossible to feel even a semblance of the usual ecstasy experience - I have tried double-dropping, triple-dropping and only a month ago I double-dropped followed by two more pills within the space of an hour and a half - still nothing. This was the fifth time I had combined paroxetine with ecstasy, I had kind of hoped that before I'd just been unlucky with the pills but this time I was with a group of friends and it was quite obvious that everyone was buzzing their faces off, even those who had only taken one pill.
LSD - Contrary to other reports I have found that the effects of acid are not reduced as such, but that they become more manageable. On previous occasions I have occasionally freaked out on acid and required talking down, yet when combined with paroxetine I find I welcome the trip with open arms. Visual distortions, changes in depth perception etc. are all still present in full, yet I have found that these seem much more enchanting/exciting than fearful or confusing as they occasionally did before I was prescribed paroxetine. Generally I have had more mystical and exciting experiences on acid when taken with paroxetine than when not. Although this may simply be due to the fact that paroxetine seems to have diminished my sense of worry, paranoia etc. and increased my overall confidence.
Cocaine - I have never noticed any change in effects when using coke with paroxetine, apart from an unpleasant nausea which was not previously present with coke alone.
Mushrooms - Absolutely no change in effects whatsoever.
Ketamine - I am not a big fan of ket, and have only taken it three times - twice before being prescribed paroxetine and once after, The effects seem a little reduced, the physical effects more greatly so - I was still able to walk around and communicate as normal even after six generous (!) lines. On the two previous occasions this became difficult after the third line and impossible after the fourth.
Alcohol - Out of all the aforementioned drugs, the interaction between paroxetine and alcohol is the one I have definitely found the worst! I am never ever violent and usually keep it to myself if I find anything/anyone irritating or offensive.  And then I wake up the next morning and it all seems like a blur - paroxetine has defintely reduced my alcohol intake and I now only occasionally drink small amounts when socialising with close friends.
These are solely my experiences with paroxetine, I have never been prescribed another antidepressant drug. And, through contact with other antidepressant users, I can almost certainly say that different SSRIs have vastly different interactions with psychoactives - for example I have a friend who has been on prozac for over four years - he reports no change whatsoever to the effects of ecstasy and yet, though the effects are still noticeable, experiences greatly reduced visual distortions on acid.
Happy Tripping!!!
Experience Reports are the writings and opinions of the individual authors who submit them.
Some of the activities described are dangerous and/or illegal and none are recommended by Erowid.


Zii Jia withdraws from Hong Kong Open
KUALA LUMPUR, Nov 10 — National men’s singles, Lee Zii Jia was forced to withdraw from the upcoming Hong Kong Open starting on Nov 12, due to severe food poisoning.
The 21-year-old player found the illness debilitating and was unable to train.
National men’s singles coach Hendrawan said Zii Jia would undergo further medical check-ups and continue his recovery in Malaysia.
“Zii Jia was feeling lethargic and had difficulties to train due to the food poisoning.
“We’ve decided to pull him out of the Hong Kong Open and he will have a medical check-up in Malaysia,” he said in a statement issued by Badminton Association of Malaysia (BAM) today.
Zii Jia who is currently ranked ninth in world tour retired midway through his second round match against world number one, Kento Momota at the Fuzhou China Open last Thursday. — Bernama


Takes the values of each character and adds a certain key (modulo 26). A = 0 Encrypt = [Character code + step] mod 26 Decrypt = [Character code - step] mod 26
Encrypt = [Character code + step] mod 26
Decrypt = [Character code - step] mod 26


Safer Space
Use the sensitivity dropdown to tell us how much to
censor around potentially offensive phrases!
Use the sensitivity dropdown to tell us how much to
censor around potentially offensive phrases!


Default settings for the slider.
duration: time in millis. Duration for the transformation.
autoPlay: activates the autoplay function.
autoPlayDirection: PREV or NEXT.
autoPlayInterval: interval for autoplay.
rewind: activates the rewind function.
rewindDuration: duration for the rewind slideback.
loop: activate the infinite loop.
navigation: activates the dot navigation.
autoSwitchOff: disables the slider if all items are visible.
swipe: activates the gesture control.
lazyLoading: activates image lazy loading.
autoHeight: activates auto high.
easeFunction: TimingFunction
classContainer: container div
classFrame: frame div
classList: item unsorted list
classPrevButton: prev button
classNextButton: bext button
classDeactivatedButton: disabled button
classActiveItem: active item
classNavigationFrame: navigation div
classNavigationItem: navigation unsorted list
classActiveNavigationItem: dots


Welcome to NPAT’s documentation!¶
NPAT (nuclear physics analysis tools) is a python toolkit to aid in the analysis of experimental nuclear data.
The primary application for NPAT is activation analysis, with specific utilities developed for stacked-target, charged-particle activation analysis. However, the convenient python interface to nuclear decay data and a range of cross section libraries makes NPAT more generally useful in the nuclear sciences.
Features¶
NPAT features the following classes to aid in data analysis:
- Spectrum - Peak fitting for HPGe detector data.
- Calibration - Energy & efficiency calibration tool (for HPGe detectors).
- Ziegler - Stacked-target energy loss characterization.
- DecayChain - General purpose Bateman equation solver.
- Isotope - Isotopic and decay data.
- Reaction - Cross sections from multiple libraries.
- Library - Tool for searching and retrieving cross sections from multiple libraries.


class: center, middle, inverse, title-slide # ETC3250: Regularization ## Semester 1, 2019 ###
Professor Di Cook
Econometrics and Business Statistics
Monash University ### Week 9 (a) --- class: split-30 layout: false .column[.pad10px[ ## Outline - .orange[Shrinkage methods] ]] .column[.top50px[
 .orange[Shrinkage methods] fit a model containing all `\(p\)` predictors using a technique that constrains or regularizes the coefficient estimates, or equivalently, that .orange[shrinks some of the coefficient estimates towards zero].
 .boxshadow[There are two main methods: .orange[ridge] regression and .orange[lasso].] ]] --- class: split-30 layout: false .column[.pad10px[ ## Outline - Shrinkage Methods - Ridge regression ]] .column[.top50px[ `\begin{align*} & \mbox{RSS} = \sum_{i = 1}^n \left(y_i - \beta_0 - \sum_{j = 1}^p \beta_j x_{ij} \right)^2 \end{align*}` Least squares: `\begin{align*} & \underset{{\beta}}{\text{minimize}} \mbox{ RSS} \end{align*}` .orange[Ridge] regression: `\begin{align*} & \underset{{\beta}}{\text{minimize}} \mbox{ RSS} \color{orange}{+ \lambda \sum_{j=1}^p \beta_j^2} \end{align*}` where `\(\lambda \geq 0\)` is a tuning parameter. ]] --- class: split-30 layout: false .column[.pad10px[ ## Outline - Shrinkage Methods - Ridge regression ]] .column[.top50px[ `$$\lambda \sum_{j=1}^p \beta_j^2$$` is called a .orange[shrinkage penalty]. It is small when `\(\beta_1, ..., \beta_p\)` are close to 0. `\(\lambda\)` serves as a .orange[tuning parameter], controlling the relative impact of these two terms on the regression coefficient estimates. When it is 0, the penalty term has no effect on the fit. Ridge regression will produce a .orange[different set of coefficients] for each `\(\lambda\)`, call them `\(\hat{\beta}_{\lambda}^R\)`. Tuning `\(\lambda\)`, typically by cross-validation, is critical component of fitting the model. ]] --- class: split-60 layout: false .column[.pad10px[ Standardized ridge regression coefficients for the Credit data set.    .font_tiny[(Chapter6/6.4.pdf)] ]] .column[.top50px[ - `\(p=10\)` - Left side of plot corresponds to least squares. - When `\(\lambda\)` is extremely large, then all of the ridge coefficient estimates are basically zero, which is the null model. - 4 of 10 variables have larger coefficients, and one, Rating, initially increases with `\(\lambda\)`. - Right-side plot, `\(x\)`-axis indicates amount the coefficients shrink to 0, value of 1 indicates LS. ]] --- class: split-50 layout: false .column[.pad10px[ The scale of variables can affect ridge regression performance.
.orange[It is important to standardise the scale of predictors prior to ridge regression.]
`$$\tilde{x}_{ij} = \frac{x_{ij}}{\sigma_{x_{j}}}$$` ]] .column[.pad10px[ Simulation scenario! Ridge regression improves on least squares, for large number of variables, in the bias-variance tradeoff. It .orange[sacrifices some bias] for the benefit of .orange[decreased variance].    .black[bias] .green[variance] .purple[test error] .font_tiny[(Chapter6/6.5.pdf)] ]] --- class: split-30 layout: false .column[.pad10px[ ## Outline - Shrinkage Methods - [Ridge regression](#3) - Lasso ]] .column[.top50px[ Ridge regression: `\begin{align*} & \underset{{\beta}}{\text{minimize}} \mbox{ RSS} + \lambda \sum_{j=1}^p \beta_j^2 \end{align*}` .orange[Lasso]: `\begin{align*} & \underset{{\beta}}{\text{minimize}} \mbox{ RSS} + \lambda \sum_{j=1}^p \color{orange}{|\beta_j|} \end{align*}` and same `\(\lambda \geq 0\)` is a tuning parameter. ]] --- class: split-60 layout: false .column[.pad10px[ Standardized lasso coefficients for the Credit data set.    .font_tiny[(Chapter6/6.6.pdf)] ]] .column[.top50px[ - `\(p=10\)` - Has the effect of forcing some variables exactly to 0. - Cleaner solution than ridge regression. ]] --- Simulation scenario! Bias-variance tradeoff with lasso, and comparison against ridge regression.    .black[bias] .green[variance] .purple[test error] .font_tiny[(Chapter6/6.5.pdf)] --- class: split-50 layout: false .column[.pad10px[ .orange[Bayesian] interpretation: Ridge regression is the posterior mode for `\(\beta\)` under a Gaussian prior (left); The lasso is the posterior mode for `\(\beta\)` under a double-exponential prior (right).    .font_tiny[(Chapter6/6.11.pdf)] ]] .column[.pad10px[ .orange[Cross-validation] on the Credit example, yields a suggestion to use `\(\lambda=0.5\)` for ridge regression model.    .font_tiny[(Chapter6/6.12.pdf)] ]] --- class: split-30 layout: false .column[.pad10px[ ## Outline - .orange[Shrinkage methods] - [Ridge regression](#3) - [Lasso](#7) - Penalised LDA ]] .column[.top50px[ Recall: LDA involves the eigen decomposition of `\(\color{orange}{\Sigma^{-1}\Sigma_B}\)`, where `$$\Sigma_B = \frac{1}{K}\sum_{i=1}^{K} (\mu_i-\mu)(\mu_i-\mu)'$$` `$$\Sigma = \frac{1}{n} \sum_{i=1}^{n} (x_i-\mu_i)(x_i-\mu_i)'$$` The eigen-decomposition is an analytical solution to a sequential optimisation problem: `\begin{align*} & \underset{{\beta_k}}{\text{maximize}} \beta_k^T\hat{\Sigma}_B \beta_k \\ & \mbox{ subject to } \beta_k^T\hat{\Sigma} \beta_k \leq 1, \beta_k^T\hat{\Sigma}\beta_j = 0 \mbox{ } \forall i<k \end{align*}` ]] --- class: split-30 layout: false .column[.pad10px[ ## Outline - .orange[Shrinkage methods] - [Ridge regression](#3) - [Lasso](#7) - Penalised LDA ]] .column[.top50px[ The problem is inverting `\(\color{orange}{\Sigma^{-1}}\)`, fix it by `\begin{align*} & \underset{{\beta_k}}{\text{maximize}} \left(\beta_k^T\hat{\Sigma}_B \beta_k + \lambda_k \sum_{j=1}^p |\hat{\sigma}_j\beta_{kj}|\right)\\ & \mbox{ subject to } \beta_k^T\tilde{\Sigma} \beta_k \leq 1 \end{align*}` where `\(\hat{\sigma}_j\)` is the within-class standard deviation for variable `\(j\)`. This is .orange[penalised LDA], and see [reference](https://faculty.washington.edu/dwitten/Papers/JRSSBPenLDA.pdf), and the [R package](https://cran.r-project.org/web/packages/penalizedLDA/index.html). ]] --- class: split-30 layout: false .column[.pad10px[ ## Outline - .orange[Shrinkage methods] - [Ridge regression](#3) - [Lasso](#7) - [Penalised LDA](#11) - PDA Index ]] .column[.top50px[ Penalised LDA projection pursuit index. Available in the `tourr` package. `\begin{align*} I_{PDA}(A,\lambda) = 1-\frac{\Big|A'\big\{(1-\lambda)\hat{\Sigma}+n\lambda I_p\big\}A\Big|} {\Big|A'\big\{(1-\lambda)(\hat{\Sigma}_B +\hat{\Sigma})+n\lambda I_p\big\} A\Big|} \end{align*}` Optimising this function over `\(p\times d\)` projection matrix `\(A\)`. ]] --- class: split-30 layout: false .column[.pad10px[ ## Outline - [Shrinkage methods](#2) - Dimension reduction - Principal component regression ]] .column[.top50px[ The .orange[principal components regression (PCR)] approach involves constructing the first `\(M\)` principal components, `\(Z_1, ..., Z_M\)`, and then using these components as the predictors in a linear regression model, that is fit using least squares. ]] --- PCR, ridge regression, and the lasso compared on simulated data. PCR does well when the response is related to few PCs.    .black[bias] .green[variance] .purple[test error] .font_tiny[(Chapter6/6.19.pdf)] --- class: split-30 layout: false .column[.pad10px[ ## Outline - [Shrinkage methods](#2) - Dimension reduction - Principal component regression - Partial least squares ]] .column[.top50px[ .orange[Partial least squares (PLS)], a supervised alternative to PCR.    Two predictors are shown: .green[Solid line is PLS], dashed line is PCR. ]] --- class: split-30 layout: false .column[.pad10px[ ## Outline - [Shrinkage methods](#2) - Dimension reduction - Principal component regression - Partial least squares ]] .column[.top50px[ 1. .orange[Standardise] all variables 2. Find `\(Z_1=\phi_{1j}X_j\)` by setting `\(\phi_{1j}\)` to be the coefficient from a .orange[simple linear regression] model `\(Y\)` ~ `\(X_j\)`. 3. To find `\(Z_2\)`, first regress each variable on `\(Z_1\)` and use the .orange[residuals], call these `\(X^r_j\)`. Then find `\(Z_2 = \phi_{2j}X^r_j\)` by setting `\(\phi_{2j}\)` to be the coefficient from a simple linear regression model `\(Y\)` ~ `\(X^r_j\)`. 4. Repeat steps 2-3 until we have `\(Z_1, ..., Z_M\)`. Final model fitted for `\(Y\)` using `\(Z_1, ..., Z_M\)`. Performance is no better than ridge regression or PCR. Can reduce bias, has potential to increase variance. .orange[PLS is similar to partial regression], where new variables are first regressed on predictors that are already in the model, and it is the residuals that are used. ]] --- layout: false # 👩💻 Made by a human with a computer ### Slides at [https://monba.dicook.org](https://monba.dicook.org). ### Code and data at [https://github.com/dicook/Business_Analytics](https://github.com/dicook/Business_Analytics).
 ### Created using [R Markdown](https://rmarkdown.rstudio.com) with flair by [**xaringan**](https://github.com/yihui/xaringan), and [**kunoichi** (female ninja) style](https://github.com/emitanaka/ninja-theme).

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.


Toll blending, also known as contract manufacturing or contract blending is a service whereby the production of (complex) chemical products is out sourced to a third party company.
DBM Chemicals Limited offers an independent toll blending/manufacturing service with complete confidentiality assured, protected by secrecy/non-disclosure agreements if required. Blending facilities include modern stainless steel mixing vessels with a capacity of 1,000 to 20,000 litres and all are equipped with heating, circulation, agitation, filtration, extraction and load cells.
We understand that every product and raw material is different and in some cases heat is required through out the toll blending process.
Read more
Through years of experience we have come to the understanding that when toll blending for our customers a large amount of storage is required for both raw materials and finished products.
Read more
To ensure all of our customers products leave site at the highest of standards we offer a bespoke packaging service. Read more


?6
7
8
9
10
copyright
reserved
The
New
York
Botanical
Garden
name
Cewte-Wflk.
CXiucxTÈ
ccu,
L(V^cWotoVu\e
*"©¥
P<\a\(1ol
Cf
Ç,.
I
AP*-
hii
,*u**JLCo
,,
NEW
YORK
BOTANICAL
GARDEN
0
501152
Collector
Bv'¡lwV\
Date
XukV^e
\S~I
(o
DEPARTMENT
OF
BOTANY,
HUNTER
COLLEGE
OF
THE
CITY
OF
NEW
YORK
01501152
Legend -
Level of confidence that token is an accurately-transcribed word
extremely low
very low
low
undetermined
medium
high
very high


How to enable Last.fm scrobbling & visualise your Last.fm data with My Music Stats
Create a Last.fm account (Skip if you already have a Last.fm account)
Go to Last.fm & fill the details to create your account.
Download Simple Last.fm Scrobbler
Once it is installed, we need to configure it.
Follow below steps to configure Simple Last.fm Scrobbler
Simple Last.fm Scrobbler Configuration
Open Simple Last.fm Scrobbler.
Tap User credentials.
Enter your Last.fm account details.
Configure Playback threshold.
For this, go back to the app's homepage & tap the Options.
Now tap the Scrobble point & adjust the slider accordingly. For most users, 50% is sufficient.
Configure Your Music Player
Simple Last.fm Scrobbler supports all the major music player apps. You can check the list
on the Play Store page or their GitHub repository.

Check the Scrobble Music box. If it is already selected, keep it checked.
Configure Rocket Player
Go to Rocket Player's Settings & then tap Sound.
Now tap the Simple Last.fm radio button. If it is already selected, keep it checked.
Your configuration is now complete & you can start listening to your songs from your
favorite Android music players & analyse your music data with My Music Stats :-)
If you have any questions around this or my explanation is not clear, drop a comment below.
I will be more than happy to assist!


Business with usFor right quality products
PHONE: + 91-9739849396,9986069581 MAIL<EMAIL_ADDRESS>For More Info Visit: info@abtools.co


Elixir v1.3.4 String
A String in Elixir is a UTF-8 encoded binary.
Codepoints and graphemes
The functions in this module act according to the Unicode Standard, version 6.3.0.
As per the standard, a codepoint is a single Unicode Character, which may be represented by one or more bytes.
For example, the codepoint “é” is two bytes:
iex> byte_size("é")
2
However, this module returns the proper length:
iex> String.length("é")
1
Furthermore, this module also presents the concept of graphemes. A single grapheme can consist of multiple codepoints that may be perceived as a single character by readers. For example, the “é” grapheme can be represented either as a single “e with acute” codepoint (like above), or as the letter “e” followed by a “combining acute accent” (two codepoints):
iex> string = "\u0065\u0301"
iex> byte_size(string)
3
iex> String.length(string)
1
iex> String.codepoints(string)
["e", "́"]
iex> String.graphemes(string)
["é"]
Although the example above is made of two characters, it is perceived by users as one.
Graphemes can also be two characters that are interpreted as one by some languages. For example, some languages may consider “ch” as a grapheme. However, since this information depends on the locale, it is not taken into account by this module.
In general, the functions in this module rely on the Unicode Standard, but do not contain any of the locale specific behaviour.
More information about graphemes can be found in the Unicode Standard Annex #29. The current Elixir version implements Extended Grapheme Cluster algorithm.
String and binary operations
To act according to the Unicode Standard, many functions in this module run in linear time, as they need to traverse the whole string considering the proper Unicode codepoints.
For example, String.length/1
will take longer as
the input grows. On the other hand, Kernel.byte_size/1
always runs
in constant time (i.e. regardless of the input size).
This means often there are performance costs in using the functions in this module, compared to the more low-level operations that work directly with binaries:
Kernel.binary_part/3
- retrieves part of the binaryKernel.bit_size/1
andKernel.byte_size/1
- size related functionsKernel.is_bitstring/1
andKernel.is_binary/1
- type checking function- Plus a number of functions for working with binaries (bytes)
in the
:binary
module
There are many situations where using the String
module can
be avoided in favor of binary functions or pattern matching.
For example, imagine you have a string prefix
and you want to
remove this prefix from another string named full
.
One may be tempted to write:
iex> take_prefix = fn full, prefix ->
...> base = String.length(prefix)
...> String.slice(full, base, String.length(full) - base)
...> end
iex> take_prefix.("Mr. John", "Mr. ")
"John"
Although the function above works, it performs poorly. To
calculate the length of the string, we need to traverse it
fully, so we traverse both prefix
and full
strings, then
slice the full
one, traversing it again.
A first attempt at improving it could be with ranges:
iex> take_prefix = fn full, prefix ->
...> base = String.length(prefix)
...> String.slice(full, base..-1)
...> end
iex> take_prefix.("Mr. John", "Mr. ")
"John"
While this is much better (we don’t traverse full
twice),
it could still be improved. In this case, since we want to
extract a substring from a string, we can use byte_size/1
and binary_part/3
as there is no chance we will slice in
the middle of a codepoint made of more than one byte:
iex> take_prefix = fn full, prefix ->
...> base = byte_size(prefix)
...> binary_part(full, base, byte_size(full) - base)
...> end
iex> take_prefix.("Mr. John", "Mr. ")
"John"
Or simply use pattern matching:
iex> take_prefix = fn full, prefix ->
...> base = byte_size(prefix)
...> <<_::binary-size(base), rest::binary>> = full
...> rest
...> end
iex> take_prefix.("Mr. John", "Mr. ")
"John"
On the other hand, if you want to dynamically slice a string
based on an integer value, then using String.slice/3
is the
best option as it guarantees we won’t incorrectly split a valid
codepoint into multiple bytes.
Integer codepoints
Although codepoints could be represented as integers, this module represents all codepoints as strings. For example:
iex> String.codepoints("olá")
["o", "l", "á"]
There are a couple of ways to retrieve a character integer
codepoint. One may use the ?
construct:
iex> ?o
111
iex> ?á
225
Or also via pattern matching:
iex> <<aacute::utf8>> = "á"
iex> aacute
225
As we have seen above, codepoints can be inserted into a string by their hexadecimal code:
"ol\u0061\u0301" #=>
"olá"
Self-synchronization
The UTF-8 encoding is self-synchronizing. This means that if malformed data (i.e., data that is not possible according to the definition of the encoding) is encountered, only one codepoint needs to be rejected.
This module relies on this behaviour to ignore such invalid
characters. For example, length/1
will return
a correct result even if an invalid codepoint is fed into it.
In other words, this module expects invalid data to be detected when retrieving data from the external source. For example, a driver that reads strings from a database will be responsible to check the validity of the encoding.
Patterns
Many functions in this module work with patterns. For example, String.split/2 can split a string into multiple patterns given a pattern. This pattern can be a string, a list of strings or a compiled pattern:
iex> String.split("foo bar", " ")
["foo", "bar"]
iex> String.split("foo bar!", [" ", "!"])
["foo", "bar", ""]
iex> pattern = :binary.compile_pattern([" ", "!"])
iex> String.split("foo bar!", pattern)
["foo", "bar", ""]
The compiled pattern is useful when the same match will be done over and over again. Note though the compiled pattern cannot be stored in a module attribute as the pattern is generated at runtime and does not survive compile term.
Summary
Functions
Returns the grapheme at the position
of the given utf8 string
.
If position
is greater than string
length, then it returns nil
Converts the first character in the given string to uppercase and the remainder to lowercase
Splits the string into chunks of characters that share a common trait
Returns all codepoints in the string
Checks if string
contains any of the given contents
Converts all characters in the given string to lowercase
Returns a string subject
duplicated n
times
Returns true
if string
ends with any of the suffixes given
Returns true
if string1
is canonically equivalent to ‘string2’
Returns the first grapheme from a utf8 string,
nil
if the string is empty
Returns Unicode graphemes in the string as per Extended Grapheme Cluster algorithm
Returns a float value between 0 (equates to no similarity) and 1 (is an exact match)
representing Jaro
distance between string1
and string2
Returns the last grapheme from a utf8 string,
nil
if the string is empty
Returns the number of Unicode graphemes in a utf8 string
Checks if string
matches the given regular expression
Returns a keyword list that represents an edit script
Returns the next codepoint in a string
Returns the next grapheme in a string
Returns the size of the next grapheme
Converts all characters in string
to Unicode normalization
form identified by form
Returns a new string padded with a leading filler
which is made of elements from the padding
Returns a new string padded with a trailing filler
which is made of elements from the padding
Checks if a string contains only printable characters
Returns a new string created by replacing occurrences of pattern
in
subject
with replacement
Replaces all leading occurrences of match
by replacement
of match
in string
Replaces prefix in string
by replacement
if it matches match
Replaces suffix in string
by replacement
if it matches match
Replaces all trailing occurrences of match
by replacement
in string
Reverses the graphemes in given string
Returns a substring from the offset given by the start of the range to the offset given by the end of the range
Returns a substring starting at the offset start
, and of
length len
Divides a string into substrings at each Unicode whitespace occurrence with leading and trailing whitespace ignored. Groups of whitespace are treated as a single occurrence. Divisions do not occur on non-breaking whitespace
Divides a string into substrings based on a pattern
Splits a string into two at the specified offset. When the offset given is negative, location is counted from the end of the string
Returns an enumerable that splits a string on demand
Returns true
if string
starts with any of the prefixes given
Converts a string to an atom
Converts a string into a charlist
Converts a string to an existing atom
Returns a float whose text representation is string
Returns an integer whose text representation is string
Returns an integer whose text representation is string
in base base
Returns a string where all leading and trailing Unicode whitespaces have been removed
Returns a string where all leading and trailing to_trim
s have been
removed
Returns a string where all leading Unicode whitespaces have been removed
Returns a string where all leading to_trim
s have been removed
Returns a string where all trailing Unicode whitespaces has been removed
Returns a string where all trailing to_trim
s have been removed
Converts all characters in the given string to uppercase
Checks whether string
contains only valid characters
Types
Functions
Returns the grapheme at the position
of the given utf8 string
.
If position
is greater than string
length, then it returns nil
.
Examples
iex> String.at("elixir", 0)
"e"
iex> String.at("elixir", 1)
"l"
iex> String.at("elixir", 10)
nil
iex> String.at("elixir", -1)
"r"
iex> String.at("elixir", -10)
nil
Converts the first character in the given string to uppercase and the remainder to lowercase.
This relies on the titlecase information provided by the Unicode Standard. Note this function makes no attempt to capitalize all words in the string (usually known as titlecase).
Examples
iex> String.capitalize("abcd")
"Abcd"
iex> String.capitalize("ﬁn")
"Fin"
iex> String.capitalize("olá")
"Olá"
Splits the string into chunks of characters that share a common trait.
The trait can be one of two options:
:valid
- the string is split into chunks of valid and invalid character sequences:printable
- the string is split into chunks of printable and non-printable character sequences
Returns a list of binaries each of which contains only one kind of characters.
If the given string is empty, an empty list is returned.
Examples
iex> String.chunk(<<?a, ?b, ?c, 0>>, :valid)
["abc\0"]
iex> String.chunk(<<?a, ?b, ?c, 0, 0x0FFFF::utf8>>, :valid)
["abc\0", <<0x0FFFF::utf8>>]
iex> String.chunk(<<?a, ?b, ?c, 0, 0x0FFFF::utf8>>, :printable)
["abc", <<0, 0x0FFFF::utf8>>]
Returns all codepoints in the string.
For details about codepoints and graphemes, see the String
module documentation.
Examples
iex> String.codepoints("olá")
["o", "l", "á"]
iex> String.codepoints("оптими зации")
["о", "п", "т", "и", "м", "и", " ", "з", "а", "ц", "и", "и"]
iex> String.codepoints("ἅἪῼ")
["ἅ", "Ἢ", "ῼ"]
iex> String.codepoints("é")
["é"]
iex> String.codepoints("é")
["e", "́"]
Checks if string
contains any of the given contents
.
contents
can be either a single string or a list of strings.
Examples
iex> String.contains? "elixir of life", "of"
true
iex> String.contains? "elixir of life", ["life", "death"]
true
iex> String.contains? "elixir of life", ["death", "mercury"]
false
An empty string will always match:
iex> String.contains? "elixir of life", ""
true
iex> String.contains? "elixir of life", ["", "other"]
true
The argument can also be a precompiled pattern:
iex> pattern = :binary.compile_pattern(["life", "death"])
iex> String.contains? "elixir of life", pattern
true
Converts all characters in the given string to lowercase.
Examples
iex> String.downcase("ABCD")
"abcd"
iex> String.downcase("AB 123 XPTO")
"ab 123 xpto"
iex> String.downcase("OLÁ")
"olá"
Returns a string subject
duplicated n
times.
Examples
iex> String.duplicate("abc", 0)
""
iex> String.duplicate("abc", 1)
"abc"
iex> String.duplicate("abc", 2)
"abcabc"
Returns true
if string
ends with any of the suffixes given.
suffixes
can be either a single suffix or a list of suffixes.
Examples
iex> String.ends_with? "language", "age"
true
iex> String.ends_with? "language", ["youth", "age"]
true
iex> String.ends_with? "language", ["youth", "elixir"]
false
An empty string will always match:
iex> String.ends_with? "language", ""
true
iex> String.ends_with? "language", ["", "other"]
true
Returns true
if string1
is canonically equivalent to ‘string2’.
It performs Normalization Form Canonical Decomposition (NFD) on the strings before comparing them. This function is equivalent to:
String.normalize(string1, :nfd) == String.normalize(string2, :nfd)
Therefore, if you plan to compare multiple strings, multiple times in a row, you may normalize them upfront and compare them directly to avoid multiple normalization passes.
Examples
iex> String.equivalent?("abc", "abc")
true
iex> String.equivalent?("man\u0303ana", "mañana")
true
iex> String.equivalent?("abc", "ABC")
false
iex> String.equivalent?("nø", "nó")
false
Returns the first grapheme from a utf8 string,
nil
if the string is empty.
Examples
iex> String.first("elixir")
"e"
iex> String.first("եոգլի")
"ե"
Returns Unicode graphemes in the string as per Extended Grapheme Cluster algorithm.
The algorithm is outlined in the Unicode Standard Annex #29, Unicode Text Segmentation.
For details about codepoints and graphemes, see the String
module documentation.
Examples
iex> String.graphemes("Ńaïve")
["Ń", "a", "ï", "v", "e"]
iex> String.graphemes("é")
["é"]
iex> String.graphemes("é")
["é"]
Returns a float value between 0 (equates to no similarity) and 1 (is an exact match)
representing Jaro
distance between string1
and string2
.
The Jaro distance metric is designed and best suited for short strings such as person names.
Examples
iex> String.jaro_distance("dwayne", "duane")
0.8222222222222223
iex> String.jaro_distance("even", "odd")
0.0
Returns the last grapheme from a utf8 string,
nil
if the string is empty.
Examples
iex> String.last("elixir")
"r"
iex> String.last("եոգլի")
"ի"
Returns the number of Unicode graphemes in a utf8 string.
Examples
iex> String.length("elixir")
6
iex> String.length("եոգլի")
5
Checks if string
matches the given regular expression.
Examples
iex> String.match?("foo", ~r/foo/)
true
iex> String.match?("bar", ~r/foo/)
false
Returns a keyword list that represents an edit script.
The algorithm is outlined in the “An O(ND) Difference Algorithm and Its Variations” paper by E. Myers.
Examples
iex> string1 = "fox hops over the dog"
iex> string2 = "fox jumps over the lazy cat"
iex> String.myers_difference(string1, string2)
[eq: "fox ", del: "ho", ins: "jum", eq: "ps over the ", del: "dog", ins: "lazy cat"]
Returns the next codepoint in a string.
The result is a tuple with the codepoint and the
remainder of the string or nil
in case
the string reached its end.
As with other functions in the String module, this function does not check for the validity of the codepoint. That said, if an invalid codepoint is found, it will be returned by this function.
Examples
iex> String.next_codepoint("olá")
{"o", "lá"}
Returns the next grapheme in a string.
The result is a tuple with the grapheme and the
remainder of the string or nil
in case
the String reached its end.
Examples
iex> String.next_grapheme("olá")
{"o", "lá"}
Returns the size of the next grapheme.
The result is a tuple with the next grapheme size and
the remainder of the string or nil
in case the string
reached its end.
Examples
iex> String.next_grapheme_size("olá")
{1, "lá"}
Converts all characters in string
to Unicode normalization
form identified by form
.
Forms
The supported forms are:
:nfd
- Normalization Form Canonical Decomposition. Characters are decomposed by canonical equivalence, and multiple combining characters are arranged in a specific order.:nfc
- Normalization Form Canonical Composition. Characters are decomposed and then recomposed by canonical equivalence.
Examples
iex> String.normalize("yêṩ", :nfd)
"yêṩ"
iex> String.normalize("leña", :nfc)
"leña"
Returns a new string padded with a leading filler
which is made of elements from the padding
.
Passing a list of strings as padding
will take one element of the list
for every missing entry. If the list is shorter than the number of inserts,
the filling will start again from the beginning of the list.
Passing a string padding
is equivalent to passing the list of graphemes in it.
If no padding
is given, it defaults to whitespace.
When count
is less than or equal to the length of string
,
given string
is returned.
Raises ArgumentError
if the given padding
contains non-string element.
Examples
iex> String.pad_leading("abc", 5)
" abc"
iex> String.pad_leading("abc", 4, "12")
"1abc"
iex> String.pad_leading("abc", 6, "12")
"121abc"
iex> String.pad_leading("abc", 5, ["1", "23"])
"123abc"
Returns a new string padded with a trailing filler
which is made of elements from the padding
.
Passing a list of strings as padding
will take one element of the list
for every missing entry. If the list is shorter than the number of inserts,
the filling will start again from the beginning of the list.
Passing a string padding
is equivalent to passing the list of graphemes in it.
If no padding
is given, it defaults to whitespace.
When count
is less than or equal to the length of string
,
given string
is returned.
Raises ArgumentError
if the given padding
contains non-string element.
Examples
iex> String.pad_trailing("abc", 5)
"abc "
iex> String.pad_trailing("abc", 4, "12")
"abc1"
iex> String.pad_trailing("abc", 6, "12")
"abc121"
iex> String.pad_trailing("abc", 5, ["1", "23"])
"abc123"
Returns a new string created by replacing occurrences of pattern
in
subject
with replacement
.
By default, it replaces all occurrences, unless the global
option is
set to false
, where it will only replace the first one
The pattern
may be a string or a regular expression.
Examples
iex> String.replace("a,b,c", ",", "-")
"a-b-c"
iex> String.replace("a,b,c", ",", "-", global: false)
"a-b,c"
When the pattern is a regular expression, one can give \N
or
\g{N}
in the replacement
string to access a specific capture in the
regular expression:
iex> String.replace("a,b,c", ~r/,(.)/, ",\\1\\g{1}")
"a,bb,cc"
Notice we had to escape the escape character \
. By giving \0
,
one can inject the whole matched pattern in the replacement string.
When the pattern is a string, a developer can use the replaced part inside
the replacement
by using the :insert_replace
option and specifying the
position(s) inside the replacement
where the string pattern will be
inserted:
iex> String.replace(“a,b,c”, “b”, “[]“, insert_replaced: 1)
“a,[b],c”
iex> String.replace(“a,b,c”, “,”, “[]“, insert_replaced: 2)
“a[],b[],c”
iex> String.replace(“a,b,c”, “,”, “[]“, insert_replaced: [1, 1])
“a[,,]b[,,]c”
If any position given in the :insert_replace
option is larger than the
replacement string, or is negative, an ArgumentError
is raised.
Replaces all leading occurrences of match
by replacement
of match
in string
.
Returns the string untouched if there are no occurrences.
Examples
iex> String.replace_leading("hello world", "hello ", "")
"world"
iex> String.replace_leading("hello hello world", "hello ", "")
"world"
iex> String.replace_leading("hello world", "hello ", "ola ")
"ola world"
iex> String.replace_leading("hello hello world", "hello ", "ola ")
"ola ola world"
Replaces prefix in string
by replacement
if it matches match
.
Returns the string untouched if there is no match.
Examples
iex> String.replace_prefix("world", "hello ", "")
"world"
iex> String.replace_prefix("hello world", "hello ", "")
"world"
iex> String.replace_prefix("hello hello world", "hello ", "")
"hello world"
iex> String.replace_prefix("world", "hello ", "ola ")
"world"
iex> String.replace_prefix("hello world", "hello ", "ola ")
"ola world"
iex> String.replace_prefix("hello hello world", "hello ", "ola ")
"ola hello world"
Replaces suffix in string
by replacement
if it matches match
.
Returns the string untouched if there is no match.
Examples
iex> String.replace_suffix("hello", " world", "")
"hello"
iex> String.replace_suffix("hello world", " world", "")
"hello"
iex> String.replace_suffix("hello world world", " world", "")
"hello world"
iex> String.replace_suffix("hello", " world", " mundo")
"hello"
iex> String.replace_suffix("hello world", " world", " mundo")
"hello mundo"
iex> String.replace_suffix("hello world world", " world", " mundo")
"hello world mundo"
Replaces all trailing occurrences of match
by replacement
in string
.
Returns the string untouched if there are no occurrences.
Examples
iex> String.replace_trailing("hello world", " world", "")
"hello"
iex> String.replace_trailing("hello world world", " world", "")
"hello"
iex> String.replace_trailing("hello world", " world", " mundo")
"hello mundo"
iex> String.replace_trailing("hello world world", " world", " mundo")
"hello mundo mundo"
Reverses the graphemes in given string.
Examples
iex> String.reverse("abcd")
"dcba"
iex> String.reverse("hello world")
"dlrow olleh"
iex> String.reverse("hello ∂og")
"go∂ olleh"
Keep in mind reversing the same string twice does not necessarily yield the original string:
iex> "̀e"
"̀e"
iex> String.reverse("̀e")
"è"
iex> String.reverse String.reverse("̀e")
"è"
In the first example the accent is before the vowel, so it is considered two graphemes. However, when you reverse it once, you have the vowel followed by the accent, which becomes one grapheme. Reversing it again will keep it as one single grapheme.
Returns a substring from the offset given by the start of the range to the offset given by the end of the range.
If the start of the range is not a valid offset for the given
string or if the range is in reverse order, returns ""
.
If the start or end of the range is negative, the whole string is traversed first in order to convert the negative indices into positive ones.
Remember this function works with Unicode graphemes and considers
the slices to represent grapheme offsets. If you want to split
on raw bytes, check Kernel.binary_part/3
instead.
Examples
iex> String.slice("elixir", 1..3)
"lix"
iex> String.slice("elixir", 1..10)
"lixir"
iex> String.slice("elixir", 10..3)
""
iex> String.slice("elixir", -4..-1)
"ixir"
iex> String.slice("elixir", 2..-1)
"ixir"
iex> String.slice("elixir", -4..6)
"ixir"
iex> String.slice("elixir", -1..-4)
""
iex> String.slice("elixir", -10..-7)
""
iex> String.slice("a", 0..1500)
"a"
iex> String.slice("a", 1..1500)
""
Returns a substring starting at the offset start
, and of
length len
.
If the offset is greater than string length, then it returns ""
.
Remember this function works with Unicode graphemes and considers
the slices to represent grapheme offsets. If you want to split
on raw bytes, check Kernel.binary_part/3
instead.
Examples
iex> String.slice("elixir", 1, 3)
"lix"
iex> String.slice("elixir", 1, 10)
"lixir"
iex> String.slice("elixir", 10, 3)
""
iex> String.slice("elixir", -4, 4)
"ixir"
iex> String.slice("elixir", -10, 3)
""
iex> String.slice("a", 0, 1500)
"a"
iex> String.slice("a", 1, 1500)
""
iex> String.slice("a", 2, 1500)
""
Divides a string into substrings at each Unicode whitespace occurrence with leading and trailing whitespace ignored. Groups of whitespace are treated as a single occurrence. Divisions do not occur on non-breaking whitespace.
Examples
iex> String.split("foo bar")
["foo", "bar"]
iex> String.split("foo" <> <<194, 133>> <> "bar")
["foo", "bar"]
iex> String.split(" foo bar ")
["foo", "bar"]
iex> String.split("no\u00a0break")
["no\u00a0break"]
Divides a string into substrings based on a pattern.
Returns a list of these substrings. The pattern can be a string, a list of strings or a regular expression.
The string is split into as many parts as possible by
default, but can be controlled via the parts: pos_integer
option.
If you pass parts: :infinity
, it will return all possible parts
(:infinity
is the default).
Empty strings are only removed from the result if the
trim
option is set to true
(default is false
).
Examples
Splitting with a string pattern:
iex> String.split("a,b,c", ",")
["a", "b", "c"]
iex> String.split("a,b,c", ",", parts: 2)
["a", "b,c"]
iex> String.split(" a b c ", " ", trim: true)
["a", "b", "c"]
A list of patterns:
iex> String.split("1,2 3,4", [" ", ","])
["1", "2", "3", "4"]
A regular expression:
iex> String.split("a,b,c", ~r{,})
["a", "b", "c"]
iex> String.split("a,b,c", ~r{,}, parts: 2)
["a", "b,c"]
iex> String.split(" a b c ", ~r{\s}, trim: true)
["a", "b", "c"]
Splitting on empty patterns returns graphemes:
iex> String.split("abc", ~r{})
["a", "b", "c", ""]
iex> String.split("abc", "")
["a", "b", "c", ""]
iex> String.split("abc", "", trim: true)
["a", "b", "c"]
iex> String.split("abc", "", parts: 2)
["a", "bc"]
A precompiled pattern can also be given:
iex> pattern = :binary.compile_pattern([" ", ","])
iex> String.split("1,2 3,4", pattern)
["1", "2", "3", "4"]
Splits a string into two at the specified offset. When the offset given is negative, location is counted from the end of the string.
The offset is capped to the length of the string. Returns a tuple with two elements.
Note: keep in mind this function splits on graphemes and for such it
has to linearly traverse the string. If you want to split a string or
a binary based on the number of bytes, use Kernel.binary_part/3
instead.
Examples
iex> String.split_at "sweetelixir", 5
{"sweet", "elixir"}
iex> String.split_at "sweetelixir", -6
{"sweet", "elixir"}
iex> String.split_at "abc", 0
{"", "abc"}
iex> String.split_at "abc", 1000
{"abc", ""}
iex> String.split_at "abc", -1000
{"", "abc"}
Returns an enumerable that splits a string on demand.
This is in contrast to split/3
which splits all
the string upfront.
Note splitter does not support regular expressions (as it is often more efficient to have the regular expressions traverse the string at once than in multiple passes).
Options
- :trim - when
true
, does not emit empty patterns
Returns true
if string
starts with any of the prefixes given.
prefix
can be either a single prefix or a list of prefixes.
Examples
iex> String.starts_with? "elixir", "eli"
true
iex> String.starts_with? "elixir", ["erlang", "elixir"]
true
iex> String.starts_with? "elixir", ["erlang", "ruby"]
false
An empty string will always match:
iex> String.starts_with? "elixir", ""
true
iex> String.starts_with? "elixir", ["", "other"]
true
Converts a string to an atom.
Currently Elixir does not support the conversion of strings that contain Unicode codepoints greater than 0xFF.
Inlined by the compiler.
Examples
iex> String.to_atom("my_atom")
:my_atom
Converts a string into a charlist.
Specifically, this functions takes a UTF-8 encoded binary and returns a list of its integer
codepoints. It is similar to codepoints/1
except that the latter returns a list of codepoints as
strings.
In case you need to work with bytes, take a look at the
:binary
module.
Examples
iex> String.to_charlist("æß")
'æß'
Converts a string to an existing atom.
Currently Elixir does not support the conversion of strings that contain Unicode codepoints greater than 0xFF.
Inlined by the compiler.
Examples
iex> _ = :my_atom
iex> String.to_existing_atom("my_atom")
:my_atom
iex> String.to_existing_atom("this_atom_will_never_exist")
** (ArgumentError) argument error
Returns a float whose text representation is string
.
string
must be the string representation of a float.
If a string representation of an integer wants to be used,
then Float.parse/1
should be used instead,
otherwise an argument error will be raised.
Inlined by the compiler.
Examples
iex> String.to_float("2.2017764e+0")
2.2017764
iex> String.to_float("3.0")
3.0
Returns an integer whose text representation is string
.
Inlined by the compiler.
Examples
iex> String.to_integer("123")
123
Returns an integer whose text representation is string
in base base
.
Inlined by the compiler.
Examples
iex> String.to_integer("3FF", 16)
1023
Returns a string where all leading and trailing Unicode whitespaces have been removed.
Examples
iex> String.trim("\n abc\n ")
"abc"
Returns a string where all leading and trailing to_trim
s have been
removed.
Examples
iex> String.trim("a abc a", "a")
" abc "
Returns a string where all leading Unicode whitespaces have been removed.
Examples
iex> String.trim_leading("\n abc ")
"abc "
Returns a string where all leading to_trim
s have been removed.
Examples
iex> String.trim_leading("__ abc _", "_")
" abc _"
iex> String.trim_leading("1 abc", "11")
"1 abc"
Returns a string where all trailing Unicode whitespaces has been removed.
Examples
iex> String.trim_trailing(" abc\n ")
" abc"
Returns a string where all trailing to_trim
s have been removed.
Examples
iex> String.trim_trailing("_ abc __", "_")
"_ abc "
iex> String.trim_trailing("abc 1", "11")
"abc 1"
Converts all characters in the given string to uppercase.
Examples
iex> String.upcase("abcd")
"ABCD"
iex> String.upcase("ab 123 xpto")
"AB 123 XPTO"
iex> String.upcase("olá")
"OLÁ"


--- layout: newsstory title: THE CUP match: DMC SF Yeltz 2 Chippenham 1 ---
Despite our poor league form we've been mostly excellent in Cups this season, and we continued in that vein to reach the League Cup final through a 2-1 victory against Chippenham. After going behind in the first half, we came back through 2 pens from Fraser McHugh to earn a well-deserved victory.
The final will be against Crawley, but I'm not sure about the format yet - never paid much attention to the competition this far to be honest. I'm sure someone will let me know.
More good news tonight when relegation rivals Hastings lost at Bath, and if we can beat Cambridge on Saturday we'll be right back in the thick of things. Let's hope we can take some confidence from tonight into the rest of the season.