--- layout: post title: "The State pattern and the State monad" description: "The names are the same. Is there a connection? An article for object-oriented programmers." date: 2022-09-05 12:48 UTC tags: [Software Design, Design Patterns, Functional Programming] image: "/content/binary/state-monad-venn.png" image_alt: "Venn diagram with the two sets state monad and polymorphism. The intersection is labelled state." --- {% include JB/setup %}
{{ page.description }}
This article is part of a series of articles about specific design patterns and their category theory counterparts. In this article I compare the State design pattern to the State monad.
Since the design pattern and the monad share the name State you'd think that they might be isomorphic, but it's not quite that easy. I find it more likely that the name is an example of parallel evolution. Monads were discovered by Eugenio Moggi in the early nineties, and Design Patterns is from 1994. That's close enough in time that I find it more likely that whoever came up with the names found them independently. State, after all, is hardly an exotic word.
Thus, it's possible that the choice of the same name is coincidental. If this is true (which is only my conjecture), does the State pattern have anything in common with the State monad? I find that the answer is a tentative yes. The State design pattern describes an open polymorphic stateful computation. That kind of computation can also be described with the State monad.
This article contains a significant amount of code, and it's all quite abstract. It examines the abstract shape of the pattern, so there's little prior intuition on which to build an understanding. While later articles will show more concrete examples, if you want to follow along, you can use the GitHub repository.
Design Patterns is a little vague when it comes to representing the essential form of the pattern. What one can deduce from the diagram in the Structure section describing the pattern, you have an abstract State
class with a Handle
method like this:
public virtual void Handle(Context context) { }
This, however, doesn't capture all scenarios. What if you need to pass more arguments to the method? What if the method returns a result? What if there's more than one method?
Taking into account all those concerns, you might arrive at a more generalised description of the State pattern where an abstract State
class might define methods like these:
public abstract Out1 Handle1(Context context, In1 in1); public abstract Out2 Handle2(Context context, In2 in2);
There might be an arbitrary number of Handle
methods, from Handle1
to HandleN
, each with their own input and return types.
The idea behind the State pattern is that clients don't interact directly with State
objects. Instead, they interact with a Context
object that delegates operations to a State
object, passing itself as an argument:
public Out1 Request1(In1 in1) { return State.Handle1(this, in1); } public Out2 Request2(In2 in2) { return State.Handle2(this, in2); }
Classes that derive from the abstract State
may then mutate context.State
.
public override Out2 Handle2(Context context, In2 in2) { if (in2 == In2.Epsilon) context.State = new ConcreteStateB(); return Out2.Eta; }
Clients interact with the Context
object and aren't aware of this internal machinery:
var actual = ctx.Request2(in2);
With such state mutation going on, is it possible to refactor to a design that uses immutable data and pure functions?
When you have a void
method that mutates state, you can refactor it to a pure function by leaving the existing state unchanged and instead returning the new state. What do you do, however, when the method in question already returns a value?
This is the case with the generalised HandleN
methods, above.
One way to resolve this problem is to introduce a more complex type to return. To avoid too much duplication or boilerplate code, you could make it a generic type:
public sealed class StatePair<T> { public StatePair(T value, State state) { Value = value; State = state; } public T Value { get; } public State State { get; } public override bool Equals(object obj) { return obj is StatePair<T> result && EqualityComparer<T>.Default.Equals(Value, result.Value) && EqualityComparer<State>.Default.Equals(State, result.State); } public override int GetHashCode() { return HashCode.Combine(Value, State); } }
This enables you to change the signatures of the Handle
methods:
public abstract StatePair<Out1> Handle1(Context context, In1 in1); public abstract StatePair<Out2> Handle2(Context context, In2 in2);
This refactoring is always possible. Even if the original return type of a method was void
, you can use a unit type as a replacement for void. While redundant but consistent, a method could return StatePair<Unit>
.
The above StatePair
type is so coupled to a particular State
class that it's not reusable. If you had more than one implementation of the State pattern in your code base, you'd have to duplicate that effort. That seems wasteful, so why not make the type generic in the state dimension as well?
public sealed class StatePair<TState, T> { public StatePair(T value, TState state) { Value = value; State = state; } public T Value { get; } public TState State { get; } public override bool Equals(object obj) { return obj is StatePair<TState, T> pair && EqualityComparer<T>.Default.Equals(Value, pair.Value) && EqualityComparer<TState>.Default.Equals(State, pair.State); } public override int GetHashCode() { return HashCode.Combine(Value, State); } }
When you do that then clearly you'd also need to modify the Handle
methods accordingly:
public abstract StatePair<State, Out1> Handle1(Context context, In1 in1); public abstract StatePair<State, Out2> Handle2(Context context, In2 in2);
Notice that, as is the case with the State functor, the type declares the type with TState
before T
, while the constructor takes T
before TState
. While odd and potentially confusing, I've done this to stay consistent with my previous articles, which again do this to stay consistent with prior art (mainly Haskell).
With StatePair
you can make the methods pure.
Since Handle
methods can now return a new state instead of mutating objects, they can be pure functions. Here's an example:
public override StatePair<State, Out2> Handle2(Context context, In2 in2) { if (in2 == In2.Epsilon) return new StatePair<State, Out2>(Out2.Eta, new ConcreteStateB()); return new StatePair<State, Out2>(Out2.Eta, this); }
The same is true for Context
:
public StatePair<Context, Out1> Request1(In1 in1) { var pair = State.Handle1(this, in1); return new StatePair<Context, Out1>(pair.Value, new Context(pair.State)); } public StatePair<Context, Out2> Request2(In2 in2) { var pair = State.Handle2(this, in2); return new StatePair<Context, Out2>(pair.Value, new Context(pair.State)); }
Does this begin to look familiar?
The StatePair
class is nothing but a glorified tuple. Armed with that knowledge, you can introduce a variation of the IState interface I used to introduce the State functor:
public interface IState<TState, T> { StatePair<TState, T> Run(TState state); }
This variation uses the explicit StatePair
class as the return type of Run
, rather than a more anonymous tuple. These representations are isomorphic. (That might be a good exercise: Write functions that convert from one to the other, and vice versa.)
You can write the usual Select
and SelectMany
implementations to make IState
a functor and monad. Since I have already shown these in previous articles, I'm also going to skip those. (Again, it might be a good exercise to implement them if you're in doubt of how they work.)
You can now, for example, use C# query syntax to run the same computation multiple times:
IState<Context, (Out1 a, Out1 b)> s = from a in in1.Request1() from b in in1.Request1() select (a, b); StatePair<Context, (Out1 a, Out1 b)> t = s.Run(ctx);
This example calls Request1
twice, and collects both return values in a tuple. Running the computation with a Context
will produce both a result (the two outputs a
and b
) as well as the 'current' Context
(state).
Request1
is a State-valued extension method on In1
:
public static IState<Context, Out1> Request1(this In1 in1) { return from ctx in Get<Context>() let p = ctx.Request1(in1) from _ in Put(p.State) select p.Value; }
Notice the abstraction level in play. This extension method doesn't return a StatePair
, but rather an IState
computation, defined by using the State monad's Get and Put functions. Since the computation is running with a Context
state, the computation can Get
a ctx
object and call its Request1
method. This method returns a pair p
. The computation can then Put
the pair's State
(here, a Context
object) and return the pair's Value
.
This stateful computation is composed from the building blocks of the State monad, including query syntax supported by SelectMany
, Get
, and Put
.
This does, however, still feel unsatisfactory. After all, you have to know enough of the details of the State monad to know that ctx.Request1
returns a pair of which you must remember to Put
the State
. Would it be possible to also express the underlying Handle
methods as stateful computations?
The StatePair
class is isomorphic to a pair (a two-tuple), and we know that a pair gives rise to a bifunctor:
public StatePair<TState1, T1> SelectBoth<TState1, T1>( Func<T, T1> selectValue, Func<TState, TState1> selectState) { return new StatePair<TState1, T1>( selectValue(Value), selectState(State)); }
You can use SelectBoth
to implement both Select
and SelectState
. In the following we're only going to need SelectState
:
public StatePair<TState1, T> SelectState<TState1>(Func<TState, TState1> selectState) { return SelectBoth(x => x, selectState); }
This enables us to slightly simplify the Context
methods:
public StatePair<Context, Out1> Request1(In1 in1) { return State.Handle1(this, in1).SelectState(s => new Context(s)); } public StatePair<Context, Out2> Request2(In2 in2) { return State.Handle2(this, in2).SelectState(s => new Context(s)); }
Keep in mind that Handle1
returns a StatePair<State, Out1>
, Handle2
returns StatePair<State, Out2>
, and so on. While Request1
calls Handle1
, it must return a StatePair<Context, Out1>
rather than a StatePair<State, Out1>
. Since StatePair
is a bifunctor, the Request1
method can use SelectState
to map the State
to a Context
.
Unfortunately, this doesn't seem to move us much closer to being able to express the underlying functions as stateful computations. It does, however, set up the code so that the next change is a little easier to follow.
Is it possible to express the Handle
methods on State
as IState
computations? One option is to write another extension method:
public static IState<State, Out1> Request1S(this In1 in1) { return from s in Get<State>() let ctx = new Context(s) let p = s.Handle1(ctx, in1) from _ in Put(p.State) select p.Value; }
I had to add an S
suffix to the name, since it only differs from the above Request1
extension method on its return type, and C# doesn't allow method overloading on return types.
You can add a similar Request2S
extension method. It feels like boilerplate code, but enables us to express the Context
methods in terms of running stateful computations:
public StatePair<Context, Out1> Request1(In1 in1) { return in1.Request1S().Run(State).SelectState(s => new Context(s)); } public StatePair<Context, Out2> Request2(In2 in2) { return in2.Request2S().Run(State).SelectState(s => new Context(s)); }
This still isn't entirely satisfactory, since the return types of these Request
methods are state pairs, and not IState
values. The above Request1S
function, however, contains a clue about how to proceed. Notice how it can create a Context
object from the underlying State
, and convert that Context
object back to a State
object. That's a generalizable idea.
While it's possible to map the TState
dimension of the state pair, it seems harder to do it on IState<TState, T>
. A tuple, after all, is covariant in both dimensions. The State monad, on the other hand, is neither co- nor contravariant in the state dimension. You can deduce this with positional variance analysis (which I've learned from Thinking with Types). In short, this is because TState
appears as both input and output in StatePair<TState, T> Run(TState state)
- it's neither co- nor contravariant, but rather invariant.
What little option is left us, then, is to make IState
an invariant functor in the state dimension:
public static IState<TState1, T> SelectState<TState, TState1, T>( this IState<TState, T> state, Func<TState, TState1> forward, Func<TState1, TState> back) { return from s1 in Get<TState1>() let s = back(s1) let p = state.Run(s) from _ in Put(forward(p.State)) select p.Value; }
Given an IState<TState, T>
the SelectState
function enables us to turn it into a IState<TState1, T>
. This is, however, only possible if you can translate both forward
and back
between two representations. When we have two such translations, we can produce a new computation that runs in TState1
by first using Get
to retrieve a TState1
value from the new environment, translate it back
to TState
, which enables the expression to Run
the state
. Then translate the resulting p.State
forward
and Put
it. Finally, return the Value
.
As Sandy Maguire explains:
"... an invariant type
T
allows you to map froma
tob
if and only ifa
andb
are isomorphic. [...] an isomorphism betweena
andb
means they're already the same thing to begin with."
This may seem limiting, but is enough in this case. The Context
class is only a wrapper of a State
object:
public Context(State state) { State = state; } public State State { get; }
If you have a State
object, you can create a Context
object via the Context
constructor. On the other hand, if you have a Context
object, you can get the wrapped State
object by reading the State
property.
The first improvement this offers is simplification of the Request1
extension method:
public static IState<Context, Out1> Request1(this In1 in1) { return in1.Request1S().SelectState(s => new Context(s), ctx => ctx.State); }
Recall that Request1S
returns a IState<State, Out1>
. Since a two-way translation between State
and Context
exists, SelectState
can translate IState<State, Out1>
to IState<Context, Out1>
.
The same applies to the equivalent Request2
extension method.
This, again, enables us to rewrite the Context
methods:
public StatePair<Context, Out1> Request1(In1 in1) { return in1.Request1().Run(this); } public StatePair<Context, Out2> Request2(In2 in2) { return in2.Request2().Run(this); }
While this may seem like an insignificant change, one result has been gained: This last refactoring pushed the Run
call to the right. It's now clear that each expression is a stateful computation, and that the only role that the Request
methods play is to Run
the computations.
This illustrates that the Request
methods can be decomposed into two decoupled steps:
Context
wrapper class now?
A reasonable next refactoring might be to remove the context
parameter from each of the Handle
methods. After all, this parameter is a remnant of the State design pattern. Its original purpose was to enable State
implementers to mutate the context
by changing its State
.
After refactoring to immutable functions, the context
parameter no longer needs to be there - for that reason. Do we need it for other reasons? Does it carry other information that a State
implementer might need?
In the form that the code now has, it doesn't. Even if it did, we could consider moving that data to the other input parameter: In1
, In2
, etcetera.
Therefore, it seems sensible to remove the context
parameter from the State
methods:
public abstract StatePair<State, Out1> Handle1(In1 in1); public abstract StatePair<State, Out2> Handle2(In2 in2);
This also means that a function like Request1S
becomes simpler:
public static IState<State, Out1> Request1S(this In1 in1) { return from s in Get<State>() let p = s.Handle1(in1) from _ in Put(p.State) select p.Value; }
Since Context
and State
are isomorphic, you can rewrite all callers of Context
to instead use State
, like the above example:
IState<State, (Out1 a, Out1 b)> s = from a in in1.Request1() from b in in1.Request1() select (a, b); var t = s.Run(csa);
Do this consistently, and you can eventually delete the Context
class.
With the Context
class gone, you're left with the abstract State
class and its implementers:
public abstract class State { public abstract StatePair<State, Out1> Handle1(In1 in1); public abstract StatePair<State, Out2> Handle2(In2 in2); }
One further change worth considering might be to change the abstract base class to an interface.
In this article, I've considered the general case where the State
class supports an arbitrary number of independent state transitions, symbolised by the methods Handle1
and Handle2
. With an arbitrary number of such state transitions, you would have additional methods up to HandleN
for N independent state transitions.
At the other extreme, you may have just a single polymorphic state transition function. My intuition tells me that that's more likely to be the case than one would think at first.
You can view the State design pattern as a combination of two common practices in object-oriented programming: Mutation and polymorphism.
The patterns in Design Patterns rely heavily on mutation of object state. Most other 'good' object-oriented code tends to do likewise.
Proper object-oriented code also makes good use of polymorphism. Again, refer to Design Patterns or a book like Refactoring for copious examples.
I view the State pattern as the intersection of these two common practices. The problem to solve is this:
"Allow an object to alter its behavior when its internal state changes."
The State pattern achieves that goal by having an inner polymorphic object (State
) wrapped by an container object (Context
). The State
objects can mutate the Context
, which enables them to replace themselves with other states.
While functional programming also has notions of polymorphism, a pure function can't mutate state. Instead, a pure function must return a new state, leaving the old state unmodified. If there's nothing else to return, you can model such state-changing behaviour as an endomorphism. The article From State tennis to endomorphism gives a quite literal example of that.
Sometimes, however, an object-oriented method does more than one thing: It both mutates state and returns a value. (This, by the way, violates the Command Query Separation principle.) The State monad is the functional way of doing that: Return both the result and the new state.
Essentially, you replace mutation with the State monad.
From a functional perspective, then, we can view the State pattern as the intersection of polymorphism and the State monad.
This article is both long and abstract. Some examples might be helpful, so I'll give a few in separate articles:
You can view the State design pattern as the intersection of polymorphism and mutation. Both are object-oriented staples. The pattern uses polymorphism to model state, and mutation to change from one polymorphic state to another.
In functional programming pure functions can't mutate state. You can often design around that problem, but if all else fails, the State monad offers a general-purpose alternative to both return a value and change object state. Thus, you can view the functional equivalent of the State pattern as the intersection of polymorphism and the State monad.
Next: Refactoring the TCP State pattern example to pure functions.


vrEmbed Documentation
Documentation home
|
Using vrEmbed
|
Quickstart
|
Placing images and text
|
Creating stories
Using vrEmbed
A visual guide to using the controls and interface in a vrEmbed.
Quickstart
A fast-start guide to taking images and putting them in a vrEmbed.
Placing images and text
How to place images, text and controls.
Creating stories
How to create more complex scenes and stories.
vrEmbed is (c) Bhautik Joshi 2015-16 and available under the
Apache 2.0
Open Source license.


This Android App is aimed at providing artists in our time with a resolve for marketing their art and more so bridging the apparent gap between artists and clients.We provide a platform for emerging and established artists to exhibit, promote, and share their works with an enthusiastic, art-centric community
With the recent advancement in technology the commercial drone-users demand an innovative, cost-effective and modulated solution to help in all applications of drone.The drone controlled by an Android application, that is written in Java, connected via WI-FI and tcp/ip protocol.C and C++ code is used to program the EEPROM.


Josué
Martínez Moreno
PhD Candidate - Research School of Earth Sciences
Australian National University
Josué
Martínez Moreno
PhD Candidate - Research School of Earth Sciences
Australian National University
Biography
Research & Others
Design And Use Online Platforms To Learn Mathematics And The Use Of Them In. Simulations Of Problems In Applied Sciences.
Transport and dispersion of passive tracers of the Coatzacoalcos and Grijalva-Usumacinta Rivers Plumes into the Gulf of Mexico (In Preparation)
Contribution of Mesoscale Eddies into Eddy Kinetic Energy Trends (In Preparation)
Tools
Media
Blog
Location


Do you expect that applets have a main
method?
No.
The methods of an applet are called by another program,
not by its own main
method.
An applet is an object that is used by another program,
typically a Web browser.
The Web browser is the application program and (at least conceptually)
holds the main()
method.
The applet part of a Web page
provides services (methods) to the browser when the browser asks for them.
An applet object has many
instance variables and methods.
Most of this is in the definition of Applet
.
To access these definitions,
your program should import java.applet.Applet
and java.awt.*
.
Here is the code for a small applet.
The name of the class is AEHousman
and the name of the source file is AEHousman.java.
import java.applet.Applet; import java.awt.*; public class AEHousman extends Applet { public void paint ( Graphics gr ) { setBackground( Color.pink ); gr.drawString("Loveliest of trees, the cherry now", 25, 30); gr.drawString("Is hung with bloom along the bough,", 25, 50); gr.drawString("And stands about the woodland ride", 25, 70 ); gr.drawString("Wearing white for Eastertide." ,25, 90); gr.drawString("--- A. E. Housman" ,50, 130); } }
Compile the applet just like an application
using javac AEHousman.java
.
This produces a bytecode file called AEHousman.class
.
Now it can be used in a Web page.
Here is what this applet does:
This applet is explained in the next several pages.


The Game of Game of Games
The Game of Game of Games is my entry into the #TVGameJam. This was a solo development effort as well as my first game! It was inspired by the television show, Ellen's Game of Games.
The project source is available on GitHub
The player is prompted to select a category and answer the corresponding questions within a ten second time limit. If they get one answer wrong they fail the category and must choose another. Three strikes and you're out! There is also a challenge mode that endlessly shuffles categories until the strike limit is reached.
The game treats each correct answer as a point and stores the time remaining for every correct answer as the player's speed. Scores are submitted to the leaderboard sorted by questions correct and then by speed.
Thanks to my wonderful wife Carina for help with design, playtesting, and research
Leaderboard
| Name | Correct | Speed |
|---|


One of the most amazing parts of working at npm is the passion of our userbase. People make fan art. A fan invented our mascot. This stuff just happens.
Yesterday at lunch, we got into a run of punny song titles based on musicals, leading to a series of tweets about npm the musical. By late that evening, what landed in our inbox? Full lyrics to one of the songs, courtesy of the astonishingly creative Revin Guillen. Not only is it a catchy song, it’s a surprisingly thorough overview of npm’s features and functionality. We are blown away.
I Am The Very Model Of A Modern Package Manager
(To the tune of I Am The Very Model Of A Modern Major General.)
I am the very model of a modern package manager
I’ve information current, deprecated in my cache-ager
I know the code you write has other modules (“mod-you-uhls”) it depends on
And I collect it all for you from first the moment you log on
My registry with calculations teeming mathematical
Dependencies relationshipped by edges linked quite graph-ical
The versions, stars, and issues, bugs all published for the world to see
With many cheerful links to source control for the reposit'ry
With many cheerful links to source control for the reposit'ry
With many cheerful links to source control for the reposit'ry
With many cheerful links to source control for the reposiposit'ry
I’m very good at testing, tagging, publishing your libraries
I find the dupes and de- the dupes and you can rebuild all of these
In short, in matters JavaScript, dependency, and modular
I am the very model of a modern package manager
In short, in matters JavaScript, dependency, and modular
It is the very model of a modern package manager
I know your repo’s history, can shrinkwrap all the deps you need
I answer all the queries, many millions served today indeed
I quote the docs to you when asked, or open them in Chrome at least
I’m active all the time, in time zones all the way from west to east
I can uninstall, unlink, unpublish, unstar, or just un
I know your login name and I can whoami
for everyone
My interface is quick and you can write instructions easily
Abbreviate commands so they’re as terse as ‘r’, ’s’, ‘i’, and 'c’
Abbreviate commands so they’re as terse as 'r’, ’s’, 'i’, and 'c’
Abbreviate commands so they’re as terse as 'r’, ’s’, 'i’, and 'c’
Abbreviate commands so they’re as terse as 'r’, ’s’, 'i’, and 'i’ and 'c’
Then I can run-script all the things, lifecycle hooks I can perform
And tell you all about a package: view
'f you want me to inform
In short, in matters JavaScript, dependency, and modular
I am the very model of a modern package manager
In short, in matters JavaScript, dependency, and modular
It is the very model of a modern package manager
In fact when I know what is meant by “version” or (heh) “verison”
When I can give you scripts to help your shell do tab comp-uh-letion
When certain variables are all there in the environment
I enter “plumbing mode”; my output’s based upon the arguments
When I have learnt what progress has been made by npm upgrade
Or npm update
, when identical operations made
In short, when registry’s upgraded underneath transparentlyj
You’ll say a better package manager had never ran à ceej
You’ll say a better package manager had never ran à ceej
You’ll say a better package manager had never ran à ceej
You’ll say a better package manager had never ran à ran â ceej
For my packager'il knowledge, though I’m plucky and adventury
Has really really taken off since funding came in ventury
But still in matters JavaScript, dependency, and modular
I am the very model of a modern package manager
But still in matters JavaScript, dependency, and modular
It is the very model of a modern package manager


Sarah Malde
20
Favorite News Feed Articles
4
Favorite Chats
Basic Info
Dashboard
Username
ballermalde
Favorite Sports
NFL
Sports Role Model
Lionel Messi
Hometown
Atlanta, GA
Favorite Sports Team
Atlanta Braves
My Bio
Hey guys! Every sport is my game, and I'm on here to find some friends to chat with and go to games with! Send me some of your favorite articles because I'm a news geek!
Facebook, Google, Twitter Account that are connected to this account


{% extends 'commercialoperator/emails/base_email.html' %} {% block content %}
Your licence to conduct a commercial event on Conservation and Land Management Act 1984 lands and waters has been approved. A copy of your licence is attached to this email and can be accessed via the Commercial Operator Licensing System (COLS) under your account, click here to login.
Parks and Activities
The activities and parks you are permitted to operate within are listed in Schedule 1 of your licence.
Licence fees and charges
A per participant licence charge is payable in respect to your licence to conduct the commercial event.
You will receive an email from COLS in the form of a compliance requirement, two weeks before payment of the licence charge is due for your event. Complete the requirement at the conclusion of your event, by providing a record of your participants and making payment through COLS.
For more information, please see the ‘How to pay the per participant licence charge’ section of the user guide accessible here
Commercial Operator Handbook - Licence Conditions
All operators are required to adhere to the licence conditions listed in the Commercial Operator Handbook. Please ensure you have read the conditions on your licence and the Commercial Operator Handbook prior to conducting your event, including section 7.1 Commercial events.
A copy of the handbook can be downloaded from the {{settings.DEP_NAME}} website:
{{settings.COLS_HANDBOOK_URL}}Please ensure you have a copy of this handbook on hand either in hardcopy or an electronic version.
Additional Licence Conditions Additional licence conditions are listed in schedule 2 of the licence. If you are required to submit additional documents based on these conditions, you will receive a notification and it will show in the Compliance with requirements table on your COLS home dashboard. You will need to login to your account and ensure you have completed any compliance requirements by the due date by submitting the requested documents via COLS.
If you have any enquiries or need assistance with the online system, please contact a licensing officer on {{settings.DEP_PHONE_FILMING}} or email {{settings.SUPPORT_EMAIL}}
{% endblock %}


Ur-Fascism
by Umberto Eco, 1995.
Eco's prose has left me in the dust on occasion in the past. I missed so many references, or failed to keep up with the relentlessly nested layers of meaning, that I was simply holding on for the ride. This essay matches Eco's characteristically dense, intellectual prose, studded with foreign phrases, and references to contemporary thinkers, historical movements and causes and revolutions and dictatorships, and their antecedents. But it is short, and perhaps in contrast to the flourishes of brilliance that comprise his fiction, this is a factual piece, and is written to be understood rather than to dazzle. It begins by establishing Eco's credentials to speak on this topic, with the first of several entrancing first-hand indications of what it was like to grow up as an intellectual young child in Italy under Mussolini, and the revelations that followed at the opening up of his world at the end of WWII.
He differentiates between the truly totalitarian fascism of, say, Nazism, which subordinated all of life to the state, with the looser, less coherent Italian fascism, noting that this did not derive from any increment of tolerance, merely the absence of a sufficiently encompassing underlying philosophy. Despite this, it is the Italian mode, which was the first right wing dictatorship in modern history, from which subsequent dictators seem to have drawn most stylistic inspiration, and from which our generic term of "fascism" derives.
The last half of the essay describes how fascism means different things in different contexts, but the various incarnations through history have exhibited sufficiently overlapping sets of symptoms as to glean a family resemblance. Eco enumerates 13 identifying traits, noting that the presence of even one of them can be sufficient to allow fascism to coagulate around it. Mostly for my own benefit, (with my own parenthesised observations) they are, briefly:
-
Fascism incorporates a cult of tradition. This can be deployed as an automatic refutation of any undesirable new ideas, enshrining in their place the immutable wisdom of a mythical past. In addition, traditionalism undermines the perceived value of learning in itself - pre-emptively thwarting troublesome intellectuals. This anti-intellectual received wisdom, in order to provide whichever justifications are required of it, requires the syncretistic combination of various ancient beliefs. As a result it must tolerate contradictions. Indeed, the more stark they are, the better they serve the purpose of selecting followers who will obediently think whatever they are told.
-
The rejection of modernism. This is a powerful recruiting tool, enabling the fascist to leverage any dissatisfaction of the populous, laying claim to the emotionally appealing universal solution of a regression to simpler, happier times, while simultaneously rewinding societal progress in equality or liberty. While Nazis and fascists love their technology, this is a superficial tool, used in support of a deeply regressive project, namely the restoration of power to those with the strength and the will to take it. This irrationality goes hand in hand with anti-intellectualism.
-
Value vigor and action above reflection. Thinking is emasculation. Culture is suspect insofar as it aligns with any sort of critical theory or values. Regard centers of analysis or learning such as libraries or universities with suspicion for harboring - or even indoctrinating - people of opposing political viewpoints. Again, this is deeply intertwined with (1) & (2), and its prevalence pre-emptively defuses any kind of mainstream understanding or critique.
-
All of the above make it inevitable that any given fascist regime will be rife with internal contradictions. While modernity achieves its intellectual prowess through the nurturing of diverse thought, fascism cannot possibly withstand any critical analysis. Hence, disagreement is treason.
-
The fascist appeal to popularity exploits and exacerbates the natural fear of the other, and hence is always inherently racist. Expect demonization of immigrants, foreigners, other nation states, as well as other marginalized groups, taking advantage of whatever local contemporary biases and fears might be present.
-
The above exploitation takes the form of an appeal to the frustrations of the middle class - or whichever class can be most useful and readily mobilized by persuasion that their problems are caused by some identifiable other.
-
Modernity genuinely does disintegrate traditional social bonds, along with sources of identity and meaning. Fascism's solution to this is to unify the disaffected under the only remaining banner common to them all, that of patriotism and nationalism. This unity is strengthened by emphasis on the country's enemies, and especially by conspiracy theories of secret international plots against the nation. Followers must feel besieged (as Trump advised the January 6th crowd that "America is under siege"). Eco makes special mention, in the U.S, of Pat Robertson's The New World Order, but potential sources of conspiracy are innumerable.
-
Followers can be riled into frenzy of humiliation at their enemies' wealth or power. Jews control the world and its money. Instead of coastal liberals, refer to coastal elites. But at the same time, the instinct to action requires that enemies can easily be defeated. Hence enemies are simultaneously too weak and too strong. Herein lies one of fascism's greatest weaknesses, responsible for several lost wars, in that it is constitutionally incapable of objectively assessing an enemy's strength.
-
Goad followers into violent action with rhetoric not just of a struggle for survival, but by declaration that life is struggle, and hence pacifism is conspiring with the enemy.
-
While fascism appeals for the participation of the population by promising empowerment for the majority, its naked power lust is a fundamentally aristocratic endeavor. The leader takes power from those too weak to oppose him, disdaining both conquered rivals and the subjugated population. Power struggles within the Party are vicious, and the party rides roughshod over the citizens, who likewise are leagues above the disenfranchised. The hierarchy is strict, steep, and ruthless. Elitism abounds, as does fear of losing one's status.
-
The redress of modernity's threadbare social fabric, by emphasizing nationalism and strength, further erodes interpersonal solidarity. Each individual must becomes their own hero. Strong, independent, and utterly without recourse in times of need. The cult of the hero is intimately entwined with a cult of death. Having only the narrow causes of the nation and the Party to live for, the hero yearns for a heroic death - or, better, to demonstrate their power and status by sending others to their death.
-
The preeminent will to power, so often frustrated in an aristocratic, dog-eat-dog social order, manifests alternately in things like machismo, disdain for women, and phallic fetishization of weapons. Repressed insecurity breeds an outward contempt for unconventional sexuality, including chastity.
-
Under fascism, the people have no innate rights, and hence no material preferences or expression. Instead, the leader pretends to interpret the Will of the People. This charade requires the party apparatus to select and amplify some emotional response of the people, and present it as representative, so that the party can be empowered to act on behalf of that supposedly majority. Consider the amplifications of manufactured outrage about culture war issues, so that elected representatives are empowered to act decisively on their own preferences, against the majority of the population's wishes. This leads directly to confrontation with institutions such as a parliament. Fascism will therefore cast aspersions on any properly functioning parliament's legitimacy.
-
All fascisms make use of their own varieties of NewSpeak, using an impoverished vocabulary and syntax, in order to limit the instruments for critical reasoning. This may appear in apparently innocent forms, from schoolbooks to popular talk shows.


|
|
|
|
|
|
|
|
__parse(self)
Parses a web2py request for the REST interface |
source code
|
|
|
|
|
|
|
__next(self,
id=None,
method=None,
representation=None)
Returns a URL of the current resource |
source code
|
|
|
|
here(self,
representation=None)
URL of the current request |
source code
|
|
|
|
other(self,
method=None,
record_id=None,
representation=None)
URL of a request with different method and/or record_id of the same
resource |
source code
|
|
|
|
there(self,
representation=None)
URL of a HTTP/list request on the same resource |
source code
|
|
|
|
same(self,
representation=None)
URL of the same request with neutralized primary record ID |
source code
|
|
|
|
target(self)
Get the target table of the current request |
source code
|
|
|
|
export_xml(self,
permit=None,
audit=None,
template=None,
filterby=None,
pretty_print=False)
Export the requested resources as XML |
source code
|
|
|
|
export_json(self,
permit=None,
audit=None,
template=None,
filterby=None,
pretty_print=False)
Export the requested resources as JSON |
source code
|
|
|
|
import_xml(self,
tree,
permit=None,
audit=None)
import the requested resources from XML |
source code
|
|
|
|
options_tree(self)
Export field options as element tree |
source code
|
|
|
|
options_xml(self,
pretty_print=False)
Export field options in XML |
source code
|
|
|
|
options_json(self,
pretty_print=False)
Export field options in JSON |
source code
|
|
|
Inherited from object :
__delattr__ ,
__format__ ,
__getattribute__ ,
__hash__ ,
__new__ ,
__reduce__ ,
__reduce_ex__ ,
__repr__ ,
__setattr__ ,
__sizeof__ ,
__str__ ,
__subclasshook__
|


--- layout: default ---
By sending your message you agree to the details you provide being used to help answer your query, such as being contacted via email. For details about how your details will be used please see the Privacy and Cookies policy.


{{Template:UiOslo_Norway/Head}} {{Template:UiOslo_Norway/Header}} {{Template:UiOslo_Norway/TopBar}}
In our project a model of fish schools has been central, the path that led us here is elaborated on in the Engineering page and Integrated Human Practices page . Here we discuss the model we have implemented, the results and how we obtained them. For our project we are using a discrete stochastic model which is based on individuals. Our model is an extension of an existing model [1] which it self is based on [2]. There also exists a continuous version of this model [3]. [1] presents a model for two dimensions, our model follows the same principles but can be used in 3 dimensions. There is of course a big concern caused by this transition, as 3 dimensions introduce more degrees of freedom. But the exact parameters in this model are not “scientific”, rather they are tuned such that the model exhibits behaviors seen in fish schools, for example fish migrating in the same direction. The initial values are random, causing the steady state to vary greatly. As an example, the model can have a varying number of schools.
Our model simulates a fish school. This model is very interesting for our purposes because of its tunable parameters. Each fish has a radius of attraction, repulsion and orientation, with associated weights. With these parameters we can approximately represent the symptoms of many different diseases, such as lethargy represented with less reactive fish by increasing the self weight parameter. As seen in the model description this parameter is the weight of a fish’s own direction. Avoidance behavior can be simulated by increasing the repulsion radius, erratic swimming can be introduced by increasing randomness. These are only approximations of symptoms, but they might give a good indication of what is the best way to detect these symptoms, and of the degree of illness that is required for detection, or how many fish need to be sick.
In our simulations we have made an effort to use measurements that are simple, so that they hopefully contain less information. If our system needs little information to detect differences, then it's a good indication that this might be the case in the real world. All parameters that are kept constant are found on the bottom.
Some authors have extended such a model in literature, trying to make it more accurate. [4] is a good example of this, introducing models of perception, maximum turning angles, variable speed, etc. We unfortunately have not had time to implement these extended versions, but hopefully they could be implemented in the future and extended upon even further.
The structure of what we call a detection system is seen in the graphic below.
Here the sensors could be cameras, and feature extraction could be an estimate of school velocity over time. The classifier would then get a vector of these estimates, coined a feature vector. Given a set of classes, for example “sick” and “healthy” fish, the classifier would try to classify the feature vector as belonging to the sick or healthy classes.
A classifier is an algorithm that implements classification, that is it takes in some data and assigns it a category or class. The basic principle in statistical classification is seen below.
Here x_1 and x_2 are features, and the space their Cartesian product spans out is refereed to as feature space. Each point here is a feature vector, where blue and green belong to two different classes. The goal of a classifier is to find a decision boundary, here the red line. This allows us to classify new data by knowing on which side of the line it falls in feature space. In our case, these features would have 50 dimensions, making a graphical representation quite impossible.
The same principle is also used by the classifier we implemented, a neural net. With machine learning we do classification by what is called supervised learning, where we beforehand have a set of data with an assigned class for training. When we input some of this data, consisting of feature vectors, the classifier (for example a neural net) will give some output. Since we know the class in the training set, we have a preferred output, say 0 for blue and 1 for green. Some smart people have figured out that if you define a loss function as (target-targetOutput)2 one can define functions called optimizers which attempt to minimize this loss. The smart thing here is that the human does not need to know exactly how the classifier tells these two apart, while insight into the data is important one can almost apply this concept blind-foldedly. In our case we can easily create training data, and train a classifier without knowing how it tells the classes apart.
Our detection system consists of a simple neural net where the number of inputs is the number of measurements per simulation. The structure of this neural net was found by trying different configurations on our own. All the data is normalized to the interval [0,1] with min-max feature scaling. Our measurement is defined as
Containing relatively little information, this measurement is just a scalar additive of all the positional components of all N fish. All positional components are used as absolute numbers, placing them only in the positive side of their axis. Our neural net uses the normal sigmoid activation function, mean square error loss function and the ADAM optimizer. The ADAM optimizer has done well in literature, and outperformed the classic gradient descent in our case. More information on ADAM can be found here [5], we used the parameters that the authors advised on page 2 of their article.
Each node calculates an activation function while the arrows represent weights. For the final output we simply classify on the intervals (-infinity, 0.5] and (0.5, infinity).
During the simulation, we take 50 measurements which are fed straight to the neural net after normalization, so our input layer has 50 nodes.
Neural net architecture
| Layer | Input layer | Hidden 1 | Hidden 2 | Hidden 3 | Hidden 4 | Hidden 5 | Output layer |
| Number of nodes | 50 | 40 | 30 | 15 | 10 | 5 | 1 |
Our classifier is trained on 1600 samples, requiring 1600 simulations, 800 “sick” and 800 “healthy”. The number of training iterations over these samples is set to 1000. The number of test samples is 10 % of the 1600 samples, meaning we had 160 test samples. The set of feature vectors is shuffled before being divided into training and test sets.
Results
The most natural part of our simulations to classify is the steady state, at this point the fish are actually schooling. But there is another phase, the transient one that turns out to also be very interesting. There is a big difference between the ease of classification when it comes to these two phases of the simulation. In the start of a simulation there is no order, the system of fishes then undergo a phase transition to an ordered school system. After this phase transition the fish are organized, for example they could be migrating in a common direction. It turns out that it is much easier to classify the fish if one has the additional information contained in this phase transition.
Steady state:
The part of the simulation which was steady state was determined visually and was found to be between 30-100% of the simulation, meaning we take our measurements between the 600th and 2000th iteration. We then take 50 samples of our measurement evenly distributed throughout this part of the simulation.
Parameters for “healthy” fish
| Parameter | value |
| Radius of attraction | 150 |
| Radius of orientation | 55 |
| Radius of repulsion | 14 |
| Attraction weight | 1.4 |
| Repulsion weight | 0.7 |
| Self weight | 1 |
| Orientation weight | 2 |
In our model these parameters give a migratory solution, in other words the steady state is that most or all fish move together in a defined direction. These “healthy” fish are used as our baseline and we want to see if we can tell them apart from other fish whose parameters we have changed, coined “sick” fish.
Parameters for “sick” fish during steady state classification
| Parameter | value |
| Radius of attraction | 150 |
| Radius of orientation | 45 |
| Radius of repulsion | 10 |
| Attraction weight | 0.7 |
| Repulsion weight | 0.35 |
| Self weight | 3 |
| Orientation weight | 1.5 |
The sick fish in this simulation are less reactive and have a lower affinity to orient with others and move towards others. While the choices of parameters might seem a bit arbitrary the important thing here is that the change in parameters does not change the type of steady state that we end up in. So the system with these parameters has a migratory solution. For us to say that we are comparing them this is most important part. Some solutions might be circular or still, comparing them to each other and saying one detects the difference has no value. To clarify, if the parameters changes in such a way that the steady state becomes stationary or circular then these are just two legitimate solutions to the system. So telling them apart does not mean schooling performance has changed.
Our classification results are evaluated with the terms accuracy, precision and recall. Accuracy is defined as where TP is true positive, TN is true negative, FP is false positive and FN is false negative. True refers to a correct classification and false refers to a wrong classification.
Precision is defined as we then construct what is called a confusion matrix as seen below.
| Classified\True | Healthy | Sick | Precision |
| Healthy | TP | FP | |
| Sick | FN | TN | |
| Recall |
With this setup we routinely get an accuracy of over 65%, in the case shown below we had a good run, getting an accuracy of 71.25%. These changes are caused by differences in initialization of the neural network, the initial weights are always random in the beginning.
| Classified\True | Healthy | Sick | Precision |
| Healthy | 61 | 33 | 0.65 |
| Sick | 13 | 53 | 0.80 |
| Recall | 0.82 | 0.62 | Accuracy: 0.7125 |
Transient
Here we sample between 0-70% of the simulation, and we use the same parameters for sick and healthy as above. We then have the same interval size, but the additional information is contained in the phase transition. While the accuracy here is also variable we routinely see it go over 74%.
| Classified\True | Healthy | Sick | Precision |
| Healthy | 68 | 23 | 0.75 |
| Sick | 15 | 54 | 0.78 |
| Recall | 0.82 | 0.70 | Accuracy: 0.7625 |
These differences in accuracy might be a good indication that it would be the same case with real fish, and that also in the real world there would be extra information contained in the phase transition . The phase transition here is a transition between two different global behaviors. In our case we go from not schooling to schooling, in the real world it might be interesting to look at other phase transitions such as disruptions caused by feeding. The exact characteristic of these phase transitions is not known by us, only by the “black box” classifier, it might for example be the time it takes to form a school. One could maybe impose a phase transition in fish by feeding or making them change habitat routinely. This could for example be a system where some gates open and the fish are pushed slowly into another tank: doing this back and forth might allow for frequent observation of phase transitions. While our accuracy might not be perfect, it is not of great concern. This is because in the real world, one could measure and evaluate many times, and if the number of “sick” classifications is high then one could contact a veterinarian or follow some procedure. It makes sense that in the early phases of a disease there is little information to indicate its presence. Therefore, early classification would come with some unreliability. But we are sure others can take this much further. Another result that we believe to be important is that these changes are very hard to spot as humans, even with such drastic parameter changes. As mentioned in our other texts most of the behavioral symptoms described in literature are quite obvious to humans in a disease situation. They have been documented and used by for example veterinarians, but we believe that some smaller changes changes might actually occur much earlier and our project shows that technology can pick up these changes much better than humans at an early stage.
| Name | Value |
| Length of the sides of cubic tank (boundary) | 1000 |
| Scalar multiple for initial normally distributed fish position | 100 |
| Amplitude for normally distributed velocity noise (mu=0, sigma=1) | 0.3 |
| Amplitude for normally distributed position noise (mu=0, sigma=1) | 1 |
| Number of fish | 100 |
| Number of dimensions | 3 |
| Time step | 0.3 |
| Number of steps | 2000 |
| Mean velocity | 1 |
| Max velocity | 3 |
| Initial variance of velocity | 1 |
| Number of measurements | 50 |
Bibliography
[1] Alethea Barbaro , Bjorn Birnir, Kirk Taylor, (2006) “Simulating The Collective Behavior of Schooling FishvWith A Discrete Stochastic Model” funded byThe National Science Foundation,The Research Fund of The University of Iceland, https://www.mrl.ucsb.edu/sites/default/files/mrl_docs/ret_attachments/research/KTaylor.pdf
[2] T. Vicsek, A. Czirok, E. Ben-Jacob, I. Cohen, and O. Shochet. Novel type of phase transition in a system of self-driven particles. Physical Review Letters, 75(6): 1226-1229, 1995
[3] Uchitane, T., Ton, T. V., & Yagi, A. (2015). An Ordinary Differential Equation Model for Fish Schooling. arXiv, 1508.05597. Retrieved from https://arxiv.org/abs/1508.05597v2
[4] Lisette de Boer (2010) “What makes fish school?”,Master Thesis ,Mathematical Institute, Leiden University
[5] Kingma, D., & Ba, J. (2014). Adam: A Method for Stochastic Optimization. International Conference on Learning Representations. Retrieved from https://www.researchgate.net/publication/269935079_Adam_A_Method_for_Stochastic_Optimization


$ \omega_u = $
$ \xi = $
$ \frac{k}{m} = \omega_u^2 = $
$ \frac{c}{m} = 2\xi\omega_u = $
$ \beta = \omega_{u}\big(1-\xi^{2}\big)^{1/2} = $
$ \alpha$=$\omega_{u}\xi = $
Hello there :-)
This is a guide for the free vibrations visualisation
The sliders control the parameters of the dynamic system shown.
Combination of mode shapes give system response. Drag the slider to leftmost for pure first mode response, vise versa.
Reset button sets time to 0s and parameters to default values.
System responses are presented in plots. You can switch tabs by clicking on the dots. You can zoom in by clicking on the graphs and click on the legend to hide certain traces
Have fun!


