WWE changes decision on Cain Velasquez's future
by Shiven SachdevaCain Velasquez failed to make a major impact at WWE Crown Jewel when the former UFC Champion lost to his rival Brock Lesnar in a matter of minutes.
Velasquez has not been seen on WWE television ever since his humiliating loss at the hands of The Beast, but there were reports that he will be teaming up with Rey Mysterio when WWE returned to Mexico City for a live event later this month.
Unfortunately, WWE scrapped that match. A match featuring the tag team of Rey Mysterio and Humberto Carillo was announced to take on Karl Anderson and Luke Gallows at the event. However, it looks like the company has changed its plans for Velasquez yet again as he has now replaced Rey Mysterio in the match.
Here is what Cagesideseats has stated:
Plans for Cain Velasquez on WWE’s Mexico City house show have changed again. He’s back to being listed for a match, teaming with Humberto Carrillo against Karl Anderson & Luke Gallows.
This will be Velasquez's second match for the company and hopefully the 37-year-old will fare better this time than he did in his debut. The fact that it is a tag team contest will certainly help Velasquez as he would have talented Superstars like Karl Anderson, Luke Gallows and Humberto Carillo to help him throughout the contest.
Also Read: Is Rey Mysterio responsible for a 10-year veteran asking to quit WWE?
Now you can rate WWE matches on Sportskeeda !


Particle
A Particle is an object that is emitted by an emitter.
Constructor Summary
| Public Constructor | ||
| public |
constructor(properties: object): * Constructs a Particle instance. |
Member Summary
| Public Members | ||
| public |
The particle's acceleration |
|
| public |
The particle's age |
|
| public |
The particle's alpha |
|
| public |
The particle's behaviours array |
|
| public |
The particle's body |
|
| public |
The particle's color store |
|
| public |
Determines if the particle is dead or not |
|
| public |
The particle's easing |
|
| public |
The particle's energy loss |
|
| public |
The particle's unique id |
|
| public |
The particle's life |
|
| public |
The particle's mass |
|
| public |
|
|
| public |
The particle's last position, velocity and acceleration |
|
| public |
The particle's position |
|
| public |
The particle's parent |
|
| public |
The particle's radius |
|
| public |
The particle's rotation |
|
| public |
The particle's scale |
|
| public |
Determines if the particle is sleeping or not |
|
| public |
The particle's transform collection |
|
| public |
Determines whether to use alpha or not |
|
| public |
Determines whether to use color or not |
|
| public |
The particle's velocity |
Method Summary
| Public Methods | ||
| public |
addBehaviour(behaviour: Behaviour): * Adds a behaviour to the particle. |
|
| public |
addBehaviours(behaviours: array<Behaviour>): * Adds multiple behaviours to the particle. |
|
| public |
clear(): * Clear's the particle's position, velocity, acceleration, color and rotation. |
|
| public |
destroy(): * Destroys the particle. |
|
| public |
Gets the particle's current direction. |
|
| public |
removeAllBehaviours(): * Removes all behaviours from the particle. |
|
| public |
removeBehaviour(behaviour: Behaviour): * Removes the behaviour from the particle. |
|
| public |
Updates the particle's properties by applying each behaviour to the particle. Will also update the particle's energy, unless it's age is greater than it's life in which case it will be destroyed. |
Public Constructors
public constructor(properties: object): * source
Constructs a Particle instance.
Params:
| Name | Type | Attribute | Description |
| properties | object | The properties to instantiate the particle with |
Return:
| * | void |
Return Properties:
| Name | Type | Attribute | Description |
| properties.life | number | The particle's life |
|
| properties.age | number | The particle's age |
|
| properties.energy | number | The particle's energy loss |
|
| properties.dead | boolean | Determines if the particle is dead or not |
|
| properties.sleep | boolean | Determines if the particle is sleeping or not |
|
| properties.target | object | The particle's target |
|
| properties.body | object | The particle's body |
|
| properties.mass | number | The particle's mass |
|
| properties.radius | number | The particle's radius |
|
| properties.alpha | number | The particle's alpha |
|
| properties.scale | number | The particle's scale |
|
| properties.rotation | number | The particle's rotation |
|
| properties.color | string | number | The particle's color |
|
| properties.easing | function | The particle's easing |
|
| properties.p | Vector3D | The particle's position |
|
| properties.v | Vector3D | The particle's velocity |
|
| properties.a | Vector3D | The particle's acceleration |
|
| properties.behaviours | array | The particle's behaviours array |
|
| properties.transform | object | The particle's transform collection |
Public Members
Public Methods
public addBehaviour(behaviour: Behaviour): * source
Adds a behaviour to the particle.
Params:
| Name | Type | Attribute | Description |
| behaviour | Behaviour | The behaviour to add to the particle |
Return:
| * | void |
public addBehaviours(behaviours: array<Behaviour>): * source
Adds multiple behaviours to the particle.
Params:
| Name | Type | Attribute | Description |
| behaviours | array<Behaviour> | An array of behaviours to add to the particle |
Return:
| * | void |
public clear(): * source
Clear's the particle's position, velocity, acceleration, color and rotation. Destroy's the particle's transform collection & removes all behaviours.
Return:
| * | void |
public removeBehaviour(behaviour: Behaviour): * source
Removes the behaviour from the particle.
Params:
| Name | Type | Attribute | Description |
| behaviour | Behaviour | The behaviour to remove from the particle |
Return:
| * | void |
public update(time: number, index: integer): * source
Updates the particle's properties by applying each behaviour to the particle. Will also update the particle's energy, unless it's age is greater than it's life in which case it will be destroyed.
Params:
| Name | Type | Attribute | Description |
| time | number | Integration time |
|
| index | integer | Particle index |
Return:
| * | void |


{{partial "head.html" .}}
{{partial "header.html" .}}
⇠ PREV
NEXT ⇢
{{partial "social-buttons.html" .}}
{{partial "newsletter.html" .}} {{partial "footer.html" .}}


Collapse: How Societies Choose to Fail or Survive
by Jared Diamond
A brilliant tome from the same bloke who penned Guns, Germs and Steel. This time he examines the flip side of the equation - what characteristics cause civilisations to fail? From the statues of Easter Island to the Mayan Ruins, the world is replete with the abandoned relics of cultures that collapsed. Diamond examines seven examples of societies whose members all died or dispersed, sometimes over a period of just a few years, leaving their hauntingly abandoned habitats, looking for the common factors which lead to their demise. The implications for our own culture are serious. Do we have more in common with these failed civilisations, or with the ones that exhibited long-term stability? Will our own skyscrapers one day stand as hauntingly abandoned monuments amongst jungle or desert? It's a serious message, and the immediate conclusion looks a little grim, as our rabid consumerism and resource consumption is anything but steady-state. However, Diamond finds a silver lining, presenting his conclusions as a message of hope. We are the first civilisation to have a global reach, and to have knowledge of ancient societies that have gone before, so while the stakes are higher than ever, so is our ability to forsee the consequences of our actions, and to change our course before it's too late.
Rating: 8/10 - a fascinating and important read.


The complainant was not impressed by the bumper's badinage and made sure to let him know with a few choice words of her own. [G|D]
The announcerblandly informed the audience that the brindle-colored puppy had won the competition in a landslide victory, eliciting a roar of approval from the crowd. [G|D]
The colonel was renowned for his bendy moves and abstinent lifestyle, leading to a great deal of admiration from both his peers and subordinates. [G|D]
The attorney was bent on getting his client the best possible outcome and was carefully angling for a favorable resolution in the cannery dispute. [G|D]


It happens to all developers.  You try using your editor of choice, only to find all your custom keybindings broken and the backspace not working.  The screen is too small, too flickery. Everything just feels wrong.
  I hate how it doesn't act exactly like my computer. I hate how nothing is where I expect it to be.
I've switched through a lot of different ways of doing things. The good bits stick, the less useful stuff gets forgotten. I definitely don't think I have my ideal environment set up, but there's definitely slow incremental progress.
Let's start with the simple stuff. Long development times require a comfortable setup. For me, this includes a dual display setup, an Microsoft ergo-keyboard, and a comfortable chair. You'd think this would be common sense, but I only got this setup after extremely sore forearms and a messed up back during my compilers project. Specifically, I use the Microsoft Natural Ergo 4000, and a beefy mesh backed chair with lumbar support I got from Costco.
 My requirements for computer hardware isn't about raw number-crunching power. Instead, I'd much rather have a computer that's fast enough and doesn't harress me. Noise is the big one for me. I loved my last desktop cause it had just the right amount of cooling with so little noise that I could sleep a meter away from it and not hear it being on.

I like OS X for it's unix internals and consistent UI and usage patterns. I can't use Windows because their shell isn't usable enough. I still like Linux for dev work, but I don't like it non-dev related activities: e.g. web surfing, chat, organization.
As you can see, it doesn't sound like I use that many differet tools. Just like my software, I like to keep my dev environment simple and really focus on a core set of functionality. When it comes down to it, all I need is something to write in, a browser to look up stuff, and a shell to glue everything together. More and more, I find myself looking for hosted solutions to local tools because it's just easier to maintain and more accessible.
Silent PC Review - is a fantastic site by Mike Chin with extensive tests about computer component noise and whole systems.


version 0.0.1
Icons are based on Arrow icon designed by Simple Icons from the Noun Project
Did you find a bug? Do you have an idea? Do you want to translate this extension to your language? Please contact me at GitHub issue tracker or send me an email.


Exercise Routine Maker
Create A Routine:
Title:
Exercise:
Sets:
Reps:
Exercise:
Sets:
Reps:
Exercise:
Sets:
Reps:
Exercise:
Sets:
Reps:
Exercise:
Sets:
Reps:
Exercise:
Sets:
Reps:
Choose a category:
Add New Exercise
Name:
Description:
Choose a category:
Filter:
all


Sporting support for big integers, whole-page contrast checks checks for accessibility, and a completely new implementation of a core Firefox feature: the ever-awesome URL bar. Dan Callahan also reports on updated CSS scroll-snapping and other features, DOM API updates, next steps in the WebRender implementation, and more.
Keeping the Web open is hard work. Sometimes browsers disagree on how to interpret web standards. Other times, browsers implement and ship their own ideas without going through the standards process. Even worse, some developers intentionally block certain browsers from their sites, regardless of whether or not those browsers would have worked.


public final class DictionaryLookup extends java.lang.Object implements IStemmer, java.lang.Iterable<WordData>
Important: finite state automatons in Jan Daciuk's implementation use bytes not unicode characters. Therefore objects of this class always have to be constructed with an encoding used to convert Java strings to byte arrays and the other way around. You can use UTF-8 encoding, as it should not conflict with any control sequences and separator characters.
| Constructor and Description |
|---|
DictionaryLookup(Dictionary dictionary)
Creates a new object of this class using the given FSA for word lookups
and encoding for converting characters to bytes.
|
| Modifier and Type | Method and Description |
|---|---|
static java.nio.ByteBuffer |
decodeBaseForm(java.nio.ByteBuffer output,
byte[] encoded,
int encodedLen,
java.nio.ByteBuffer inflectedForm,
DictionaryMetadata metadata)
Decode the base form of an inflected word and save its decoded form into
a byte buffer.
|
Dictionary |
getDictionary() |
char |
getSeparatorChar() |
java.util.Iterator<WordData> |
iterator()
Return an iterator over all
WordData entries available in the
embedded Dictionary . |
java.util.List<WordData> |
lookup(java.lang.CharSequence word)
Searches the automaton for a symbol sequence equal to
word ,
followed by a separator. |
public DictionaryLookup(Dictionary dictionary) throws java.lang.IllegalArgumentException
Creates a new object of this class using the given FSA for word lookups and encoding for converting characters to bytes.
java.lang.IllegalArgumentException
- if FSA's root node cannot be acquired (dictionary is empty).public java.util.List<WordData> lookup(java.lang.CharSequence word)
word
,
followed by a separator. The result is a stem (decompressed accordingly
to the dictionary's specification) and an optional tag data.public static java.nio.ByteBuffer decodeBaseForm(java.nio.ByteBuffer output, byte[] encoded, int encodedLen, java.nio.ByteBuffer inflectedForm, DictionaryMetadata metadata)
output
- The byte buffer to save the result to. A new buffer may be
allocated if the capacity of bb
is not large
enough to store the result. The buffer is not flipped upon
return.inflectedForm
- Inflected form's bytes (decoded properly).encoded
- Bytes of the encoded base form, starting at 0 index.encodedLen
- Length of the encode base form.bb
or a new buffer whose capacity is
large enough to store the output of the decoded data.public java.util.Iterator<WordData> iterator()
WordData
entries available in the
embedded Dictionary
.iterator
in interface java.lang.Iterable<WordData>
public Dictionary getDictionary()
Dictionary
used by this object.public char getSeparatorChar()
DictionaryMetadata.separator
and
may not be valid in the target encoding (although this is highly unlikely).Copyright © 2014. All Rights Reserved.


Array vs. Hashes
Ruby's arrays and hashes are indexed collections, they store collections of objects, which are accessible using a key. Both arrays and hashes grow as needed to hold new elements. I personally think it's more efficient to access array elements, but hashes provide more flexibility. Moreover, any particular array or hash can hold objects of differing types; you can have an array/hash containing an integer, a string, and a floating point number.
Array
An Array is just a list of items in order. Every slot in the list acts like a variable: you can see what object a particular slot points to, and you can make it point to a different object. You can make an array by using square brackets. In Ruby, the first value in an array has index 0. The size and length methods return the number of elements in an array. Negative index values count from the end of the array, so the last element of an array can also be accessed with an index of -1. In addition, Ruby's arrays are mutable, which means arrays are dynamically resizable, you can append elements to them and they grow as needed.
Hash
Hashes are similar to arrays in that they are indexed collection of object references. However, while you index arrays with integers, you can index a hash with objects of any types: strings, regular expressions, and so on. When you store a value in a hash, you actually supply two objects: the index, which normally called the key and the value. You can subsequently retrieve the value by indexing the hash with the same key. The values in a hash can be objects of any type. Hashes also have a default value that is returned when an attempt is made to access keys that do not exist in the hash. By default this value is nil.


The game ends once all of the beers are gone and someone takes a drink from the center bottle (they are the True American), or when you just want to stop
Do not drink and drive. Be responsible, and remember you don't have to play with alcohol
Stay safe on chairs and surfaces
Be loud
Don't worry too much about the rules, feel free to make your own
By playing, you agree to our terms of use


In today's world, having a basic understanding of web security is a must. There are simple ways to help
protect yourself while online. A few ways to do so:
Install Anti-Virus Software
Update Passwords Often
Visit Trusted Sites
Download Only From Trusted Sites
Keep Operating System Up To Date
You also may be surprised as to what a web app can "see" information wise.
The Navigator Object is used to locate information about the current browser window. It can be used
with all browsers. The following properties of the Navigator Object gathers the following information:
appName: Name of web browser
appVersion: Version of the web browser
geolocation: Access to the user's location
onLine: If the browser is connected to the internet
platform: Operating system current CPU is using
userAgent: Information stored including browser, platform name, and compatibility


3. Python: Advanced¶
3.1. Classes¶
Classes are like blueprints for creating objects.
Instances are what is built using the class.
The __init__()
function is found in all classes. It is used to assign values to object properties, or other operations when the object is being created.
self
is used to reference the current instance of the class, and is used to access variables that belong to the class. it doesn’t need to be named self
Classes can contain methods (in object functions)
class car:
def __init__(self, make, topspeed):
self.make = make
self.topspeed = topspeed
blueCar = car("Ford", "150")
print(blueCar.make)
print(blueCar.topspeed)
Ford
150
add a method to the class
class animal:
def __init__(self, name, weight, habitat):
self.name = name
self.weight = weight
self.habitat = habitat
def sayHello(self):
print("Hello I am a " + self.name)
tiger = animal("tiger", 200, "forest")
tiger.sayHello()
Hello I am a tiger
modifying object parameters is similar to normal python sytax
tiger.weight = 220
print(tiger.weight)
del tiger.habitat
print(tiger.__dict__) # quick investigation
220
{'name': 'tiger', 'weight': 220}
3.1.1. Attribute Visibility¶
public - no change
protected - 1 underscore prefix
private - 2 underscore prefix
class employee:
def __init__(self, name, salary, bonus):
self.name = name # public
self._salary = salary # protected
self.__bonus = bonus # private
jacob = employee("jacob", 30000, 2000)
print(jacob.name)
print(jacob._salary)
#print(jacob.__bonus) # would return an error
jacob
30000
3.1.2. Inheritance¶
Inheritance allows us to define a class that inherits methods and properties from another class.
parent and child classes will be used.
# Parent class
class animal:
def __init__(self, name, weight, habitat):
self.name = name
self.weight = weight
self.habitat = habitat
def sayHello(self):
print("Hello I am a " + self.name)
# Child class
class fish(animal):
pass # used for empty classes
shark = fish("Great White", "1000", "tropical ocean")
print(shark.name)
Great White
if we were to add the __init__()
function, the child overrides that of the parents class.
To keep it, add a call to the parents __init__()
directly or use super()
class animal:
def __init__(self, name, weight, habitat):
self.name = name
self.weight = weight
self.habitat = habitat
# explicitly calling
class bird(animal):
def __init__(self, name, weight, habitat):
animal.__init__(self, name, weight, habitat)
# using super()
class mammal(animal):
def __init__(self, name, weight, habitat):
super().__init__(name, weight, habitat)
eagle = bird("Golden", 2, "mountains")
print(eagle.__dict__)
bear = mammal("Grizzly", 500, "forest")
print(bear.__dict__)
{'name': 'Golden', 'weight': 2, 'habitat': 'mountains'}
{'name': 'Grizzly', 'weight': 500, 'habitat': 'forest'}
properties can also be added at the inheritance stage
class animal:
def __init__(self, name, weight, habitat):
self.name = name
self.weight = weight
self.habitat = habitat
class insect(animal):
def __init__(self, name, weight, habitat, colonySize):
super().__init__(name, weight, habitat)
self.colonySize = colonySize
self.exoskeleton = True # you can also add properties that aren't assigned
def printColonySize(self):
print("The ", self.name, " has a colony size of ", self.colonySize)
ant = insect("fire ant", 0.001, "tropical forest", 100000)
ant.printColonySize()
ant.__dict__
The fire ant has a colony size of 100000
{'name': 'fire ant',
'weight': 0.001,
'habitat': 'tropical forest',
'colonySize': 100000,
'exoskeleton': True}
3.1.3. Super - Extended¶
from - https://realpython.com/python-super/#what-can-super-do-for-you
super(Square, self).__init__()
the first element should be the same name as the new class
calling methods using super: super().area()
imagine that we don’t want to inherite a method eg. a cube should not be able to use area()
outside of the class.
In this instance we should modify the method by using the same name
# superclass - parent
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * self.length + 2 * self.width
# subclass - child
class Square(Rectangle):
def __init__(self, length):
super(Square, self).__init__(length, length)
class Cube(Square):
# modify an existing method
def area(self):
face_area = super().area() # using the area() method
return face_area * 6
# add a new method
def volume(self):
face_area = super().area()
return face_area * self.length
print("square")
squareObj = Square(4)
print(squareObj.area())
print("cube")
cubeObj = Cube(4)
print(cubeObj.area())
square
16
cube
96
3.1.4. Multiple inheritance¶
We must be careful when inheriting from multiple classes.
For example, the below will return an error
Method Resolution Order - is the order in which the methods are called.
__mro__
- provides info on the order
class Triangle:
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
# inherit from 2 classes
class RightPyramid(Triangle, Square):
def __init__(self, base, slant_height):
self.base = base
self.slant_height = slant_height
def area(self):
base_area = super().area
perimeter = super().perimeter
return 0.5 * perimeter * self.slant_height + base_area
pyramid = RightPyramid(2, 4)
# pyramid.area() # returns an error
# method resolution order
RightPyramid.__mro__
(__main__.RightPyramid,
__main__.Triangle,
__main__.Square,
__main__.Rectangle,
object)
note how the order is RightPyramid, Triangle, Square
We want to switch the order of Triangle and Square
class RightPyramidAlt(Square, Triangle):
def __init__(self, base, slant_height):
self.base = base
self.slant_height = slant_height
def area(self):
base_area = super().area
perimeter = super().perimeter
return 0.5 * perimeter * self.slant_height + base_area
RightPyramidAlt.__mro__
(__main__.RightPyramidAlt,
__main__.Square,
__main__.Rectangle,
__main__.Triangle,
object)
There are still some issues though:
two separate classes with the same method name and signature i.e. we are inheriting the
area()
method from Square and Triangethe new class doesn’t distinguish between Triange and Square objects very well. i.e. they don’t reference their superclass
Issue 1 resolution: name the method area()
differently eg. squ_area
and tri_area
Issue 2 resolution:
add
super().__init__()
to the.__init__()
in Rectange and Traingeallow
.__init__()
to take keyword dictionary
Alternatively, we could define a new class
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Square(Rectangle):
def __init__(self, length):
super().__init__(length, length)
# the new volume superclass
class Volume:
def volume(self):
return self.area() * self.height
# subclass
class Cube(Volume, Square):
def __init__(self, length):
super().__init__(length)
self.height = length
cube = Cube(2)
print(cube.volume())
8
3.1.5. Iterators¶
Is an object that can be iterated upon.
Specifically consitsting of the metods __iter__()
and __next__()
__iter__()
- returns the iterator object
__next__()
- returns the next item in the sequence
class numbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = numbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
1
2
3
to stop the iteration use StopIteration
class numbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 10:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = numbers()
myiter = iter(myclass)
for x in myiter:
print(x)
1
2
3
4
5
6
7
8
9
10
3.2. Class Concepts¶
classes have a number of key concepts
inheritance - creating a new class from a parent
encapsulation - being unable to effect the core data, unless a function specifices this
Polymorphism - to use a common interface for multiple forms
3.2.1. Inheritance¶
# Parent class
class animal:
def __init__(self, species, habitat, size):
self.species = species
self.habitat = habitat
self.size = size
def __str__(self):
return "I am a " + self.species
def sayHelloSpecies(self):
print("hello I am a " + self.species)
# child class
class fish(animal):
def __init__(self, species, habitat, size):
super().__init__(species, habitat, size)
def fishSpeak(self):
print("bubble bubble bubble")
skate = fish("skate", "north sea", 4)
skate.sayHelloSpecies()
skate.fishSpeak()
print(skate)
hello I am a skate
bubble bubble bubble
I am a skate
3.2.2. Encapsulation¶
note how the __maxprice
cannot be changed without the use of the specificed function as it is a private attribute
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("selling at price {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price - doesn't work! good
c.__maxprice = 9
c.sell()
# using setter function - works
c.setMaxPrice(1000)
c.sell()
selling at price 900
selling at price 900
selling at price 1000
3.2.3. Polymorphism¶
We can have multiple common classes, that can be used by other functions/class/etc.
the flying_test()
function uses the fly()
method in both the parrot and emu classes.
# parent
class animal:
def __init__(self, species, habitat, size):
self.species = species
self.habitat = habitat
self.size = size
class parrot(animal):
def __init__(self, species, habitat, size):
super().__init__(species, habitat, size)
def fly(self):
print("can fly")
class emu(animal):
def __init__(self, species, habitat, size):
super().__init__(species, habitat, size)
def fly(self):
print("cannot fly")
# define a common test
def flying_test(birdSpecies):
birdSpecies.fly()
# create object and run tests
polly = parrot("parrot", "tropics", 1)
paul = emu("emu", "tropics", 67)
flying_test(polly)
flying_test(paul)
can fly
cannot fly
3.3. Custom iterators¶
uses __iter__()
and __next__()
methods
__iter__()
- returns the iterator object
__next__()
- returns the next item in the sequence
it also requires use of StopIteration
class powerTwo:
def __init__(self, max=0):
self.max = max
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n <= self.max:
result = 2 ** self.n
self.n += 1
return result
else:
raise StopIteration
for i in powerTwo(3):
print(i)
1
2
4
8
3.4. Generators¶
Are a simple way of creating iterations
yield
is used at least once in a function. It has the same effect as the return
function, but pauses the functions state, allowing it to be iterable.
__iter__()
and __next__()
methods are automatically initiated
They are:
memory efficient
easier to understand
def powerTwoAlt(max = 0):
n = 0
while n <= max:
yield 2 ** n
n += 1
for i in powerTwoAlt(3):
print(i)
1
2
4
8
An alternative is in the style of a list comprehension, but uses ()
over []
# list comprehension
listPowerTwo = [2 ** x for x in range(0, 4)]
# generator
generatorPowerTwo = (2 ** x for x in range(0, 4))
print(listPowerTwo)
print(generatorPowerTwo)
for i in generatorPowerTwo:
print(i)
[1, 2, 4, 8]
<generator object <genexpr> at 0x102e48970>
1
2
4
8
3.5. Closure¶
if a function has a nested function with a value that must be referenced in the enclosed function then closure should be used.
It is the concept of returning the nested function
def makePrinter(msg):
def printer():
print(msg)
def doSomethingElse():
return 0
return printer
testPrint = makePrinter("hello there")
testPrint()
hello there
3.6. Decorators¶
adds functionallity to existing code - metacoding
decorators act as a wrapper
Divider example, we are aiming to add functionality to:
def divide(a, b):
return a / b
# the decorator function
def describeDivide(func):
def innerDivide(a, b):
print("I am going to divide ", a, " and ", b)
return func(a, b) # returns answer
return innerDivide # returns statement
@describeDivide
def divide(a, b):
return a / b
divide(10, 2)
I am going to divide 10 and 2
5.0
Decorators can be chained together, making the code more modular
in the below example:
args
is the tuple of positional arguments
kwargs
is the dictionary of keyword arguments
thus…
function(*args, **kwargs)
is th ultimate python wildcard
pseudocode for decorators
define function
define inner function allowing everything to pass
print
*
s /%
sLet the function run
print
*
s /%
sexit
def addStars(func):
def inner(*args, **kwargs):
print("*" * 30)
func(*args, **kwargs)
print("*" * 30)
return inner
def addPercentage(func):
def inner(*args, **kwargs):
print("%" * 30)
func(*args, **kwargs)
print("%" * 30)
return inner
# now chain them
@addStars
@addPercentage
def printBanner(msg):
print(msg)
printBanner("Hello I am a banner")
******************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Hello I am a banner
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
******************************
3.7. Getters, setters, and property
¶
When using getters and setters it is important to ensure we have backwards compatibility.
For example, assume we want to convert the below use getters and setters
class animal:
def __init__(self, species):
self.species = species
bear = animal("panda")
print(bear.species)
panda
class animal:
def __init__(self, species):
self.setSpecies(species)
def setSpecies(self, valueSpecies):
self.__species = valueSpecies # note the attribute is private
def getSpecies(self):
return self.__species
bear = animal("panda")
print(bear.getSpecies())
bear.setSpecies("grizzly")
print(bear.getSpecies())
panda
grizzly
So one issue we now face is that bear.species
has now been replaced with bear.getSpecies()
This is not backwards compatible…
This is where property
comes in!
property(fget=None, fset=None, fdel=None, doc=None)
fget
- get value attribute
fset
- set value attribute
fdel
- delete value attribute
doc
- string value
class animal:
def __init__(self, species):
self.setSpecies(species)
def setSpecies(self, valueSpecies):
self.__species = valueSpecies # note the attribute is private
def getSpecies(self):
return self.__species
# enable backwards compatibility
species = property(fget=getSpecies, fset=setSpecies)
bear = animal("panda")
print(bear.species)
bear.species = "grizzly"
print(bear.species)
panda
grizzly
3.7.1. @property
¶
A more pythonic way, is to use the @property
decorator.
Which has:
getter (fget)
- this is the default with @propertysetter (fset)
deleter (fdel)
mro
When using the same name eg. species
it is important that the visability is private or protected
N.B. how @property
is used for establising and getting and @funcName.setter
<EMAIL_ADDRESS>are used.
class animal:
def __init__(self, species):
self.species = species
@property
def species(self):
return self.__species
@species.setter
def species(self, newSpecies):
self.__species = newSpecies
@species.deleter
def species(self):
del self.__species
# initiate and get
pandaBear = animal("panda")
print(pandaBear.species)
# set
pandaBear.species = "grizzly"
print(pandaBear.species)
# delete
print(pandaBear.__dict__)
del pandaBear.species
print(pandaBear.__dict__)
panda
grizzly
{'_animal__species': 'grizzly'}
{}
3.8. Instant, Class, and Static Methods¶
Instant - a basic class method, takes self
and points to an instance of the class
Class - takes a class parameter cls
and points to the class when the method is called
Static - do not require a class instance creation, thus are not dependent on the state of the object.
class MyClass:
def method(self):
return 'instance method called', self
@classmethod
def classmethod(cls):
return 'class method called', cls
@staticmethod
def staticmethod():
return 'static method called'
obj = MyClass()
obj.method()
('instance method called', <__main__.MyClass at 0x102e254f0>)
obj.classmethod()
('class method called', __main__.MyClass)
obj.staticmethod()
'static method called'
3.8.1. Class methods: when to use¶
One example of usage is with factory functions. These are predefined methods that feed back into the class.
Pizza example.
Assume we have a class pizza
that allows users to define toppings. We also want to have some preset pizza types however.
class pizza:
def __init__(self, ingredients):
self.ingredients = ingredients
def __repr__(self):
return "Ingredients: {}".format(self.ingredients)
@classmethod
def jacobSpecial(cls):
return cls(['mozzarella', 'pineapple', 'sweetcorn', 'olives'])
# we can use the class as normal
standardPizza = pizza(['mozzarella'])
print(standardPizza)
# or we can call the classmethod
print(pizza.jacobSpecial())
# note how it exists in the new object
print(standardPizza.jacobSpecial())
Ingredients: ['mozzarella']
Ingredients: ['mozzarella', 'pineapple', 'sweetcorn', 'olives']
Ingredients: ['mozzarella', 'pineapple', 'sweetcorn', 'olives']
3.8.2. Static methods: when to use¶
Day to day, static methods aren’t used often.
A large benefit is improving code readability, signifying that the method does not depend on state of the object itself.
When then?:
grouping a utility function in a class (because it can’t go anywhere else)
having a single implementation
# 1. grouping a utility function in a class (because it can't go anywhere else)
class Dates:
def __init__(self, date):
self.__date = date
def getDate(self):
return self.__date
@staticmethod
def toDashDate(date):
return date.replace("/", "-")
dateObj = Dates("01/01/2020")
print(dateObj.getDate())
Dates.toDashDate("01/01/2020")
01/01/2020
'01-01-2020'
toDashDate
is completely independent of the class and object, but storing the method here makes sense.
# 2. having a single implementation
class Dates:
def __init__(self, date):
self.date = date
def getDate(self):
return self.date
@staticmethod
def toDashDate(date):
return date.replace("/", "-")
class DatesWithSlashes(Dates):
def getDate(self):
return Dates.toDashDate(self.date)
dateObj = Dates("01/01/2020")
print(dateObj.getDate())
dateFromDB = DatesWithSlashes("15/12/2016")
print(dateFromDB.getDate())
01/01/2020
15-12-2016
here we wouldn’t want DatesWithSlashes
to override the static utility
3.9. Magic Methods¶
3.10. ¶
__repr__()
is used to help with printing the object.
it gets called when you try to convert an object into a string through the various means that are available eg. print()
, str()
, etc.
3.11. Initiate and call method¶
sometimes you may want to call a method when the class is initiated
class animal:
def __init__(self, name):
self.name = name
self.sayName() # initiate here
def sayName(self):
print("I am a", self.name)
dog = animal("dog")
I am a dog
3.12. kwargs¶
Usage of **kwargs
with classes.
Allow the user to input as many fields as they wish.
class Employee:
def __init__(self, fullname, **kwargs):
fullname_array = fullname.split()
self.name = fullname_array[0]
self.lastname = fullname_array[1]
self.__dict__.update(kwargs)
jacob = Employee("Jacob Brown", height=180, mobile = "0123456789")
print(jacob.name)
print(jacob.lastname)
print(jacob.height)
print(jacob.__dict__)
Jacob
Brown
180
{'name': 'Jacob', 'lastname': 'Brown', 'height': 180, 'mobile': '0123456789'}


Michelle Obama
Résumé
— Girl from the South Side and former First Lady. Wife, mother, dog lover. Always hugger-in-chief. #IAmBecoming
Career and Life Before Becoming First Lady
-
2002
Began working for the University of Chicago Hospitals, first as executive director for community affairs.
-
1996
Served as the Associate Dean of Student Services at the University of Chicago, where she developed the University’s Community Service Center.
-
1993
Was named executive director for the Chicago branch of Public Allies, a leadership-training program for young adults.
-
1991
Held public sector positions in the Chicago city government as an Assistant to the Mayor and as Assistant Commissioner of Planning and Development
-
1988
Joined the Chicago office of the law firm Sidley Austin as a junior associate specializing in marketing and intellectual property.
Tenure as First Lady
-
2016
Accompanied her husband and children to Cuba in a trip that was seen by the administration as having the possibility of positively impacting relations between the country and America.
Endorsed Democratic nominee Hillary Clinton and made several high-profile speeches in favor of her.
-
2015
Traveled to Selma, Alabama, with her family to commemorate the fiftieth anniversary of the Selma to Montgomery marches.
Journeyed to Coachella Valley while coming to Los Angeles for that year's Special Olympics World Games.
-
2014
Joined the campaign to bring back school girls who had been kidnapped in Nigeria.
-
2013
Attended the 50th anniversary ceremony for the March on Washington at the Lincoln Memorial.
-
2012
Was awarded the Jerald Washington Memorial Founders' Award by the National Coalition for Homeless Veterans (NCHV).
-
2011
Co-founded the Joining Forces program to expand educational and employment options for veterans and to raise awareness about the difficulties plaguing military families.
-
2010
The first lady announced Let's Move! and President Barack Obama created the Task Force on Childhood Obesity to review all current programs and create a national plan for change.
Traveled to Mexico, her first solo visit to a nation. In Mexico, Obama spoke to students, encouraging them to take responsibility for their futures.
-
2009
Wored with local elementary school students to plant a 1,100-square-foot vegetable garden on the South Lawn of the White House./p>
Delivered the commencement speech at a graduating ceremony at UC Merced in Merced County, California.
Met with Queen Elizabeth II in Buckingham Palace, Obama embracing her before attending an event with world leaders.
-
2008
Became the first African American first lady upon Obama’s Election Day victory.
Became the third with a post-graduate degree.


Question
example: A * B + C becomes A B * C +
A * (B + C) becomes A B C + *
Solution
One of the main purpose of converting infix to postfix is to remove alll parentheses from the expression.
This is a very difficult question. The solution is:
Print operands as they arrive.
If the incoming symbol is ‘+’ or ‘-’ or ‘(’, push it on the stack.
If the incoming symbol is a ‘)’, pop the stack and print the operators until you see a ‘(’. Discard the pair of parentheses.
If the incoming symbol is ‘*’ or ‘/’, pop until we sees ‘+’ or ‘-’ or ‘(’ at top of the stack, then push the symbol onto the stack.
At the end of the expression, pop and print all operators on the stack. (No parentheses should remain.)
Code
public String solve(String infix) {
StringBuilder sb = new StringBuilder();
// get next operand or non-operand
// notice that operand is >=1 chars
int p = 0;
int len = infix.length();
Stack<Character> stack = new Stack<Character>();
while (p != len) {
if (isDigit(infix.charAt(p))) {
// if char at p is a digit
int q = p;
while (q != len && isDigit(infix.charAt(q))) {
q++;
}
// it is a number in the range [p, q-1]
sb.append(infix.substring(p, q) + " ");
p = q;
} else {
// if char at p is + - * / or ( )
char op = infix.charAt(p++);
if (op == ')') {
// pop until sees a '('
while (stack.peek() != '(') {
sb.append(stack.pop() + " ");
}
stack.pop();
} else if (op == '(' || op == '+' || op == '-') {
stack.push(op);
} else {
// if * or /
// pop until sees + or - or '('
while (!stack.isEmpty()) {
if (stack.peek() == '+' || stack.peek() == '-' || stack.peek() == '(') {
break;
}
sb.append(stack.pop() + " ");
}
stack.push(op);
}
}
}
// reach Eof, pop everything
while (!stack.isEmpty()) {
sb.append(stack.pop() + " ");
}
return sb.toString();
}


Responsive web design (RWD) is a web design approach aimed at crafting sites to provide an optimal viewing experience. It should provide easy reading and navigation with a minimum of resizing, panning, and scrolling—across a wide range of devices (from mobile phones to desktop computer monitors). 1 Responsive design is designing one web page to be easily viewable on multiple screen sizes.2To see responsive design, try resizing your browser smaller smaller and then do the opposite.
Liquid or fluid layout dimensions are defined in percentages, and as you might expect, this affords greater malleability and fluidity. In other words, by setting a percentage, you won’t have to think about device size or screen width, and consequently, you can find a reasonable solution for each case because your design’s size will adapt to the size of the device used. 3
We think that responsive design and fluid layouts are good practice because it makes your website more accessible to muiltiple devices. Statistics show that as of now 30% off all web-traffic comes from mobile devices. It is crucial for any site to cater to all forms of technology. 4
Responsive web design is the process of having websites render correctly no matter what type of device or viewport the user is on. I do like it because it is clear that we are moving more and more into a mobile world with a verity of devices to vew the web on. It is good practice to have a responsive web site because you can be confident that no matter where a user is coming from, they are going to have a good user experience.
The portability of smartphones is what really changed the web. No longer are people sitting at a desk when veiwing the web. People use the web for information when they are on the go and the internet has to make adjustments to that. Web practices will have to continually keep up with the newest techonlogy. As mobile matures and newer tech, like Google glass and wearable devices become more and more prominient.
I'm not sure how someone who is fully visually impaired is able to use the web. I think that partially impared people may have trouble seeing different colors and that when we are designing we should keep them in mind when picking what color schemes to use.
So far, I really like the use of semantic tags in HTML5 instead of endless divs. I feel that I have a basic understanding of most of the concepts, the biggest issue is getting them to stick and to develop a deeper understanding of them.
Implementing responsive web designs reassures developers that no matter the device being used, the contents will be displayed appropriately. This in return yields a good user experience. It’s a great concept and should be continuously applied.
The increasing usage of the web via smartphones and tablets has drastically affected web design. Developers have to make their websites not just accessible from a desktop, but now they have to consider accessibility for newer forms of technology such as smartphones and tablets. How contents appear on a desktop may look completely different on a smaller device, if the design is left as it is. As technology continues to expand, web design will also have to expand to make sure user experience is equal on all platforms of tech.
Visually impaired people are able to use the web despite their disability. They may heavily rely on their keyboard or software such as screen readers. Also, there are techniques that can be applied to make websites accessible to visually impaired people. I think we should definitely design and develop for this group of people because it’s not they don’t understand the content presented in a website; it’s just that they have difficulty seeing.
I think web design is such a powerful tool. It offers so many ways to modify the web to be more accessible in all forms of technology and to a greater audience.


{% load static %}
{% include "user_home/navbar_after_login.html" %}Here are some reasons why mutual funds hold a little edge over shares in terms of investment subject to individual rationality.
The interest in equities is soaring as the stock markets touch new highs. However, the big question remains whether young investors put money in stocks directly or through mutual funds. Here are some reasons why mutual funds hold a little edge over shares (stocks) in terms of investment subject to individual rationality.
-> Portfolio diversification
It reduces the risk of concentration in a particular stock as here the investment is made in various types of stocks, and such activity mitigates the losses if one or two stocks won’t work or incur losses. But in case of direct investment in stocks, one won’t invest in more than 10 stocks on an average, thereby entailing huge risks on his investment in case of volatility.
-> Professional Management
Mutual funds are professionally managed by a team of fund managers who do a lot of research and study various stocks and then identify and pick up such select stocks that are more profitable or those that signify growth in near future. They study the financial statements and other necessary information about the companies, and are well-versed with the risk management process. On the other hand, investing in stocks means an individual will have to study the stock market himself, and analyse the headwinds and tailwinds of such stocks. That is the reason why the task of identifying, analysing and evaluating risks isn’t a beginner’s cup of tea.
-> Disciplined Approach
A mutual fund follows a very systematic-cum-professional-cum-disciplined approach towards investing investors’ money, and then there are various types of funds here in the form of equity, debt, hybrid, gold, etc., with specific goals like retirement, children’s plans, etc. Depending upon your investment horizon, you can go for either liquid funds or corporate bond funds. You can also take the Systematic Investment Plan (SIP) route.
-> Tax Benefits
There are benefits in the form of deductions available under Section 80C of Income Tax Act when investing in certain schemes in mutual funds, for e.g., Equity-Linked Saving Scheme wherein deduction of up to Rs 1.5 lakh per year is available. No such benefit is available in direct stock investment and one has to pay certain charges like STT, dividend distribution tax, capital gains tax, brokerage charges. In mutual funds, one has to pay fund management fees. If an investor has time to study and research various stocks and its financial information, then he can create his own stock investment portfolio. But if we are not able to conduct adequate research or dedicate sufficient time in understanding and evaluating various stocks and their related news, and want our money to be looked after by fund managers professionally whose intent is to provide us a consistent return over a long term period specifically by investing in a diversified manner, then mutual fund is the best option for investing.
Disclaimer:The views expressed by experts on FINLER are of their own experience and interest. Finler.com advises user that they are not to be hled responsible for any losses
Go back to headlinesEvery expert was once a beginner. Want to start investing? Start with these fundamentals and follow them to START your investing journey.
Know moreLast updated 3 mins ago
Those who hold Titan shares in their portfolio should maintain trailing stop loss at ₹1670, say experts.
Know moreLast updated 3 mins ago
Stocks like Adani Total Gas vaulted 334 percent in the calendar year till June 11. Shares of Adani Transmission, Adani Enterprises and Adani Power have jumped between 200 percent and 265 percent in the same period
Know moreLast updated 3 mins ago


Chapter 6 Reporting data results #2-ng
Download a pdf of the lecture slides covering this topic.
6.1 Matrices
A matrix is like a data frame, but all the values in all columns must be of the same class (e.g., numeric, character).
R uses matrices a lot for its underlying math (e.g., for the linear algebra operations required for fitting regression models). R can do matrix operations quite quickly.
You can create a matrix with the matrix
function. Input a vector with the values to fill the matrix and ncol
to set the number of columns:
foo <- matrix(1:10, ncol = 5)
foo
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 3 5 7 9
## [2,] 2 4 6 8 10
By default, the matrix will fill up by column. You can fill it by row with the byrow
function:
foo <- matrix(1:10, ncol = 5, byrow = TRUE)
foo
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 2 3 4 5
## [2,] 6 7 8 9 10
In certain situations, you might want to work with a matrix instead of a data frame (for example, in cases where you were concerned about speed – a matrix is more memory efficient than the corresponding data frame). If you want to convert a data frame to a matrix, you can use the as.matrix
function:
foo <- data.frame(col_1 = 1:2, col_2 = 3:4,
col_3 = 5:6, col_4 = 7:8,
col_5 = 9:10)
(foo <- as.matrix(foo))
## col_1 col_2 col_3 col_4 col_5
## [1,] 1 3 5 7 9
## [2,] 2 4 6 8 10
You can index matrices with square brackets, just like data frames:
foo[1, 1:2]
## col_1 col_2
## 1 3
You cannot, however, use dplyr
functions with matrices:
foo %>% filter(col_1 == 1)
Error in UseMethod("filter_") :
no applicable method for 'filter_' applied to
an object of class "c('matrix', 'integer',
'numeric')"
All elements in a matrix must have the same class.
The matrix will default to make all values the most general class of any of the values, in any column. For example, if we replaced one numeric value with the character “a”, everything would turn into a character:
foo[1, 1] <- "a"
foo
## col_1 col_2 col_3 col_4 col_5
## [1,] "a" "3" "5" "7" "9"
## [2,] "2" "4" "6" "8" "10"
6.2 Regular expressions
For these examples, we’ll use some data on passengers of the Titanic. You can load this data using:
# install.packages("titanic")
library(titanic)
data("titanic_train")
We will be using the stringr
package:
library(stringr)
This data includes a column called “Name” with passenger names. This column is somewhat messy and includes several elements that we might want to separate (last name, first name, title). Here are the first few values of “Name”:
titanic_train %>% select(Name) %>% slice(1:3)
## # A tibble: 3 x 1
## Name
## <chr>
## 1 Braund, Mr. Owen Harris
## 2 Cumings, Mrs. John Bradley (Florence Briggs Thayer)
## 3 Heikkinen, Miss. Laina
We’ve already done some things to manipulate strings. For example, if we wanted to separate “Name” into last name and first name (including title), we could actually do that with the separate
function:
titanic_train %>%
select(Name) %>%
slice(1:3) %>%
separate(Name, c("last_name", "first_name"), sep = ", ")
## # A tibble: 3 x 2
## last_name first_name
## * <chr> <chr>
## 1 Braund Mr. Owen Harris
## 2 Cumings Mrs. John Bradley (Florence Briggs Thayer)
## 3 Heikkinen Miss. Laina
Notice that separate
is looking for a regular pattern (“,”) and then doing something based on the location of that pattern in each string (splitting the string).
There are a variety of functions in R that can perform manipulations based on finding regular patterns in character strings.
The str_detect
function will look through each element of a character vector for a designated pattern. If the pattern is there, it will return TRUE
, and otherwise FALSE
. The convention is:
## Generic code
str_detect(string = [vector you want to check],
pattern = [pattern you want to check for])
For example, to create a logical vector specifying which of the Titanic passenger names include “Mrs.”, you can call:
mrs <- str_detect(titanic_train$Name, "Mrs.")
head(mrs)
## [1] FALSE TRUE FALSE TRUE FALSE FALSE
The result is a logical vector, so str_detect
can be used in filter
to subset data to only rows where the passenger’s name includes “Mrs.”:
titanic_train %>%
filter(str_detect(Name, "Mrs.")) %>%
select(Name) %>%
slice(1:3)
## # A tibble: 3 x 1
## Name
## <chr>
## 1 Cumings, Mrs. John Bradley (Florence Briggs Thayer)
## 2 Futrelle, Mrs. Jacques Heath (Lily May Peel)
## 3 Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)
There is an older, base R function called grepl
that does something very similar (although note that the order of the arguments is reversed).
titanic_train %>%
filter(grepl("Mrs.", Name)) %>%
select(Name) %>%
slice(1:3)
## # A tibble: 3 x 1
## Name
## <chr>
## 1 Cumings, Mrs. John Bradley (Florence Briggs Thayer)
## 2 Futrelle, Mrs. Jacques Heath (Lily May Peel)
## 3 Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)
The str_extract
function can be used to extract a string (if it exists) from each value in a character vector. It follows similar conventions to str_detect
:
## Generic code
str_extract(string = [vector you want to check],
pattern = [pattern you want to check for])
For example, you might want to extract “Mrs.” if it exists in a passenger’s name:
titanic_train %>%
mutate(mrs = str_extract(Name, "Mrs.")) %>%
select(Name, mrs) %>%
slice(1:3)
## # A tibble: 3 x 2
## Name mrs
## <chr> <chr>
## 1 Braund, Mr. Owen Harris <NA>
## 2 Cumings, Mrs. John Bradley (Florence Briggs Thayer) Mrs.
## 3 Heikkinen, Miss. Laina <NA>
Notice that now we’re creating a new column (mrs
) that either has “Mrs.” (if there’s a match) or is missing (NA
) if there’s not a match.
For this first example, we were looking for an exact string (“Mrs”). However, you can use patterns that match a particular pattern, but not an exact string. For example, we could expand the regular expression to find “Mr.” or “Mrs.”:
titanic_train %>%
mutate(title = str_extract(Name, "Mr\\.|Mrs\\.")) %>%
select(Name, title) %>%
slice(1:3)
## # A tibble: 3 x 2
## Name title
## <chr> <chr>
## 1 Braund, Mr. Owen Harris Mr.
## 2 Cumings, Mrs. John Bradley (Florence Briggs Thayer) Mrs.
## 3 Heikkinen, Miss. Laina <NA>
Note that this pattern uses a special operator (|
) to find one pattern or another. Double backslashes (\\
) escape the special character “.”.
As a note, in regular expressions, all of the following characters are special characters that need to be escaped with backslashes if you want to use them literally:
. * + ^ ? $ \ | ( ) [ ] { }
Notice that “Mr.” and “Mrs.” both start with “Mr”, end with “.”, and may or may not have an “s” in between.
titanic_train %>%
mutate(title = str_extract(Name, "Mr(s)*\\.")) %>%
select(Name, title) %>%
slice(1:3)
## # A tibble: 3 x 2
## Name title
## <chr> <chr>
## 1 Braund, Mr. Owen Harris Mr.
## 2 Cumings, Mrs. John Bradley (Florence Briggs Thayer) Mrs.
## 3 Heikkinen, Miss. Laina <NA>
This pattern uses (s)*
to match zero or more “s”s at this spot in the pattern.
In the previous code, we found “Mr.” and “Mrs.”, but missed “Miss.”. We could tweak the pattern again to try to capture that, as well. For all three, we have the pattern that it starts with “M”, has some lowercase letters, and then ends with “.”.
titanic_train %>%
mutate(title = str_extract(Name, "M[a-z]+\\.")) %>%
select(Name, title) %>%
slice(1:3)
## # A tibble: 3 x 2
## Name title
## <chr> <chr>
## 1 Braund, Mr. Owen Harris Mr.
## 2 Cumings, Mrs. John Bradley (Florence Briggs Thayer) Mrs.
## 3 Heikkinen, Miss. Laina Miss.
The last pattern used [a-z]+
to match one or more lowercase letters. The [a-z]
is a character class.
You can also match digits ([0-9]
), uppercase letters ([A-Z]
), just some letters ([aeiou]
), etc.
You can negate a character class by starting it with ^
. For example, [^0-9]
will match anything that isn’t a digit.
Sometimes, you want to match a pattern, but then only subset a part of it. For example, each passenger seems to have a title (“Mr.”, “Mrs.”, etc.) that comes after “,” and before “.”. We can use this pattern to find the title, but then we get some extra stuff with the match:
titanic_train %>%
mutate(title = str_extract(Name, ",\\s[A-Za-z]*\\.\\s")) %>%
select(title) %>%
slice(1:3)
## # A tibble: 3 x 1
## title
## <chr>
## 1 , Mr.
## 2 , Mrs.
## 3 , Miss.
As a note, in this pattern, \\s
is used to match a space.
We are getting things like “, Mr.”, when we really want “Mr”. We can use the str_match
function to do this. We group what we want to extract from the pattern in parentheses, and then the function returns a matrix. The first column is the full pattern match, and each following column gives just what matches within the groups.
head(str_match(titanic_train$Name,
pattern = ",\\s([A-Za-z]*)\\.\\s"))
## [,1] [,2]
## [1,] ", Mr. " "Mr"
## [2,] ", Mrs. " "Mrs"
## [3,] ", Miss. " "Miss"
## [4,] ", Mrs. " "Mrs"
## [5,] ", Mr. " "Mr"
## [6,] ", Mr. " "Mr"
To get just the title, then, we can run:
titanic_train %>%
mutate(title =
str_match(Name, ",\\s([A-Za-z]*)\\.\\s")[ , 2]) %>%
select(Name, title) %>%
slice(1:3)
## # A tibble: 3 x 2
## Name title
## <chr> <chr>
## 1 Braund, Mr. Owen Harris Mr
## 2 Cumings, Mrs. John Bradley (Florence Briggs Thayer) Mrs
## 3 Heikkinen, Miss. Laina Miss
The [ , 2]
pulls out just the second column from the matrix returned by str_match
.
Here are some of the most common titles:
titanic_train %>%
mutate(title =
str_match(Name, ",\\s([A-Za-z]*)\\.\\s")[ , 2]) %>%
group_by(title) %>% summarize(n = n()) %>%
arrange(desc(n)) %>% slice(1:5)
## # A tibble: 5 x 2
## title n
## <chr> <int>
## 1 Mr 517
## 2 Miss 182
## 3 Mrs 125
## 4 Master 40
## 5 Dr 7
Here are a few other examples of regular expressions in action with this dataset.
 William Thornton II
## 2 Roebling, Mr. Washington Augustus II
Get names with “Andersen” or “Anderson” (alternatives in square brackets):
titanic_train %>%
filter(str_detect(Name, "Anders[eo]n")) %>%
select(Name)
## Name
## 1 Andersen-Jensen, Miss. Carla Christine Nielsine
## 2 Anderson, Mr. Harry
## 3 Walker, Mr. William Anderson
## 4 Olsvigen, Mr. Thor Anderson
## 5 Soholt, Mr. Peter Andreas Lauritz Andersen
Get names that start with (“^” outside of brackets) the letters “A” and “B”:
titanic_train %>%
filter(str_detect(Name, "^[AB]")) %>%
select(Name) %>%
slice(1:3)
## # A tibble: 3 x 1
## Name
## <chr>
## 1 Braund, Mr. Owen Harris
## 2 Allen, Mr. William Henry
## 3 Bonnell, Miss. Elizabeth
Get names that end with (“$”) the letter “b” (either lowercase or uppercase):
titanic_train %>%
filter(str_detect(Name, "[bB]$")) %>%
select(Name)
## Name
## 1 Emir, Mr. Farred Chehab
## 2 Goldschmidt, Mr. George B
## 3 Cook, Mr. Jacob
## 4 Pasic, Mr. Jakob
Some useful regular expression operators include:
| Operator | Meaning |
|---|---|
| . | Any character |
| * | Match 0 or more times (greedy) |
| *? | Match 0 or more times (non-greedy) |
| + | Match 1 or more times (greedy) |
| +? | Match 1 or more times (non-greedy) |
| ^ | Starts with (in brackets, negates) |
| $ | Ends with |
| […] | Character classes |
For more on these patterns, see:
- Help file for the
stringi-search-regex
function in thestringi
package (which should install when you installstringr
) - Introduction to stringr by Hadley Wickham
- Handling and Processing Strings in R by Gaston Sanchez (seven chapter ebook)
- http://gskinner.com/RegExr and http://www.txt2re.com: Interactive tools for helping you build regular expression pattern strings
6.3 Point maps
It is very easy now to create point maps in R based on longitude and latitude values of specific locations. You can use the map_data
function from the ggplot2
package to pull data for maps at different levels (“usa”, “state”, “world”, “county”).
The maps you pull using map_data
are just data to use to plot polygon shapes for areas like states and counties.
library(ggplot2)
us_map <- map_data("state")
head(us_map, 3)
## long lat group order region subregion
## 1 -87.46201 30.38968 1 1 alabama <NA>
## 2 -87.48493 30.37249 1 2 alabama <NA>
## 3 -87.52503 30.37249 1 3 alabama <NA>
You can add points to these based on latitude and longitude.
Mapping uses the long
and lat
columns from this data for location:
north_carolina <- us_map %>%
filter(region == "north carolina")
ggplot(north_carolina, aes(x = long, y = lat)) +
geom_point()
If you try to plot lines, however, you’ll have a problem:
carolinas <- us_map %>%
filter(str_detect(region, "carolina"))
ggplot(carolinas, aes(x = long, y = lat)) +
geom_path()
The group
column fixes this problem. It will plot a separate path or polygon for each separate group. For mapping, this gives separate groupings for mainland versus islands and for different states:
carolinas %>%
group_by(group) %>%
slice(1)
## # A tibble: 4 x 6
## # Groups: group [4]
## long lat group order region subregion
## <dbl> <dbl> <dbl> <int> <chr> <chr>
## 1 -75.89399 36.55471 38 9549 north carolina knotts
## 2 -78.55824 33.86753 39 9587 north carolina main
## 3 -76.00285 36.55471 40 10321 north carolina spit
## 4 -83.10753 34.99053 47 11441 south carolina <NA>
Using group = group
avoids the extra lines from the earlier map:
ggplot(carolinas, aes(x = long, y = lat,
group = group)) +
geom_path()
To plot filled regions, use geom_polygon
with fill = region
. Also, the “void” theme is often useful when mapping:
ggplot(carolinas, aes(x = long, y = lat,
group = group,
fill = region)) +
geom_polygon(color = "black") +
theme_void() +
coord_map()
Here is an example of plotting all of the US by state:
map_1 <- ggplot(us_map, aes(x = long, y = lat,
group = group)) +
geom_polygon(fill = "dodgerblue",
color = "white") +
theme_void() +
coord_map()
map_1
To add points to these maps, you can use geom_point
, again using longitude and latitude to define position.
Here I’ll use an example of data points related to the story told in last year’s “Serial” podcast.
serial <- read.csv("data/serial_map_data.csv")
head(serial, 3)
## x y Type Name Description
## 1 356 437 cell-site L688
## 2 740 360 cell-site L698
## 3 910 340 cell-site L654
David Robinson figured out a way to convert the x and y coordinates in this data to latitude and longitude coordinates. I’m also adding a column for whether of not the point is a cell tower.
serial <- serial %>%
mutate(long = -76.8854 + 0.00017022 * x,
lat = 39.23822 + 1.371014e-04 * y,
tower = Type == "cell-site")
serial[c(1:2, (nrow(serial) - 1):nrow(serial)),
c("Type", "Name", "long", "lat", "tower")]
## Type Name long lat tower
## 1 cell-site L688 -76.82480 39.29813 TRUE
## 2 cell-site L698 -76.75944 39.28758 TRUE
## 24 base-location Adnan's house -76.76284 39.30622 FALSE
## 25 base-location Jenn's house -76.72301 39.29443 FALSE
Now I can map just Baltimore City and Baltimore County in Maryland and add these points. I used map_data
to pull the “county” map and specified “region” as “maryland”, to limit the map just to Maryland counties.
baltimore <- map_data('county', region = 'maryland')
head(baltimore, 3)
## long lat group order region subregion
## 1 -78.64992 39.53982 1 1 maryland allegany
## 2 -78.70148 39.55128 1 2 maryland allegany
## 3 -78.74159 39.57420 1 3 maryland allegany
From that, I subset out rows where the subregion
column was “baltimore city” or “baltimore”.
baltimore <- subset(baltimore,
subregion %in% c("baltimore city",
"baltimore"))
head(baltimore, 3)
## long lat group order region subregion
## 114 -76.88521 39.35074 3 114 maryland baltimore
## 115 -76.89094 39.37939 3 115 maryland baltimore
## 116 -76.88521 39.40804 3 116 maryland baltimore
I used geom_point
to plot the points. ggplot
uses the group
column to group together counties, but we don’t need that in the points, so I needed to set group = NA
in the geom_point
statement. I put color = tower
inside the aes
statement so that the points would be one color for cell towers and another color for everything else.
balt_plot <- ggplot(baltimore,
aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "lightblue", color = "black") +
geom_point(data = serial, aes(x = long, y = lat,
group = NA,
color = tower)) +
theme_bw()
balt_plot +
coord_map()
6.4 Choropleth maps
There’s a fantastic new(-ish) package in R to plot choropleth maps. You could also plot choropleths using ggplot
and other mapping functions, but I would strongly recommend this new package if you’re mapping the US.
You will need to install and load the choroplethr
package in R to use the functions below.
# install.packages("choroplethr")
library(choroplethr)
# install.packages("choroplethrMaps")
library(choroplethrMaps)
At the most basic level, you can use this package to plot some data that comes automatically with the package (you’ll just need to load the data using the data
function). For example, if you wanted to plot state-by-state populations as of 2012, you could use:
data(df_pop_state)
map_3 <- state_choropleth(df_pop_state)
map_3
You can find out more about the df_pop_state
data if you type ?df_pop_state
. Notice that, for the data frame, the location is given in a column called region
and the population size to plot is in a column called value
.
head(df_pop_state, 3)
## region value
## 1 alabama 4777326
## 2 alaska 711139
## 3 arizona 6410979
You could use this function to create any state-level choropleth you wanted, as long as you could create a data frame with a column for states called region
and a column with the value you want to show called value
.
You can run similar functions at different spatial resolutions (for example, county or zip code):
data(df_pop_county)
head(df_pop_county, 3)
## region value
## 1 1001 54590
## 2 1003 183226
## 3 1005 27469
You can plot choropleths at this level, as well:
map_4 <- county_choropleth(df_pop_county)
map_4
You can even do this for countries of the world:
data(df_pop_country)
country_choropleth(df_pop_country)
You can zoom into states or counties. For example, to plot population by county in Colorado, you could run:
county_choropleth(df_pop_county, state_zoom = "colorado")
You can also use this package to map different tables from the US Census’ American Community Survey.
The package includes the choroplethr_acs()
function to do this, with an option for which level of map you want (map =
, choices are “state”, “country”, and “zip”). If you want to map at the state level, for example, use state_choroplethr_acs()
(other options are county level and zip code level).
These functions pull recent Census data directly from the US Census using its API, so they require you to get an API key, which you can get here.
Once you put in your request, they’ll email you your key. Once they give you your API key, you’ll need to install it on R:
library(acs)
api.key.install('[your census api key]');
You can pick from a large number of American Community Survey tables– see here for the list plus ID numbers. If the table has multiple columns, you will be prompted to select which one you want to plot.
For example, table B19301 gives per-capita income, so if you wanted to plot that, you could run:
county_choropleth_acs(tableId = "B19301",
state_zoom = c("wyoming",
"colorado"))
6.5 Google Maps API
The ggmap
package allows you to use tools from Google Maps directly from R.
## install.packages("ggmap")
library(ggmap)
This package uses the Google Maps API, so you should read their terms of service and make sure you follow them. In particular, you are limited to just a certain number of queries per time.
You can use the get_map
function to get maps for different locations. You can either use the longitude and latitude of the center point of the map, along with the zoom
option to say how much to zoom in (3: continent to 20: building) or you can use a character string to specify a location.
If you do the second, get_map
will actually use the Google Maps API to geocode the string to a latitude and longitude and then get the map (you can imagine that this is like searching in Google Maps in the search box for a location).
beijing <- get_map("Beijing", zoom = 12)
ggmap(beijing)
With this package, you can get maps from the following different sources:
- Google Maps
- OpenStreetMap
- Stamen Maps
- CloudMade Maps (You may need a separate API key for this)
Here are different examples of Beijing using different map sources. (Also, note that I’m using the option extent = "device"
to fill up the whole plot are with the map, instead of including axis labels and titles.)
beijing_a <- get_map("Beijing", zoom = 12,
source = "stamen", maptype = "toner")
a <- ggmap(beijing_a, extent = "device")
beijing_b <- get_map("Beijing", zoom = 12,
source = "stamen", maptype = "watercolor")
b <- ggmap(beijing_b, extent = "device")
beijing_c <- get_map("Beijing", zoom = 12,
source = "google", maptype = "hybrid")
c <- ggmap(beijing_c, extent = "device")
grid.arrange(a, b, c, nrow = 1)
As with the maps from ggplot2
, you can add points to these maps:
serial_phone <- read.csv("data/serial_phone_data.csv") %>%
mutate(Cell_Site = substring(Cell_Site, 1, 4),
Call_Time = as.POSIXct(Call_Time, format = "%d/%m/%y %H:%M",
tz = "EST")) %>%
left_join(serial, by = c("Cell_Site" = "Name")) %>%
select(Person_Called, Call_Time, Duration, long, lat) %>%
filter(!(Person_Called %in% c("incoming", "# + Adnan cell"))) %>%
arrange(Call_Time)
serial_map <- get_map(c(-76.7, 39.3), zoom = 12,
source = "stamen",
maptype = "toner")
serial_map <- ggmap(serial_map, extent = "device") +
geom_point(data = serial_phone,
aes(x = long, y = lat),
color = "red", size = 3,
alpha = 0.4) +
geom_point(data = subset(serial,
Type != "cell-site"),
aes(x = long, y = lat),
color = "darkgoldenrod1",
size = 2)
You can also use the Google Maps API, through the geocode
function, to get the latitude and longitude of specific locations. Basically, if the string would give you the right location if you typed it in Google Maps, geocode
should be able to geocode it.
For example, you can get the location of CSU:
geocode("Colorado State University")
You can also get a location by address:
geocode("1 First St NE, Washington, DC")
You can get distances, too, using the mapdist
function with two locations. This will give you distance and also time.
mapdist("Fort Collins CO",
"1 First St NE, Washington, DC") %>%
select(from, miles, hours)
6.6 String operations
The str_trim
function from the stringr
package allows you to trim leading and trailing white space:
with_spaces <- c(" a ", " bob", " gamma")
with_spaces
## [1] " a " " bob" " gamma"
str_trim(with_spaces)
## [1] "a" "bob" "gamma"
This is rarer, but if you ever want to, you can add leading and/or trailing white space to elements of a character vector with str_pad
from the stringr
package.
There are also functions to change a full character string to uppercase, lowercase, or title case:
titanic_train$Name[1]
## [1] "Braund, Mr. Owen Harris"
str_to_upper(titanic_train$Name[1])
## [1] "BRAUND, MR. OWEN HARRIS"
str_to_lower(titanic_train$Name[1])
## [1] "braund, mr. owen harris"
str_to_title(str_to_lower(titanic_train$Name[1]))
## [1] "Braund, Mr. Owen Harris"
6.7 In-course exercise
This exercise will continue using the Fatality Analysis Reporting System (FARS) data we started using last week.
6.7.1 Using a function and purrr
to create state-specific plots
The first part of this week’s in-course exercise continues last week’s exercise. You will write a function to create state-specific plots from this data, then use it to create plots for the states of Colorado, Texas, California, and New York.
- The FARS data includes a column called
STATE
, but it gives state as a one- or two-digit code, rather than by name. These codes are the state Federal Information Processing Standard (FIPS) codes. A dataset with state names and FIPS codes is available at http://www2.census.gov/geo/docs/reference/state.txt. Read that data into an R object calledstate_fips
and clean it so the first few lines look like this (hint: to change thestate
column to an integer class, you can use the functionas.integer
):
## # A tibble: 5 x 2
## state state_name
## <int> <chr>
## 1 1 Alabama
## 2 2 Alaska
## 3 4 Arizona
## 4 5 Arkansas
## 5 6 California
- Read the 2015 FARS data into an R object named
accident
. Use all the date and time information to create a column nameddate
with the date and time of the accident. Include information on whether the accident was related to drunk driving (FALSE if there were 0 drunk drivers, TRUE if there were one or more), and create columns that gives whether the accident was during the day (7 AM to 7 PM) or not as well as the month of the accident (for this last column, you can either retain it from the original data or recalculate it based on the newdate
variable). Filter out any values where the date-time does not render (i.e.,date
is a missing value). The first few rows of the cleaned dataframe should look like this:
## # A tibble: 5 x 5
## state date drunk_dr daytime month
## <int> <dttm> <lgl> <lgl> <dbl>
## 1 1 2015-01-01 02:40:00 TRUE FALSE 1
## 2 1 2015-01-01 22:13:00 FALSE FALSE 1
## 3 1 2015-01-01 01:25:00 TRUE FALSE 1
## 4 1 2015-01-04 00:57:00 TRUE FALSE 1
## 5 1 2015-01-07 07:09:00 FALSE TRUE 1
- Join the information from
state_fips
into theaccident
dataframe. There may be a few locations in thestate_fips
dataframe that are not included in theaccident
dataframe (e.g., Virgin Islands), so when you join keep all observations inaccident
but only the observations instate_fips
that match at least one row ofaccident
. The first few rows of the joined dataset should look like this:
## # A tibble: 5 x 6
## state date drunk_dr daytime month state_name
## <int> <dttm> <lgl> <lgl> <dbl> <chr>
## 1 1 2015-01-01 02:40:00 TRUE FALSE 1 Alabama
## 2 1 2015-01-01 22:13:00 FALSE FALSE 1 Alabama
## 3 1 2015-01-01 01:25:00 TRUE FALSE 1 Alabama
## 4 1 2015-01-04 00:57:00 TRUE FALSE 1 Alabama
## 5 1 2015-01-07 07:09:00 FALSE TRUE 1 Alabama
- Summarize the data to get the total number of accidents in Colorado in each month, separated by (1) daytime and nighttime and (2) related or unrelated to drunk driving (in other words, in January, how many daytime accidents were there that were unrelated to drunk driving? How many nighttime accidents that were unrelated to drunk driving? etc.). The summarized data should look like this:
## # A tibble: 48 x 4
## # Groups: daytime, month [?]
## daytime month drunk_dr accidents
## <lgl> <dbl> <lgl> <int>
## 1 FALSE 1 FALSE 9
## 2 FALSE 1 TRUE 6
## 3 FALSE 2 FALSE 6
## 4 FALSE 2 TRUE 3
## 5 FALSE 3 FALSE 5
## 6 FALSE 3 TRUE 11
## 7 FALSE 4 FALSE 11
## 8 FALSE 4 TRUE 11
## 9 FALSE 5 FALSE 9
## 10 FALSE 5 TRUE 6
## # ... with 38 more rows
- Write a function that inputs a dataframe (
df
) and outputs this type of summary dataframe (like the one just created for Colorado) for whatever data is in the input dataframe.  How does the new function fit in? (Note: We could have achieved the same thing with basic
dplyr
code, but this framework will allow you to ultimately do a lot more than you can withdplyr
.)
library(purrr)
accident %>%
filter(state_name %in% c("Colorado", "Texas", "California", "New York")) %>%
group_by(state_name) %>%
nest() %>%
mutate(summary = purrr::map(data, summarize_fars)) %>%
select(-data) %>%
unnest()
- Write code to create boxplots for Colorado of the distribution of total accidents within each month. Create separate boxplots for daytime and nighttime accidents, and facet by whether the accident was related to drunk driving. The plot should look like the plot below.
- Now write a function called
plot_fars
to create a plot like the one you just made for Colorado for any dataframe with the format ofaccident
(i.e., same number, types, and names of columns). Test it on subsets of the data for several states (Colorado, Texas, California, and New York). (Hint: To get a function to print out a plot created with ggplot, you will need to explicitly print the output from your function. See the examples of using the function below.)
 What happens when you run this code?
library(cowplot)
plot_grid(plotlist = state_plots[["plots"]],
ncol = 2, labels = "AUTO")
<IP_ADDRESS> Example R code
Here is the code to read the dataset with state names and FIPS codes at http://www2.census.gov/geo/docs/reference/state.txt into an R object called state_fips
and clean it so the first few lines:
## # A tibble: 5 x 2
## state state_name
## <int> <chr>
## 1 1 Alabama
## 2 2 Alaska
## 3 4 Arizona
## 4 5 Arkansas
## 5 6 California
Note that you can read this file directly from the website using read_delim
.
Read the 2015 FARS data into an R object named accident
. Use all the date and time information to create a column named date
with the date and time of the accident. Include information on whether the accident was related to drunk driving (FALSE if there were 0 drunk drivers, TRUE if there were one or more), and create columns that gives whether the accident was during the day (7 AM to 7 PM) or not as well as the month of the accident (for this last column, you can either retain it from the original data or recalculate it based on the new date
variable). Filter out any values where the date-time does not render (i.e., date
is a missing value). You can use the following code to do all this:
## # A tibble: 5 x 5
## state date drunk_dr daytime month
## <int> <dttm> <lgl> <lgl> <dbl>
## 1 1 2015-01-01 02:40:00 TRUE FALSE 1
## 2 1 2015-01-01 22:13:00 FALSE FALSE 1
## 3 1 2015-01-01 01:25:00 TRUE FALSE 1
## 4 1 2015-01-04 00:57:00 TRUE FALSE 1
## 5 1 2015-01-07 07:09:00 FALSE TRUE 1
A few notes:
- Notice that
select
is using the:
operator to pick several columns in a row. - Some of the column names in all caps are changed to lower case to make them easier to work with.
- The
DAY_WEEK
column is in the middle of other date columns, but if you remove it, you can useunite
with:
to join together all the date-time columns and then uselubridate
to change this column into the right class. - A logical operator is used inside a
mutate
call to create a column of whether the accident involved drunk driving (one or more drunk drivers involved) - The
hour
function fromlubridate
is used to check if the time of the accident falls in “daytime” or not - Some of the accidents are missing some date information. A
filter
is used to filter that out.
Join the information from state_fips
into the accident
dataframe. There may be a few locations in the state_fips
dataframe that are not included in the accident
dataframe (e.g., Virgin Islands), so when you join keep all observations in accident
but only the observations in state_fips
that match at least one row of accident
. You can use the following code for this:
## # A tibble: 5 x 6
## state date drunk_dr daytime month state_name
## <int> <dttm> <lgl> <lgl> <dbl> <chr>
## 1 1 2015-01-01 02:40:00 TRUE FALSE 1 Alabama
## 2 1 2015-01-01 22:13:00 FALSE FALSE 1 Alabama
## 3 1 2015-01-01 01:25:00 TRUE FALSE 1 Alabama
## 4 1 2015-01-04 00:57:00 TRUE FALSE 1 Alabama
## 5 1 2015-01-07 07:09:00 FALSE TRUE 1 Alabama
Summarize the data to get the total number of accidents, separated by (1) daytime and nighttime and (2) related or unrelated to drunk driving, in each month (in other words, in January, how many daytime accidents were there that were unrelated to drunk driving? How many nighttime accidents that were unrelated to drunk driving? etc.). You can do that with this code:
accident %>%
filter(state_name == "Colorado") %>%
group_by(daytime, month, drunk_dr) %>%
summarize(accidents = n())
## # A tibble: 48 x 4
## # Groups: daytime, month [?]
## daytime month drunk_dr accidents
## <lgl> <dbl> <lgl> <int>
## 1 FALSE 1 FALSE 9
## 2 FALSE 1 TRUE 6
## 3 FALSE 2 FALSE 6
## 4 FALSE 2 TRUE 3
## 5 FALSE 3 FALSE 5
## 6 FALSE 3 TRUE 11
## 7 FALSE 4 FALSE 11
## 8 FALSE 4 TRUE 11
## 9 FALSE 5 FALSE 9
## 10 FALSE 5 TRUE 6
## # ... with 38 more rows
As a note, you may want to create a table (for example, for a report) from the data at this stage. You could use unite
then spread
to do this pretty easily:
accident %>%
filter(state_name == "Colorado") %>%
mutate(daytime = factor(daytime, labels = c("Nighttime", "Daytime")),
drunk_dr = factor(drunk_dr,
labels = c("Not drunk driving", "Drunk driving"))) %>%
group_by(daytime, month, drunk_dr) %>%
summarize(accidents = n()) %>%
ungroup() %>%
unite(category, daytime, drunk_dr, sep = " / ") %>%
spread(key = category, value = accidents) %>%
knitr::kable()
| month | Daytime / Drunk driving | Daytime / Not drunk driving | Nighttime / Drunk driving | Nighttime / Not drunk driving |
|---|---|---|---|---|
| 1 | 7 | 20 | 6 | 9 |
| 2 | 1 | 22 | 3 | 6 |
| 3 | 7 | 12 | 11 | 5 |
| 4 | 6 | 19 | 11 | 11 |
| 5 | 4 | 20 | 6 | 9 |
| 6 | 8 | 22 | 8 | 5 |
| 7 | 4 | 26 | 12 | 6 |
| 8 | 9 | 14 | 13 | 9 |
| 9 | 10 | 38 | 9 | 14 |
| 10 | 5 | 26 | 8 | 5 |
| 11 | 1 | 13 | 10 | 8 |
| 12 | 3 | 15 | 5 | 5 |
Write a function that inputs a dataframe (df
) and outputs this type of summary dataframe (like the one just created for Colorado). You can do that with the following code. Note that, because it inputs a dataframe and outputs a dataframe, you can include it in a pipeline.
summarize_fars <- function(df){
df %>%
group_by(daytime, month, drunk_dr) %>%
summarize(accidents = n())
}
Once you’ve written the function, see if you can figure out what the following code does. This code limits the data to data from four states and then applies the summarize_fars
function that you just wrote to the subset of data from each state. Finally, since we nest
to do that, the pipeline includes some lines to unnest
the data to get back to an unnested data frame:
library(purrr)
accident %>%
filter(state_name %in% c("Colorado", "Texas", "California", "New York")) %>%
group_by(state_name) %>%
nest() %>%
mutate(summary = purrr::map(data, summarize_fars)) %>%
select(-data) %>%
unnest()
Write code to create boxplots for Colorado of the distribution of total accidents within each month. Create separate boxplots for daytime and nighttime accidents, and facet by whether the accident was related to drunk driving. You can do that with this code:
accident %>%
filter(state_name == "Colorado") %>%
mutate(drunk_dr = factor(drunk_dr, labels = c("Unrelated to\ndrunk driving",
"Related to\ndrunk driving")),
daytime = factor(daytime, labels = c("Nighttime", "Daytime"))) %>%
group_by(daytime, month, drunk_dr) %>%
summarize(accidents = n()) %>%
ggplot(aes(x = daytime, y = accidents, group = daytime)) +
geom_boxplot() +
facet_wrap(~ drunk_dr, ncol = 2) +
xlab("Time of day") + ylab("# of monthly accidents") +
ggtitle(paste("Fatal accidents in", "Colorado", "in 2015"))
Now write a function called plot_fars
to create a plot like the one you just made for Colorado for any dataframe with the format of accident
(i.e., same number, types, and names of columns). Test it on subsets of the data for several states (Colorado, Texas, California, and New York). (Hint: To get a function to print out a plot created with ggplot, you must explicitly print the plot object. For example, you could assign the plot to fars_plot
, and then you would run print(fars_plot)
within your loop as the last step.)
Notice how similar this function is to the code you wrote in the previous step.
Once you have written this function, what happens when you run the following code? The following code applies this function to the subset of data from each of four states. The output (state_plots
) is a nested dataframe, where the new plots
column is a list of ggplot
objects. If you run print
on this list, it will print each of these plots out separately (use the arrow buttons in the “Plots” Pane in RStudio to browse through these plots).
library(purrr)
state_plots <- accident %>%
filter(state_name %in% c("Colorado", "Texas", "California", "New York")) %>%
group_by(state_name) %>%
nest() %>%
mutate(plots = purrr::map(data, plot_fars)) %>%
select(state_name, plots)
class(state_plots)
class(state_plots[["plots"]])
class(state_plots[["plots"]][[1]])
state_plots[["plots"]][[1]]$plot
Install the cowplot
package (this is a ggplot2
extension) and then try running the following code. What happens? The plot_grid
function, if you input a list with ggplot
objects using the plotlist
argument, will print all the plots out on the same page.
library(cowplot)
library(gtable)
plot_grid(plotlist = state_plots[["plots"]],
ncol = 2, labels = "AUTO")
6.7.2 First steps in mapping
Next, you’ll try out some mapping with this FARS data.
- Read in and clean up the FARS data and save it to an R object called
accident
. Theaccident
data frame should include location (longitude and latitude), state, and whether the accident involved drunk driving. Once you’re done cleaning, the dataset should look like this:
## # A tibble: 5 x 4
## lat long drunk_dr state_name
## <dbl> <dbl> <lgl> <chr>
## 1 33.87865 -87.32533 TRUE Alabama
## 2 34.91044 -86.90871 FALSE Alabama
## 3 32.14201 -85.75846 TRUE Alabama
## 4 31.43981 -85.51030 TRUE Alabama
## 5 31.31933 -85.51510 FALSE Alabama
- Next, create another R object with state-specific summaries. This object should be a data frame called
state_summaries
that gives the total number of fatal accidents in each state and the percent of all fatal accidents related to drunk driving in each state. Thestate_summaries
data frame should look like this when you are done cleaning:
## # A tibble: 5 x 3
## state_name n perc_drunk_dr
## <chr> <int> <dbl>
## 1 Alabama 783 27.45849
## 2 Alaska 60 40.00000
## 3 Arizona 810 28.76543
## 4 Arkansas 472 25.84746
## 5 California 2925 24.54701
- Create the following state-level choropleths of number of fatal accidents in 2015 in each state and of the percent of fatal accidents linked to drunk driving in each state. The quickest way to do this is with the
choroplethr
package.
Now, you will be using the latitude and longitude of each accident to plot accident locations within a state. Check if the columns for latitude and longitude need more cleaning (spoiler alert— they do). Filter out any values that could not reasonably be within the 50 U.S. states and D.C.
Map the locations of fatal accidents in Texas in 2015 on top of a Google Map base map that shows major roads. An example map is shown below. (Hint: Use the
get_map
andggmap
functions for this part.)Create a function that will take three inputs:
datafr
, a data frame likeaccident
with fatal accident data;which_state
, a state name; anddrunk_dr
, a logical value (TRUE / FALSE) specifying whether to create separate maps for accidents that were and were not linked to drunk driving. This function should output a map (or two maps ifdrunk_dr
is set to TRUE) with points for all fatal accidents in the state. Usemap_data
and create the map yourself, rather than usingchoroplethr
for this question. Examples of calling this function are shown below.
map_fatal_accidents(accident, which_state = "Colorado")
accident %>%
map_fatal_accidents(which_state = "Texas")
accident %>%
map_fatal_accidents(which_state = "Colorado", drunk_dr = TRUE)
map_fatal_accidents(accident, which_state = "Texas",
drunk_dr = TRUE)


Location:
NITPY is situated in Karaikal. NITPY is located on the National Highway NH32 at about 58 Kms from Chidambaram towards South. The Institute is located about 8.5 Kms from Karaikal Bus stand on the Nagapattinam to Chennai Highway (NH 32). Karaikal Railway Station is about 11 Kms from NITPY.
  Bus Route Map
   Chennai - Puducherry - Chidambaram - Sirkazhi - Tharangambadi - Thiruvettakudy Arch -    Karaikal
  Trichy - Thanjavur - Kumbakonam - Karaikal - Thiruvettakudy
  Mayiladuthurai - Thiruvettakudy Arch - Karaikal


"The wordld is vampire sent to drain"
SAVE
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like


Wenwei Weng's Blog
A small corner to record learning journey and share with others!
-
ARM CPU overview
ARM is coming very strong and making dramtic change to the landscape of computing industry. It is impacting to various fields like microcontroller, embedded system, mobile internet, server market. In this post, I will share what I learned about ARM CPU. ARM is a family of instruction set architectures for...
-
Low Cost Home VOIP phone system set up
Internet is changing many aspects of people’s life. One of very initial goal of internet was to make long distance voice call very cheap as stated by Cisco CEO John chambers in 1990s. It is very much in reality now. Still, home phone /landline can be pretty expensive. Thanks for...
-
GIT proxy set up
GIT is becoming very popular as SCM due to its simplicity and flexibity. Often software developers encounter proxy issue when the server sit behind firewall. There are three protocols git can use to clone a repository: http, git and ssh. GIT clone example: git clone http://git.denx.de/u-boot.git git clone git://git.denx.de/u-boot.git git...
-
My favorite Linus Torvalds' quotes
I love Linux, and pay a lot respect to the initial creator Linus Torvalds. He seems full of wisdom and really like his following quotes: I think of myself as an engineer, not as a visionary or ‘big thinker.’ I don’t have any lofty goals. I’m generally a very pragmatic...
-
Building linux system (kernel + root file system) from scratch
I always feel good if I can build something from scratch and works! I love Linux. I will show how to build a Linux system with bleeding edge linux kernel and latest stable busybox release, and run linux in [qemu] (http://www.qemu.org/). Host machine I have a x86 based ubuntu 12.04...


--- layout: archive permalink: /categories/ title: "Posts by Category" id: "pages/categories" --- {% include base_path %} {% include group-by-array collection=site.posts field="categories" %} {% if group_names %}
{% for category in group_names %} {% assign posts = group_items[forloop.index0] %}


A simple android plugin module that allows Unity to request permissions at runtime.
I developed this as a solution to a problem that was recurring on most Unity projects I encountered, the fact that native android functions as basic as requesting permissions at runtime was not possible from the C#-Unity side.
Any solutions like this on the Unity store exist bundled in unnecessary packages full of unwanted plugins that bloat the project you work in, as well costing a large sum. So I wanted to make an extremely lightweight plugin that can live in each project I work in that requires this functionality.
The project contains the Android Studio native code in Java as well as the Unity and C# source files, documented and explained in examples, to help get you set up. If the plugin is all you are after, the unitypackage is included as well.
Main tools used include the following;
Android Permission Granter For Unity


An interface to the yacas computer algebra system.
| Version: | 0.3-4 |
| Depends: | R (≥ 3.3.0) |
| Imports: | Rcpp (≥ 0.12.0), xml2, stats |
| LinkingTo: | Rcpp |
| Suggests: | testthat (≥ 0.9.0), devtools (≥ 1.11.0) |
| Published: | 2018-09-29 |
| Author: | Rob Goedman, Gabor Grothendieck, Søren Højsgaard, Ayal Pinkus, Grzegorz Mazur, Mikkel Meyer Andersen |
| Maintainer: | Mikkel Meyer Andersen <mikl at math.aau.dk> |
| BugReports: | https://github.com/mikldk/ryacas/issues |
| License: | GPL-2 |
| URL: | https://github.com//mikldk/ryacas, http://www.yacas.org |
| NeedsCompilation: | yes |
| Materials: | README NEWS |
| In views: | NumericalMathematics |
| CRAN checks: | Ryacas results |
| Reference manual: | Ryacas.pdf |
| Vignettes: |
Introduction to Ryacas |
| Package source: | Ryacas_0.3-4.tar.gz |
| Windows binaries: | r-devel: Ryacas_0.3-4.zip, r-release: Ryacas_0.3-4.zip, r-oldrel: Ryacas_0.3-4.zip |
| OS X binaries: | r-release: Ryacas_0.3-4.tgz, r-oldrel: Ryacas_0.3-4.tgz |
| Old sources: | Ryacas archive |
| Reverse suggests: | nlsr |
Please use the canonical form https://CRAN.R-project.org/package=Ryacas to link to this page.


MKPaging Class Reference
| Inherits from | MKControl : UIControl |
| Declared in | MKPaging.h |
Overview
Overview
MKPaging provieds an interface for navigating between pages of an app. The interface is long bar with an arrow on either side and dots in the middle. The arrows respond to touches and the dots represent the pages of the document.
MKPaging only provieds an interface and sends events, it does not preform any transitions between pages.
Usage Notes
Since MKPaging does not preform an transitions, it does not update the numberOfPages or currentPage properties. For the proper function of the interface, these properties should be updated when transitions are completed.
Graphics
MKGraphics structures are supported by this control. MKPaging looks for the follow graphic properties:
- fillColor :
default black
- disabledColor :
default lightGray
Dispatched Actions
MKPaging dispatches two types of actions:
-
MKActionValueIncreased
: Sent when a touch on the right arrow ends. -
MKActionValueDecreased
: Sent when a touch on the left arrow ends.
Tasks
Creating
-
- initWithPages:
Creates an instance of MKPaging for the given number of Pages. The number of pages can be changed using the numberOfPages property. -
- initWithPages:graphics:
Creates an instance of MKPaging for the given number of Pages and a graphics structure. The number of pages can be changed using the numberOfPages property.
Page Control
-
numberOfPages
The number of pages (dots) the interface will display -
currentPage
The current page (dot) that is highlighted
Instance Methods
initWithPages:
Creates an instance of MKPaging for the given number of Pages. The number of pages can be changed using the numberOfPages property.
- (id)initWithPages:(NSInteger)numOfPages
Parameters
- numOfPages
- The number of pages (dots) the interface will display.
Return Value
MKPaging instance
Declared In
MKPaging.h
initWithPages:graphics:
Creates an instance of MKPaging for the given number of Pages and a graphics structure. The number of pages can be changed using the numberOfPages property.
- (id)initWithPages:(NSInteger)numOfPages graphics:(MKGraphicsStructures *)graphics
Parameters
- numOfPages
- The number of pages (dots) the interface will display.
- graphics
- an instance of MKGraphicsStructures used to draw the control.
Return Value
MKPaging instance
Declared In
MKPaging.h


$699.00
$1299.00
$649.00
Name:
Surname:
Date Of Birth:
ID-Number:
All you need in one place. All with a few simple clicks.
Attained Year: BY 10089
University of Zimbabwe


Trump Announces Plan for New Location for Signing of ‘Phase One’ of US-China Trade Deal
US President Donald Trump says the signing site of the “phase one” trade deal, which represents 60% of the overall long-term agreement, will be announced “soon” after the initial gathering in Chile was cancelled due to protests.
Chilean President Sebastian Pinera announced Wednesday he’s calling off the Asia-Pacific Economic Cooperation summit in Santiago in mid-November due to nationwide protests sparked by a proposed hike in public transport fares. Trump and Chinese leader Xi Jinping were expected to meet at the summit to discuss a possible “phase one” deal that the two countries are close to finalizing and could possibly even sign.
“China and the USA are working on selecting a new site for the signing of Phase One of Trade Agreement, about 60% of the total deal, after APEC in Chile was cancelled due to unrelated circumstances,” Trump tweeted on Thursday.
Trump earlier said that the “phase one” trade deal represents the majority of a long-term agreement, as Bloomberg News reported Thursday that China is doubtful about reaching a comprehensive trade deal with the US due to Trump’s “impulsive nature.” The US president assured that the phase one deal is “very substantial” and phase two will start “almost immediately” after the first phase is signed.
Trump had said the agreement would address issues such as intellectual property and financial services and has China promising to buy $40 billion to $50 billion in American agricultural products, while also including a pause in tariff hikes.


{% extends "home.html" %} {% block title %} CCIW Injury and Illness Reporting Acknowledgement Form — Health and Counseling — Carthage College {% endblock %} {% block extra_style %} {{block.super}} {% endblock %} {% block extra_javascript %} {% endblock %} {% block content %}


Covid-19 Tracker
Global Data
(current)
Country`s Data
State`s Data
Sign in
Please Hold on We are Collecting Information..
Global Information
Name
Total Case
Update
By Countries
Previous
Next