Site name
Warning Messages
To close the Warning message please click on the "X" symbol.
×
Warning!
An Error Occured.


|
|
acdk_vfile_file2rc converts a binary file to a byte array in a C file.
Content of this chapter: |
acdk_vfile_file2rc <input filename> <output filename>Convert binary file <input filename> into a byte array. Sample:
unsigned char ressource_array[] = { 80, 75, 3, 4, 20, 0, 2, 0, 8, 0, 93, 146, 121, 42, 15, 201, 192, 170, 169, 0, 0 , 0, 116, 1, 0, 0, 27, 0, 21, 0, 97, 99, 100, 107, 45, 49, 46, 48, 49, 47, 97, 99 // and so on } ; int ressource_size = 36608; |
|
| acdk_vfile_readme | acdk_vfile man | acdk_vfile_convert | acdk_vfile_file2rc | Installation | License | ZLIB license | |


com.github.boybeak.adapter
com.github.boybeak.adapter.annotation
com.github.boybeak.adapter.extension
com.github.boybeak.adapter.selection


ComponentNP1
Test Bed -
Please,...go right ahead.
Content DIV (id=bottom-content) in DIV DivStage
Please,...go right ahead.
DIV (Bottom content
ooo 1
Test Bed -
Please,...go right ahead.
Content DIV (id=bottom-content) in DIV DivStage
Please,...go right ahead.
DIV (Bottom content
ooo 1


Student Form
Student Details
About Us
Contact Us
Sign Off
Student's Name
Standard
Age
Gender
Attendance
Parent Interaction


The math symbols < > and | are used only in math mode. Note that left and right angle brackets (which are somewhat taller than < and >) can be obtained with \langle and \rangle commands.
The single right quotation mark, ', produces a prime in math mode. You can also use \prime.
See also Math Formulas,
Math Symbols,
Math Fonts and Styles
Return to LaTeX Table of Contents


proteins KAI DDK sequences eu-KAI clade (Fig. DLK land file MAX protein plant family positions Additional conserved signalling plants D/KAI sequence analysis using charophyte phylogenetic analyses clades structure tree amino identified major performed shown lineage Arabidopsis perception conservation models evolution lycophyte KAIB alignment proteins, set strigolactone {border-style Fig. Plant acid homology receptors group highly px;} sequences. #ffffff;} Table mosses thaliana LINK kb) suggests (Additional However, angiosperm binding evolutionary reference residues sequences, sister branching early ligand members model Biol KAI-like data divergent position present rooted shoot structural topology function likelihood liverworts maximum monilophyte patens primary relative KAIE/F Waters blue core crystal duplication family, given liverwort occurred origin previously seed showing strongly vascular GARLI SMXL Selaginella angiosperms bootstrap eu-D evolution. karrikin known match plants. pockets proteins. species suggested super-clade (as D-like DWARF [], act characteristic clade. dataset different generated instance, lineages moss obtained pathway receptor searches single suggesting used >%, Nelson SLs Wang consistent depicting described did divergence evidence gymnosperms indicated interaction interface internal karrikins likely lineage, moellendorffii multiple px; relatively required separation signal similar similarity suggest trees values {font-family (Table Bennett Cell Leyser Liu Marchantia Sci Smith Thus, alignment. associated base clade, currently development distinct family. font-size gymnosperm implemented independently individual lack level listed non-vascular observed plants, probably provide responses resulting server strong structure. support turn (Figs. (PNG Cladogram DLKB Eu-KAI Flematti I-TASSER KAIA MAX-like Numbers PhyML RbsQ SCF Strigolactone University Zygnematales acids addition algae analysed analyses, available branch clades. compared complex contains defined double; evolution, final form genomes green; grid.. high identify including indicate indicates inferred interactions lineage. modelling named order placed predicted previous regulates removed requirements strigolactones sub-clades understanding (DOCX (see Angiosperm BMC Coleochaete Consistent Conversely, DDK, DDKB Department Furthermore, KAI. Major Nat New Phylogram Physcomitrella Protein Res Scaffidi Science Strigolactones additional analyses. arose article basic border-color border-width branches cavity class close codon congruent containing degradation denote endogenous essentially files function. gene generally genes growth hornwort hornworts lycophytes mechanisms monilophytes mutants neo-functionalization number numbers placement provided receptors, robustness role root scheme solid; species, specific super-clades taxonomic test transcriptome unambiguous vary wider {font-style {font-weight (>% (percent ./pnas. ./pp.. Acad BLAST Bythell-Douglas Cavities Charophyte Curr D-type DLK, Genetic Gymnosperms Indeed, KAI, KAIF Klebsormidium Liang Liverwort MAX, MAX. Models Natl Nature Physiol Planta Preliminary Proc SL-like Similarly, Structural Sun Zhang Zhou ]), a). analysis, angiosperms, annotated bold characteristics. characterized characters). clades, clear clearly code coloured completed composition conservative conserved’ considerable control correct, courier; degree depicted diverged does earlier em; evolved far form. full-length general grouped groups high-order history implies innovation invariant key labelled led likely’ little matched mycorrhizal non-canonical novel occurs orthologues phosphate phylogeny phylogeny. polymorpha positions, positions. pt;} random rates recent regulate related relationships resemble response second sensitivity signalling. significant starting study supplementary taxon template this, transcriptional types understand unified unique work α/β-hydrolase ‘most


pymatgen.analysis.structure_matcher module¶
This module provides classes to perform fitting of structures.
-
class
AbstractComparator
[source]¶ Bases:
monty.json.MSONable
Abstract Comparator class. A Comparator defines how sites are compared in a structure.
-
are_equal
(sp1, sp2)[source]¶ Defines how the species of two sites are considered equal. For example, one can consider sites to have the same species only when the species are exactly the same, i.e., Fe2+ matches Fe2+ but not Fe3+. Or one can define that only the element matters, and all oxidation state information are ignored.
Parameters: - sp1 – First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.
- sp2 – Second species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.
Returns: Boolean indicating whether species are considered equal.
-
get_hash
(composition)[source]¶ Defines a hash to group structures. This allows structures to be grouped efficiently for comparison. The hash must be invariant under supercell creation. (e.g. composition is not a good hash, but fractional_composition might be). Reduced formula is not a good formula, due to weird behavior with fractional occupancy.
Composition is used here instead of structure because for anonymous matches it is much quicker to apply a substitution to a composition object than a structure object.
Parameters: composition (Composition) – composition of the structure Returns: A hashable object. Examples can be string formulas, integers etc.
-
-
class
ElementComparator
[source]¶ Bases:
pymatgen.analysis.structure_matcher.AbstractComparator
A Comparator that matches elements. i.e. oxidation states are ignored.
-
are_equal
(sp1, sp2)[source]¶ True if element:amounts are exactly the same, i.e., oxidation state is not considered.
Parameters: - sp1 – First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.
- sp2 – Second species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.
Returns: Boolean indicating whether species are the same based on element and amounts.
-
-
class
FrameworkComparator
[source]¶ Bases:
pymatgen.analysis.structure_matcher.AbstractComparator
A Comparator that matches sites, regardless of species.
-
are_equal
(sp1, sp2)[source]¶ True if there are atoms on both sites.
Parameters: - sp1 – First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.
- sp2 – Second species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.
Returns: True always
-
-
class
OccupancyComparator
[source]¶ Bases:
pymatgen.analysis.structure_matcher.AbstractComparator
A Comparator that matches occupancies on sites, irrespective of the species of those sites.
-
are_equal
(sp1, sp2)[source]¶ Parameters: - sp1 – First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.
- sp2 – Second species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.
Returns: True if sets of occupancies (amt) are equal on both sites.
-
get_hash
(composition)[source]¶ Defines a hash to group structures. This allows structures to be grouped efficiently for comparison. The hash must be invariant under supercell creation. (e.g. composition is not a good hash, but fractional_composition might be). Reduced formula is not a good formula, due to weird behavior with fractional occupancy.
Composition is used here instead of structure because for anonymous matches it is much quicker to apply a substitution to a composition object than a structure object.
Parameters: composition (Composition) – composition of the structure Returns: A hashable object. Examples can be string formulas, integers etc.
-
-
class
OrderDisorderElementComparator
[source]¶ Bases:
pymatgen.analysis.structure_matcher.AbstractComparator
A Comparator that matches sites, given some overlap in the element composition
-
are_equal
(sp1, sp2)[source]¶ True if there is some overlap in composition between the species
Parameters: - sp1 – First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.
- sp2 – Second species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.
Returns: True always
-
-
class
PointDefectComparator
(check_charge=False, check_primitive_cell=False, check_lattice_scale=False)[source]¶ Bases:
monty.json.MSONable
A class that matches pymatgen Point Defect objects even if their cartesian co-ordinates are different (compares sublattices for the defect)
NOTE: for defect complexes (more than a single defect), this comparator will break.
Parameters: - check_charge (bool) – Gives option to check if charges are identical. Default is False (different charged defects can be same)
- check_primitive_cell (bool) – Gives option to compare different supercells of bulk_structure, rather than directly compare supercell sizes Default is False (requires bulk_structure in each defect to be same size)
- check_lattice_scale (bool) – Gives option to scale volumes of structures to each other identical lattice constants. Default is False (enforces same lattice constants in both structures)
-
class
SpeciesComparator
[source]¶ Bases:
pymatgen.analysis.structure_matcher.AbstractComparator
A Comparator that matches species exactly. The default used in StructureMatcher.
-
are_equal
(sp1, sp2)[source]¶ True if species are exactly the same, i.e., Fe2+ == Fe2+ but not Fe3+.
Parameters: - sp1 – First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.
- sp2 – Second species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.
Returns: Boolean indicating whether species are equal.
-
-
class
SpinComparator
[source]¶ Bases:
pymatgen.analysis.structure_matcher.AbstractComparator
A Comparator that matches magnetic structures to their inverse spins. This comparator is primarily used to filter magnetically ordered structures with opposite spins, which are equivalent.
-
are_equal
(sp1, sp2)[source]¶ True if species are exactly the same, i.e., Fe2+ == Fe2+ but not Fe3+. and the spins are reversed. i.e., spin up maps to spin down, and vice versa.
Parameters: - sp1 – First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.
- sp2 – Second species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.
Returns: Boolean indicating whether species are equal.
-
-
class
StructureMatcher
(ltol=0.2, stol=0.3, angle_tol=5, primitive_cell=True, scale=True, attempt_supercell=False, allow_subset=False, comparator=<pymatgen.analysis.structure_matcher.SpeciesComparator object>, supercell_size='num_sites', ignored_species=None)[source]¶ Bases:
monty.json.MSONable
Class to match structures by similarity.
Algorithm:
Given two structures: s1 and s2
Optional: Reduce to primitive cells.
If the number of sites do not match, return False
Reduce to s1 and s2 to Niggli Cells
Optional: Scale s1 and s2 to same volume.
Optional: Remove oxidation states associated with sites
Find all possible lattice vectors for s2 within shell of ltol.
For s1, translate an atom in the smallest set to the origin
For s2: find all valid lattices from permutations of the list of lattice vectors (invalid if: det(Lattice Matrix) < half volume of original s2 lattice)
For each valid lattice:
If the lattice angles of are within tolerance of s1, basis change s2 into new lattice.
For each atom in the smallest set of s2:
i. Translate to origin and compare fractional sites in structure within a fractional tolerance. ii. If true:
ia. Convert both lattices to cartesian and place both structures on an average lattice ib. Compute and return the average and max rms displacement between the two structures normalized by the average free length per atom
- if fit function called:
if normalized max rms displacement is less than stol. Return True
- if get_rms_dist function called:
if normalized average rms displacement is less than the stored rms displacement, store and continue. (This function will search all possible lattices for the smallest average rms displacement between the two structures)
Parameters: - ltol (float) – Fractional length tolerance. Default is 0.2.
- stol (float) – Site tolerance. Defined as the fraction of the average free length per atom := ( V / Nsites ) ** (1/3) Default is 0.3.
- angle_tol (float) – Angle tolerance in degrees. Default is 5 degrees.
- primitive_cell (bool) – If true: input structures will be reduced to primitive cells prior to matching. Default to True.
- scale (bool) – Input structures are scaled to equivalent volume if true; For exact matching, set to False.
- attempt_supercell (bool) – If set to True and number of sites in cells differ after a primitive cell reduction (divisible by an integer) attempts to generate a supercell transformation of the smaller cell which is equivalent to the larger structure.
- allow_subset (bool) – Allow one structure to match to the subset of another structure. Eg. Matching of an ordered structure onto a disordered one, or matching a delithiated to a lithiated structure. This option cannot be combined with attempt_supercell, or with structure grouping.
- comparator (Comparator) –
A comparator object implementing an equals method that declares declaring equivalency of sites. Default is SpeciesComparator, which implies rigid species mapping, i.e., Fe2+ only matches Fe2+ and not Fe3+.
Other comparators are provided, e.g., ElementComparator which matches only the elements and not the species.
The reason why a comparator object is used instead of supplying a comparison function is that it is not possible to pickle a function, which makes it otherwise difficult to use StructureMatcher with Python’s multiprocessing.
- supercell_size (str) – Method to use for determining the size of a supercell (if applicable). Possible values are num_sites, num_atoms, volume, or an element present in both structures.
- ignored_species (list) – A list of ions to be ignored in matching. Useful for matching structures that have similar frameworks except for certain ions, e.g., Li-ion intercalation frameworks. This is more useful than allow_subset because it allows better control over what species are ignored in the matching.
-
fit_anonymous
(struct1, struct2, niggli=True)[source]¶ Performs an anonymous fitting, which allows distinct species in one structure to map to another. E.g., to compare if the Li2O and Na2O structures are similar.
Parameters: Returns: Whether a species mapping can map struct1 to stuct2
Return type: True/False
-
get_all_anonymous_mappings
(struct1, struct2, niggli=True, include_dist=False)[source]¶ Performs an anonymous fitting, which allows distinct species in one structure to map to another. Returns a dictionary of species substitutions that are within tolerance
Parameters: Returns: list of species mappings that map struct1 to struct2.
-
get_best_electronegativity_anonymous_mapping
(struct1, struct2)[source]¶ Performs an anonymous fitting, which allows distinct species in one structure to map to another. E.g., to compare if the Li2O and Na2O structures are similar. If multiple substitutions are within tolerance this will return the one which minimizes the difference in electronegativity between the matches species.
Parameters: Returns: Mapping of struct1 species to struct2 species
Return type: min_mapping (Dict)
-
get_mapping
(superset, subset)[source]¶ Calculate the mapping from superset to subset.
Parameters: Returns: numpy array such that superset.sites[mapping] is within matching tolerance of subset.sites or None if no such mapping is possible
-
get_rms_anonymous
(struct1, struct2)[source]¶ Performs an anonymous fitting, which allows distinct species in one structure to map to another. E.g., to compare if the Li2O and Na2O structures are similar.
Parameters: Returns: (min_rms, min_mapping) min_rms is the minimum rms distance, and min_mapping is the corresponding minimal species mapping that would map struct1 to struct2. (None, None) is returned if the minimax_rms exceeds the threshold.
-
get_rms_dist
(struct1, struct2)[source]¶ Calculate RMS displacement between two structures
Parameters: Returns: rms displacement normalized by (Vol / nsites) ** (1/3) and maximum distance between paired sites. If no matching lattice is found None is returned.
-
get_s2_like_s1
(struct1, struct2, include_ignored_species=True)[source]¶ Performs transformations on struct2 to put it in a basis similar to struct1 (without changing any of the inter-site distances)
Parameters: Returns: A structure object similar to struct1, obtained by making a supercell, sorting, and translating struct2.
-
get_supercell_matrix
(supercell, struct)[source]¶ Returns the matrix for transforming struct to supercell. This can be used for very distorted ‘supercells’ where the primitive cell is impossible to find
-
get_transformation
(struct1, struct2)[source]¶ Returns the supercell transformation, fractional translation vector, and a mapping to transform struct2 to be similar to struct1.
Parameters: Returns: supercell matrix vector (numpy.ndarray(3)): fractional translation vector mapping (list(int or None)):
The first len(struct1) items of the mapping vector are the indices of struct1’s corresponding sites in struct2 (or None if there is no corresponding site), and the other items are the remaining site indices of struct2.
Return type: supercell (numpy.ndarray(3, 3))
-
group_structures
(s_list, anonymous=False)[source]¶ Given a list of structures, use fit to group them by structural equality.
Parameters: - s_list ([Structure]) – List of structures to be grouped
- anonymous (bool) – Wheher to use anonymous mode.
Returns: A list of lists of matched structures Assumption: if s1 == s2 but s1 != s3, than s2 and s3 will be put in different groups without comparison.


--- layout: post title: '"Post-racial"' date: 2011-09-03 04:51:20.000000000 -07:00 type: post published: true status: publish categories: [] tags: [] meta: _edit_last: '1' author: login: admin email<EMAIL_ADDRESS>display_name: admin first_name: Carina C. last_name: Zon ---
Household median net worth 2011 (2005):
$113k (135k) whites
$6k ($12k) blacks
$6 ($19k) Hispanics
Unemployment rate:
8.2% whites
16.8% blacks
11.3% Latinos
Extraordinary that we're able to hold up the pretense of being a "postracial" society.


--- layout: post title: 'Nokia makes the mobile ''a full member of the internet''' date: 2006-06-13 00:00:00 category: mobile ---
Nokia makes the mobile 'a full member of the internet': "The move also seems to raise a key issue for Nokia – how far the Symbian OS, which it has long championed as the key next generation smartphone system, fits into its new strategy, geared not just to phones but to the emerging ideas of "the internet of things"."


Student Groups
Group Name: Bruce Goldberg
Group ID: 5
Is Active: Yes
Number of students: 1
Sessions
Monday, October 5th 2015 (#298)
Paid for Sam - Brian Skinner on 5/4/16 (SessionCreditID: 17)
Cancel - Bruce Goldberg on 5/4/16
Monday, October 5th 2015 (#298)
Confirm - Brian Skinner on 5/4/16
Paid for Sam - Brian Skinner on 5/4/16 (SessionCreditID: 16)
Monday, October 5th 2015 (#298)
Confirm - Brian Skinner on 5/4/16
Move - Brian Skinner from 4/5/16 to 4/7/16
Paid for Sam - Brian Skinner on 5/4/16 (SessionCreditID: 11)
Monday, October 5th 2015 (#298)
Confirm - Brian Skinner on 5/4/16
Paid for Sam - Brian Skinner on 5/4/16 (SessionCreditID: 6)


Traditional - West Africa
This game is played on an empty 5x6 square board, where each player has 12 stones offboard.
|
| An example White has one stone in reserve, Black has none. White's move. He drops his last stone into cell [1] to prevent the potential attack. After that, Black is trapped on a position where every move leads to capture. |
There is a ZRF to play Yote with Zillions made by Peter Aronson. You can check a picture of a Yote board in here.


http://www.tldp.org/LDP/Linux-Filesystem-Hierarchy/html/proc.html - Detailed information about /proc/
/proc/mounts
/proc/config.gz
/proc/self/fd/[0-9]
Possible candidate for remote code exeution
on a php website something like
?username=/proc/self/fd/9%00cmd=id
uses the null byte terminator and runs your command
/proc/cpuinfo – cpu information
/proc/filesystems – prints filesystems currently in use
/proc/interrupts – prints interrupts currently in use
/proc/ioports – contains a list of the i/o addresses used by various devices connected to the computer
/proc/meminfo
/proc/modules
/proc/stat
/proc/swaps
/proc/version
/proc/self/net/arp


Civil Engineers' Society of Symbiosis (CESS) is a non-registered, non-profit organization within the department of Civil Engineering, Symbiosis International University.
The members of the society include the undergraduate, faculty members, alumni, and research engineers of the Civil Engineering department working together to help and facilitate the overall development of students pursuing Civil Egineering here.
CESS provides platform to showcase and sharpen student's talents through a variety of events and activities planned throughout the year.


Grandma Sends a Thanksgiving Invitation to the Wrong Person and It Grows Into a New Family Tradition
When a grandma from Arizona accidentally invited an unknown teen to a Thanksgiving celebration by sending a text to the wrong number, little did she know that she was going to grow her family. Jamal, the teen, and Wanda, the granny, have already celebrated their third Thanksgiving in a row together and this article will tell you about how it all started.
We at Bright Side are in awe when we read stories that show people’s kindness and friendliness. That’s why we can’t help but share another one with you.
This nice tradition started in 2016 when Jamal Hinton got a message from Wanda Dench, inviting him and his girlfriend to join her for Thanksgiving. “Let me know if you are coming,” she wrote in the text.
Hinton suspected that she had the wrong number and asked Wanda to send him a photo as proof that it was his granny behind the text. The picture that came from Wanda depicted a blonde woman with glasses on and she was definitely not Jamal’s grandma. However, after informing her about the mishap, Jamal asked if he could still join her for the holiday.
Wanda didn’t mind at all, and the teen gladly visited her family. They have quickly become friends, kept in touch throughout the next year, and, as a result, have already celebrated 3 Thanksgivings in a row together.
Celebrating Thanksgiving in 2016.
Celebrating Thanksgiving in 2017.
Celebrating Thanksgiving in 2018.
Hinton has also introduced his girlfriend, Mikaela, to the Dench family.
Wanda says that family is more than blood — it’s the people you want to be with. And we totally agree with her.
Bonus: A video of them celebrating their third Thanksgiving together
Would you go to a stranger’s house if you got mistakenly invited? Or would you prefer to not get into it? We would be glad to hear from you in the comments!
Preview photo credit kingjamal08 / Twitter, kingjamal08 / Twitter


Step by step install the plugin.
npm install ztip --save
or
yarn add ztip
or
Download the most recent version from Github and include the unzipped files in your project. Use the top link on this page.
Step by step create the first ztip instance.
jQuery: Make sure that jQuery library is installed. If it is not that add the following line:

CSS: Next include the CSS in document
:
<link rel="stylesheet" href="ztip.css" />
JS: And the JS just before the closing
tag:

Init: After this line add the following code to create the first instance:

HTML: In this example we selected all .my-tooltip
classes. The will become targets for tooltips.
Hover me

A few examples that demonstrates the plugin's power.
This is the default example with default settings.
DefaultI believe that themes are something that every developer should create based on project requirements. Here are just a few, most basic examples.
Theme: red Theme: blue Theme: green Theme: whiteBut default zTip
gets the tooltip text from title
attribute of current element(hover on). However you are not limited only to this. You can use any other element attribute or DOM element.
By default the tooltip will be on top of target element and will auto arrange itself depending on current viewport.


{{this.number}}
{{set time "2016-09-08"}}
Today is {{time}}.
{{123}}{{each this.list as value index}}
{{if value.user}}
{{include 'test-item-user' as value.user}}
{{else if value.pet}}
{{include 'test-item-pet' as value}}
{{else}}
{{include 'test-item-error'}}
{{/if}}
{{/each}}{{this.undefinedProperty}}


@for((key, value) <- productForm.errors) {
@for(err <- value) {
@err.message
}
}
Update category where your product will appear
Update your product description
@if(product.auction == null){
Update product price and amount
}
Upload product photo
Click Edit photo and select the photos you want to upload.
WARNING: By uploading new photos, old photos will be deleted.
Cancel
}


This is an example Spring application. In addition to showing that I can program with the Spring Framework, I attempt to show off some computer science concepts the reader may not know.
LinkedIn Source on GitHubMany people are familiar with the company Y combinator. Fewer people know the company name is based on a mathematical concept called the fixed point combinator. The Y combinator is the most succinct way to implement recursion in lambda calculus.
If we remove the ability to write recursive code in Java, we can still write code in a style that is not recursive, but then apply the Y combinator to it to make it recursive.
The second concept I will use is memoization. This allows us to trade memory for time, with the optimization divorced from the business logic. Unlike typical caching patterns, the function inputs (or cache keys) are invulnerable to key conflicts that might arise when business requirements change.
I combine these two concepts to implement the fibonacci sequence. The sequence goes as follows: 1, 1, 2, 3, 5, 8, 13... where each number is the sum of the previous two numbers, where f(5) = 5. Naturally, when calculating f(5), you must recalculate all previous numbers, so caching is useful here.


class: center, middle, inverse, title-slide # Statistics ### Introduction to R
Bern R Bootcamp
### June 2020 --- layout: true
        www.therbootcamp.com      Introduction to R | June 2020
 --- # Statistics I .pull-left45[ #### <high>Descriptive statistics</high> with `dplyr` ```r # Group-summarise idiom baselers %>% group_by(sex, eyecor) %>% summarise( N = n(), age_mean = mean(age), height_median = median(height), children_max = max(children) ) ``` #### <high>Simply hypothesis test</high> with `stats` ```r # Simple hypothesis test t.test(baselers$happiness, baselers$fitness, var.equal = TRUE) ``` ] .pull-right45[

 from xkcd.com
 ] --- # `dplyr` + `tidyr` .pull-left5[ To wrangle data in R, we will use the <high><mono>dplyr</mono></high> and <high><mono>tidyr</mono></high> packages, which are part of the <high><mono>tidyverse</mono></high>. | Package | Function| Function| |:-------------|:----| |dplyr | Transformation | `rename()`, `mutate()`, `case_when()`, `*_join()` | |dplyr | Organisation | `arrange()`, `slice()`, `filter()`, `select()` | |tidyr | Organisation | `pivot_longer()`, `pivot_wider()` | |dplyr | Aggregation | `group_by()`, `summarise()` | ] .pull-right4[

 ] --- # Grouped aggregation .pull-left3[ <high>(Conditional) descriptives statistic</high>s are easily calculated using `dplyr`'s `group_by()` and `summerise()` idiom. ```r # Start with data data %>% # AND THEN... # GROUPING VARIABLE GROUP_BY %>% # DO SUMMARIES SUMMARISE( RESULT_1, RESULT_2, RESULT_3 ) ``` ] .pull-right6[

 ] --- # The Pipe! <high>`%>%`</high> .pull-left4[ `dplyr` makes extensive use of a new operator called the "Pipe" <high>`%>%`</high>
 Read the "Pipe" <high>`%>%`</high> as "And Then..."
 ```r # Start with data data %>% # AND THEN... DO_SOMETHING %>% # AND THEN... DO_SOMETHING %>% # AND THEN... DO_SOMETHING %>% # AND THEN... ``` ] .pull-right55[

 This is not a pipe (but %>% is!)
 ] --- # `summarise()` .pull-left45[ Use `summarise()` to create new columns of <high>summary statistics</high>. The result of `summarise()` is always be a tibble. Functions used in `summerise()` <high>must return a single value</high>. ```r data %>% summarise( NAME = SUMMARY_FUN(A), NAME = SUMMARY_FUN(B), ... ) ``` ] .pull-right5[ ```r # Calculate summary statistics baselers %>% summarise( N = n(), age_mean = mean(age), height_median = median(height), children_max = max(children) ) ``` ``` # A tibble: 1 x 4 N age_mean height_median children_max <int> <dbl> <dbl> <dbl> 1 10000 44.6 171. 6 ``` ] --- # `summarise()` .pull-left45[ Use `summarise()` to create new columns of <high>summary statistics</high>. The result of `summarise()` is always be a tibble. Functions used in `summerise()` <high>must return a single value</high>. ```r data %>% summarise( NAME = SUMMARY_FUN(A), NAME = SUMMARY_FUN(B), ... ) ``` ] .pull-right5[ | Function| Purpose | Returns | |:-------------|:-------|:-------| | `n()`| Count values | Single value | | `mean()`, `median()` | Central tendencies | Single value | | `sd()`, `var()` | Variance | Single value | | `max()`, `min()` | Extremes | Single value | | `quantile()` | Quantiles | One or <high>multiple values</high> | | `range()` | Range | <high>Two values<high> | | `table()` | (Cross-) tables | <high>Multiple values<high> | | `summary()` | Overview | <high>Multiple values<high> | ] --- # `group_by()` + `summarise()` .pull-left45[ Use `group_by()` to <high>group data</high> according to one or more columns. Then, use `summarise()` to <high>calculate summary statistics</high> for each group. You can include <high>one or more</high> grouping variables. ```r data %>% group_by(A, B, ...) %>% summarise( NAME = SUMMARY_FUN(A), NAME = SUMMARY_FUN(B), ... ) ``` ] .pull-right5[ ```r # Group data by arm, and calculate many # summary statistics baselers %>% group_by(sex) %>% summarise( N = n(), age_mean = mean(age), height_median = median(height), children_max = max(children) ) ``` ``` # A tibble: 2 x 5 sex N age_mean height_median children_max <chr> <int> <dbl> <dbl> <dbl> 1 female 5000 45.4 164 6 2 male 5000 43.8 178. 6 ``` ] --- # `group_by()` + `summarise()` .pull-left45[ Use `group_by()` to <high>group data</high> according to one or more columns. Then, use `summarise()` to <high>calculate summary statistics</high> for each group. You can include <high>one or more</high> grouping variables. ```r data %>% group_by(A, B, ...) %>% summarise( NAME = SUMMARY_FUN(A), NAME = SUMMARY_FUN(B), ... ) ``` ] .pull-right5[ ```r # Group data by arm, and calculate many # summary statistics baselers %>% group_by(sex, eyecor) %>% summarise( N = n(), age_mean = mean(age), height_median = median(height) ) ``` ``` # A tibble: 4 x 5 # Groups: sex [2] sex eyecor N age_mean height_median <chr> <chr> <int> <dbl> <dbl> 1 female no 1731 45.3 164. 2 female yes 3269 45.5 164 3 male no 1772 43.6 178. 4 male yes 3228 43.9 178. ``` ] --- # Full pipeline .pull-left25[ Combine <high>tranformation</high>, <high>organization</high>, and <high>aggregating</high> operations at once! Just use the <high>pipe %>%</high>! ] .pull-right65[ ```r baselers %>% mutate(catholic = confession == "catholic") %>% filter(sex == "male" & children > 0) %>% group_by(sex, catholic) %>% summarise( N = n(), age_mean = mean(age), income_median = median(income, na.rm = TRUE) ) ``` ``` # A tibble: 3 x 5 # Groups: sex [1] sex catholic N age_mean income_median <chr> <lgl> <int> <dbl> <dbl> 1 male FALSE 2452 43.7 7100 2 male TRUE 1401 44.0 7100 3 male NA 703 43.5 7000 ``` ] --- # Inferential statistics .pull-left6[ Specific tests | Function| Purpose | |:------|:-------| | `t.test()` | Compare group means | | `cor.test()` | Compare correlations | | `chisq.test()` | Compare cell frequencies | | `wilcox.test()` | Compare group means non-parametrically | Fomula-based tests | Function| Purpose | |:-----|:-------| | `lm()`, `glm()`| (Generalized) linear models | | `lmer()`, `glmer()` | (Generalized) mixed-linear models | | `regressionBF()` | Bayesian (generalized) linear models | ] .pull-right35[

 from xkcd.com
 ] --- # `t.test()` .pull-left45[ The <high>t-test</high> compares one group mean versus a <high>reference</high> or versus <high> another group</high>. Compares two means by providing <high>two numeric vectors</high> for the arguments `x`, and `y`. Alternative <high>arguments allow for variations</high>, e.g., to account for unequal variances. ] .pull-right5[ ```r # 2-sample t-test t.test(baselers$happiness, baselers$fitness) ``` ``` Welch Two Sample t-test data: baselers$happiness and baselers$fitness t = 83, df = 15844, p-value <2e-16 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: 1.738 1.822 sample estimates: mean of x mean of y 6.905 5.125 ``` ] --- # `t.test()` .pull-left45[ The <high>t-test</high> compares one group mean versus a <high>reference</high> or versus <high> another group</high>. Compares two means by providing <high>two numeric vectors</high> for the arguments `x`, and `y`. Alternative <high>arguments allow for variations</high>, e.g., to account for unequal variances. ] .pull-right5[ ```r # 2-sample t-test assuming equal variance t.test(baselers$happiness, baselers$fitness, var.equal = TRUE) ``` ``` Two Sample t-test data: baselers$happiness and baselers$fitness t = 83, df = 19998, p-value <2e-16 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: 1.738 1.822 sample estimates: mean of x mean of y 6.905 5.125 ``` ] --- # `cor.test()` .pull-left45[ The <high>correlation test</high> compares the correlation of two variables against 0. Evaluate the correlation by providing <high>two numeric vectors</high> for the arguments `x`, and `y`. Alternative <high>arguments allow for variations</high>, e.g., to conduct the test using different correlation measures. ] .pull-right5[ ```r # correlation test cor.test(x = baselers$age, y = baselers$income) ``` ``` Pearson's product-moment correlation data: baselers$age and baselers$income t = 183, df = 8508, p-value <2e-16 alternative hypothesis: true correlation is not equal to 0 95 percent confidence interval: 0.8882 0.8968 sample estimates: cor 0.8926 ``` ] --- # `cor.test()` .pull-left45[ The <high>correlation test</high> compares the correlation of two variables against 0. Evaluate the correlation by providing <high>two numeric vectors</high> for the arguments `x`, and `y`. Alternative <high>arguments allow for variations</high>, e.g., to conduct the test using different correlation measures. ] .pull-right5[ ```r # correlation test cor.test(x = baselers$age, y = baselers$income, method = "spearman") ``` ``` Warning in cor.test.default(x = baselers$age, y = baselers$income, method = "spearman"): Cannot compute exact p-value with ties ``` ``` Spearman's rank correlation rho data: baselers$age and baselers$income S = 1.3e+10, p-value <2e-16 alternative hypothesis: true rho is not equal to 0 sample estimates: rho 0.8756 ``` ] --- # `chisq.test()` .pull-left45[ The <high>chi-square test</high> compares frequencies in (cross-) tables for equality in absolute or relative frequency. Evaluate frequencies by providing a <high>table</high>, <high>vectors</high> or <high>matrix</matrix> for the argument `x`. Alternative <high>arguments allow for variations</high>, e.g., to conduct the test using different coefficents. ] .pull-right5[ ```r # compute cross-table with table tab <- baselers %>% mutate(tattoo = tattoos == TRUE) %>% select(sex, tattoo) %>% table() # show table tab ``` ``` tattoo sex FALSE TRUE female 4703 297 male 4794 206 ``` ] --- # `chisq.test()` .pull-left45[ The <high>chi-square test</high> compares frequencies in (cross-) tables for equality in absolute or relative frequency. Evaluate frequencies by providing a <high>table</high>, <high>vectors</high> or <high>matrix</matrix> for the argument `x`. Alternative <high>arguments allow for variations</high>, e.g., to conduct the test using different coefficents. ] .pull-right5[ ```r # chi-square test chisq.test(tab) ``` ``` Pearson's Chi-squared test with Yates' continuity correction data: tab X-squared = 17, df = 1, p-value = 4e-05 ``` ] --- # `wilcox.test()` .pull-left45[ The <high>Wilcoxon test</high> compares one group' average ranks <high>versus reference</high> or <high>versus group</high>'s average rank. Compare average ranks of two groups by providing <high>two numeric vectors</high> for the arguments `x`, and `y`. Alternative <high>arguments allow for variations</high>. ] .pull-right5[ ```r # 2-sample wilcoxon rank test assuming equal variance wilcox.test(baselers$happiness, baselers$fitness) ``` ``` Wilcoxon rank sum test with continuity correction data: baselers$happiness and baselers$fitness W = 7.8e+07, p-value <2e-16 alternative hypothesis: true location shift is not equal to 0 ``` ] --- class: middle, center
Practical


VSL // The Food And Fashion Meet-Cute
* DVF has always been one of my most favorite brands, and her collaboration with Evian
today’s Very Short List:
food 15 Aug 2014
Dana Pollack is the creative force behind Dana’s Bakery
Subscribe
* I love how unexpected Kate Moss’ collaboration with Sushi Shop
* Two of my favorite things


{% extends 'explorer/base.html' %} {% block title %} | Police Detail{% endblock %} {% block content %} {% load static %}
Money used to enforce laws, arrest people, stand around at construction sites, etc.
Expenses
|_Citizen Support Services
|_Emergency Services
|_Police and Court Services
|_Toronto Police Services
Revenue
|_Provincial Transfers
|_Police Transfers
Staffing
|_Citizen Support Services
|_Emergency Services
|_Police and Court Services
|_Toronto Police Services
|_Uniformed Personnel
|_Civilian Personnel
416-808-8080


Goodday, Thanks for your response to my email. How are you today and business in your country? I am Mr. Chen Jiang, Bank Manager of a Bank in China. I am contacting you concerning a deceased customer that bears the same surname as you and an investment he placed under our banks management years ago. I would respectfully request that you keep the contents of this mail confidential and respect the integrity of the information you come by as a result of this mail. I contacted you independently of our investigation and no one is informed of this communication. I would like to intimate you with certain facts that I believe would be of interest to you. Please reply back. Chen Jiang.


Up comming...
Adventures
Lake Adventures
Crocodile Dundee
Close encounters
Hippo View
Close encounters
Hospitality
Taste some lake food
Escursions
Great experience with families and Friends
Special Treatment
Special Customer services
On-Board Snacks
As you go about your Adventures
Lake Views
Stop over sandy beaches
Hospitable Services
Hospitable services under able captain
Unique Birds
Opportunity for wide variety of Birds view
Unique Birds
Opportunity for wide variety of Birds view
Unique Birds
Opportunity for wide variety of Birds view


Antiviral challenges reported by Local Health Departments, by time period (n = 44). Proportion of LHDs reporting each antiviral challenge, by time period (April to June 2009 and June 2009 onward). Among those LHDs reporting a challenge, those issues reported to be "very challenging" by 40% or more respondents are marked by an asterisk.


Basic Overlay
Basic Overlay
Autofocus
button
Overlay 1
Overlay 2
Overlay 3
Overlay 1 with backdrop
Overlay 2 with backdrop
Overlay 3 with backdrop


See our Transparency page for details about our Board of Directors, operations, and our latest debt buys.
We have always said that Rolling Jubilee is not a solution to the debt crisis. We will continue using the funds collected by Rolling Jubilee to conduct debt purchases that highlight different aspects of the debt system. But as of December 31st, 2013, we have stopped accepting new donations.
We have launched the Debt Collective to move beyond individual tactics, and build a debt resistance movement. This is the second phase of our movement work. By banding together, we can strike a better deal for everyone.