1. liga stats & predictions
Overview of Volleyball 1. Liga Czech Republic
The Czech Republic's premier volleyball league, the 1. Liga, is a showcase of talent and competition among the nation's top clubs. As fans eagerly anticipate tomorrow's matches, it's essential to delve into the intricacies of the league and explore expert betting predictions that could guide enthusiasts in making informed decisions.
No volleyball matches found matching your criteria.
Upcoming Matches and Teams to Watch
Tomorrow promises thrilling encounters as several key teams face off in what is expected to be a pivotal round in the league standings. Among these, teams like VK Praha and Slavia Prague are consistently performing at a high level, making their matches must-watch events for any volleyball aficionado.
Expert Betting Predictions
Expert analysts have been closely monitoring team performances, player statistics, and historical match outcomes to provide insightful betting predictions for tomorrow's games. These predictions are not just about winning or losing but understanding the dynamics that could influence the game's outcome.
- VK Praha vs. Slavia Prague: Analysts predict a closely contested match with VK Praha having a slight edge due to their recent form and home advantage.
- VC Ostrava vs. Dukla Liberec: With both teams showing strong defensive capabilities, this match is expected to be low-scoring, with Dukla Liberec favored to edge out a narrow victory.
- Karlovarsko vs. Volejbal Brno: Known for their aggressive playstyle, Karlovarsko is predicted to dominate against Volejbal Brno, especially considering their impressive performance on away games.
These predictions are based on comprehensive analysis including player form, head-to-head records, and tactical setups. However, as with all sports betting, there is always an element of unpredictability.
Key Players to Watch
Individual brilliance often turns the tide in volleyball matches. Here are some players whose performances could significantly impact tomorrow's games:
- Jakub Novotný (VK Praha): Known for his powerful serves and strategic plays.
- Pavel Černoch (Slavia Prague): A formidable blocker whose presence on the court can disrupt opponents' offensive strategies.
- Martin Kríž (VC Ostrava): An agile setter who excels in orchestrating plays and maintaining team rhythm.
Watching these players in action not only enhances the viewing experience but also provides insights into how individual skills can influence team success.
Tactical Insights: What Sets Top Teams Apart?
<|repo_name|>mikolaj-szpakowski/DS-Unit-4-Sprint-1-Software-Engineering<|file_sep|>/module4/lecture.md # Software Engineering & Design ## Lecture ### Notes #### Introduction **Why Software Engineering?** * The goal of software engineering is producing high quality software quickly. * **Software engineering** is a systematic approach that helps us understand how complex systems work by breaking them down into smaller pieces. * **Software design** is an important component of software engineering. * In this module we'll learn about two different approaches: **top-down** design & **object-oriented** design. #### Top-down Design The first step in top-down design is defining your problem clearly & concisely: * What inputs will you need? * What outputs do you expect? * What steps will you need to take? Once we've defined our problem clearly we can start thinking about solutions: 1. Start at the top level 2. Break down your program into smaller pieces 3. Repeat until each piece is simple enough that it can be implemented directly ##### Example: Making Change We want our program to accept an input (the price of an item) & output change using quarters/dimes/nickels/pennies. 1) Start at the top level - what does our program need to do? Our program needs to: * Accept user input * Calculate change * Output change 2) Break down each piece until they're simple enough that they can be implemented directly.
3) Implement each piece.
#### Object-Oriented Design
Object-oriented design takes a different approach than top-down design:
1) Instead of starting at the highest level of abstraction & working down through smaller levels - start by identifying objects within your system.
* Objects are things with attributes (data) & behaviors (functions)
* Each object represents one thing in your system
* Think about what attributes those things have & what behaviors they perform
* How do objects interact with each other?
2) Once you've identified objects within your system - break down each object into its attributes & behaviors until they're simple enough that they can be implemented directly.
3) Implement each object & interaction between objects.
##### Example: Making Change
Instead of starting at the highest level abstraction - start by identifying objects within our system:
Next we identify attributes & behaviors for each object:
Finally we implement each object:
#### Design Patterns
A design pattern is a reusable solution for solving common problems when designing software applications.
##### Common Patterns Include:
**Singleton**: Ensures only one instance of an object exists throughout application lifetime; useful when managing resources like database connections or network sockets.
**Factory**: Creates instances of classes without specifying exact class type; useful when creating complex objects with multiple dependencies or configurations needed before use.
**Observer**: Allows one object (observer) watch another object (subject); useful when changes made by subject need propagated automatically throughout system without explicit calls from observers themselves..
These patterns help developers create flexible code structures capable adapting easily over time while minimizing potential errors caused by hardcoding specific implementations into codebase itself..
#### Abstraction Levels
Abstraction levels refer different levels detail represented within codebase itself ranging from high-level abstractions representing entire systems down low-level details representing individual components within those systems..
High-level abstractions typically represent entire systems such as databases networks etc., while low-level details represent individual components such as functions methods classes modules etc..
By abstracting away unnecessary details developers can focus on solving problems efficiently without getting bogged down trying understand every detail involved implementation itself..
Abstraction also allows developers reuse existing code libraries frameworks etc., instead having rewrite everything from scratch every time new project begins..
##### Example: Database Systems
In database systems abstraction levels range from high-level abstractions representing entire databases down low-level details representing individual tables rows columns etc..
High-level abstractions allow developers query data easily without worrying about underlying structure implementation itself...
Low-level details allow developers optimize queries performance fine-tune database configuration settings etc...
By abstracting away unnecessary details developers can focus on solving problems efficiently without getting bogged down trying understand every detail involved implementation itself...
Abstraction also allows developers reuse existing code libraries frameworks etc., instead having rewrite everything from scratch every time new project begins...
#### Advantages Of Abstraction Levels
Abstraction levels offer several advantages including improved maintainability scalability reusability performance etc...
Improved maintainability: By abstracting away unnecessary details developers can focus on solving problems efficiently without getting bogged down trying understand every detail involved implementation itself...
Improved scalability: By abstracting away unnecessary details developers can focus on solving problems efficiently without getting bogged down trying understand every detail involved implementation itself...
Improved reusability: By abstracting away unnecessary details developers can focus on solving problems efficiently without getting bogged down trying understand every detail involved implementation itself...
Improved performance: By abstracting away unnecessary details developers can focus on solving problems efficiently without getting bogged down trying understand every detail involved implementation itself...
Overall abstraction levels offer numerous benefits helping improve maintainability scalability reusability performance overall quality resulting applications built using them...
<|repo_name|>mikolaj-szpakowski/DS-Unit-4-Sprint-1-Software-Engineering<|file_sep eliminated after sprint completion)
[ ] Students should be able to articulate why writing tests matters.
### Concepts
### Preparation Materials
### Student Resources
### Instructor Notes
# Class Activities
## Activity: Code Review Practice
[Slides](../slides/code_review_practice.pdf)
### Learning Objectives
[ ] Students should be able explain why testing matters.
[ ] Students should be able identify bugs in code using tests.
### Preparation Materials
### Student Resources
### Instructor Notes
## Activity: Writing Tests
[Slides](../slides/writing_tests.pdf)
### Learning Objectives
[ ] Students should be able write tests using pytest framework.
[ ] Students should be able run tests using pytest framework.
### Preparation Materials
### Student Resources
### Instructor Notes
## Activity: Code Review Practice Part II
[Slides](../slides/code_review_practice_part_ii.pdf)
### Learning Objectives
[ ] Students should be able explain why testing matters.
[ ] Students should be able identify bugs in code using tests.
### Preparation Materials
### Student Resources
### Instructor Notes
## Activity: Testing Strategies
[Slides](../slides/testing_strategies.pdf)
### Learning Objectives
[ ] Students should be able explain why testing matters.
[ ] Students should be able identify bugs in code using tests.
### Preparation Materials
### Student Resources
### Instructor Notes
## Activity: Testing Strategies Practice
[Slides](../slides/testing_strategies_practice.pdf)
Learning Objectives:
[] Students should demonstrate understanding common testing strategies by practicing them during this activity.
Preparation Materials:
Student Resources:
Instructor Notes:
# Homework Assignments
## Assignment Name
Description
Learning Objectives:
[]
Preparation Materials:
Student Resources:
Instructor Notes:
# Additional Resources
# Sprint Overview
# Sprint Details
# Post Sprint Details
# Sprint Summary
<|file_sep------------- LECTURE NOTES -------------
Lecture Content:
• What’s coming up this sprint?
• What are some examples where TDD has been used successfully?
• What’s covered in Module One?
• What’s covered in Module Two?
------------- PREPARATION MATERIALS -------------
Course Textbook:
• Python Crash Course Second Edition Chapter Five – Functions
• Python Crash Course Second Edition Chapter Six – Modules
• Python Crash Course Second Edition Chapter Seven – Classes
• Python Crash Course Second Edition Chapter Eight – Debugging
• Python Crash Course Second Edition Chapter Nine – Testing Your Code
Module One:
• TDD Demo Code https://repl.it/@mattgoldspink/tdd-demo-code
Module Two:
• TDD Demo Code https://repl.it/@mattgoldspink/tdd-demo-code-part-two
------------- STUDENT RESOURCES -------------
Class Slides:
• Sprint Overview https://docs.google.com/presentation/d/e/2PACX-_QZ7kR5NqOJYwW0YiL6bTfV5FmZxJ8yWqG9vXrAARQvMg0XUvM8aKkVl6UyZsHtE7Bw/edit?usp=sharing
Lecture Video Recording:
• Sprint Overview https://www.youtube.com/watch?v=8qLW0-mFwzo&t=0s&ab_channel=Codefellows
------------- INSTRUCTOR NOTES -------------
Introductory Remarks:
This week we’ll dive deeper into Test Driven Development! In Module One we learned how TDD works and wrote some basic unit tests for our Python programs. Now it’s time to put those skills into practice!
We’ll start off by reviewing some examples where TDD has been used successfully before moving onto more advanced topics like mocking external services or handling exceptions gracefully while still maintaining good test coverage across all parts of your application(s).
Next up will be looking at how best practices around documentation fit into TDD workflows so make sure everyone knows what kind(s)of documentation exists out there already before starting any new projects!
Finally wrap up with some hands-on exercises where students get hands-on experience writing unit tests themselves!
Good luck everyone!
<|repo_name|>mikolaj-szpakowski/DS-Unit--Sprint---<|file_sep>> # Unit X - Sprint Y Outline Template
---
## Learning Outcomes
---
## Required Pre-work
---
## Classroom Time
---
## Post-Classroom Activities
--- <|repo_name|>mikolaj-szpakowski/DS--Sprints---<|file_sep skillset = ["Python", "JavaScript", "Java", "C++"]
skillset.append("SQL")
skillset.insert(0,"PHP")
skillset.remove("C++")
skillset.pop()
skillset.pop(0)
skillset.reverse()
skillset.sort()
def reverse_list(list):
return list[::-1]
reverse_list(skillset)
def contains(item,list):
if item not in list:
return False
else return True
contains("Java", skillset)<|file_sep # Lecture Notes
Lecture Content:
• Introduction to APIs
• How to Use Requests
• How to Use Response
• How To Handle Errors And Exceptions
• How To Use Pytest For API Testing
# PREPARATION MATERIALS #
# Course Textbook:
• Python Crash Course Second Edition Chapter Thirteen – Web Applications
• Python Crash Course Second Edition Chapter Fourteen – APIs
• API Testing Guidebook — An Introductory Guide To API Testing And Automation Using Python And Postman By Pradeep Soundararajan
• API Testing Guidebook — An Introductory Guide To API Testing And Automation Using Python And Postman By Pradeep Soundararajan—Chapters Four Through Sixteen
# STUDENT RESOURCES #
Class Slides :
• Lecture Slides https://docs.google.com/presentation/d/e/2PACX-_Q9xjPVY5g8tD_g_-fImyGowTtO-RuN3JBdR9CFJPGStxqDf-jCjh9vAGlQnO8cHqsDdMBrITAg3xgI/edit?usp=sharing
Lecture Video Recording :
• Lecture Video Recording https://youtu.be/qZ_DpeAv6vs
# INSTRUCTOR NOTES #
Introductory Remarks :
This lecture will cover how APIs work along with how requests work within them . We’ll discuss error handling , exception handling ,and finally look at how Pytest comes into play when testing APIs . So let’s get started ! First off , let’s talk about APIs ! An Application Programming Interface , commonly known as an API , acts as a bridge between two applications . It allows them communicate back-and-forth so they don’t have direct access one another . Think sending email through Gmail app . Gmail app uses Google’s servers via its own API which means Gmail doesn’t need direct access server space hosted somewhere else .
The requests module makes it easy send HTTP requests via Python scripts . You just import requests then call its methods depending upon which type request needs sent . For example if want GET request use requests.get() method whereas POST request would require calls requests.post() method .
Responses returned after executing requests contain information such status codes body content headers cookies etc . All this info stored Response object returned call request method .
Error handling refers process catching exceptions thrown occur during runtime . Exceptions raised either due programming errors incorrect usage library functions syntax mistakes .
Exception handling involves catching exceptions raised occur runtime then taking appropriate actions handle them gracefully rather letting crash application abruptly .
Finally , pytest framework provides powerful tools test writing automated unit integration functional acceptance end-to-end test cases written python language !
Let me know if any questions arise along way ! Good luck everyone !
<|repo_name|>mikolaj-szpakowski/DS--Sprints---<|file_sep· [Back](../../README.md)
--------------------
# Unit X - Sprint Y Outline Template
--------------------
Welcome!
This template outlines activities for Unit X / Sprint Y
You'll find sections below detailing required pre-work; classroom time activities; post-classroom activities; additional resources; sprint overview; sprint details; post sprint details; and finally sprint summary
For more information about course structure please see [here](../../course_structure/course_structure.md).
Please feel free to reach out via Slack if you have any questions!
--------------------
## Learning Outcomes
--------------------
## Required Pre-work
--------------------
## Classroom Time
--------------------
## Post-Classroom Activities
--------------------
## Additional Resources
--------------------
## Sprint Overview
--------------------
## Sprint Details
--------------------
## Post Sprint Details
--------------------
## Sprint Summary
--------------------
<|repo_name|>mikolaj-szpakowski/DS--Sprints---<|file_sep Huong Le | Mikola Szpakowski | Joseph Schmit | Maggie Chen | Kevin Zheng | Christine Chiang
-----------------------------------------------------
Project Name:
-----------------------------------------------------
Airbnb Clone
-----------------------------------------------------
Description:
-----------------------------------------------------
An AirBnb clone web application that enables users sign up / log-in / log-out / search listings / view listings / book reservations.
-----------------------------------------------------
Features:
-----------------------------------------------------
User Stories:
As a visitor,
When I visit site,
I see navigation bar with links “Home”, “About”, “Log In”,
“Sign Up”, “Listings”, “Profile”.
As a visitor,
When I click “Home” link,
I am taken back home page.
As an unregistered visitor,
When I visit site,
I see button “Log In”.
As an unregistered visitor,
When I click “Log In” button,
I am taken login page.
As an unregistered visitor,
When I am taken login page,
I see fields email address password.
As an unregistered visitor,
When I fill out field email address password submit form,
If credentials correct,
Then my session logged-in user created.
If credentials incorrect,
Then flash message appears indicating incorrect credentials.
As an unregistered visitor,
When I visit site landing page URL path "/listings",
I am redirected back homepage URL path "/".
As an unregistered visitor,
When I click "Sign Up",
I am taken sign-up page URL path "/users/new"
As a registered user
when i visit homepage url path "/",
i see my profile picture next to my name near nav bar
as well as links "My Profile", "My Listings", "Log Out"
as well as listing cards containing title price description location image urls.
Feature Tasks:
create seed data
create views for index pages
user stories:
as an admin user i want users created so i can populate db w users
Models:
User:
email:string:index unique true required valid email format validations presence true
password_digest:string:index valid password format validations presence true
session_token:string:index unique true validations presence true
role:string enum[:default] default 'user' validations inclusion {:in => ['admin', 'user']}
name:string valid name format validations presence true
Listing:
title:string valid title format validations presence true
description:text valid description format validations presence true
price:dollar integer positive number validations presence true
location:string valid location format validations presence true
image_url:string valid image url format
Reservation:
check_in:date present past date
check_out:date present future date
guest_number:int present positive number <=10
Relationships:
User has many reservations through listings
Listing belongs_to user
Listing has many reservations
Reservation belongs_to listing
Reservation belongs_to user
Database Schema Diagram:

Routes:
Users
POST '/users'
GET '/users/:id'
PATCH '/users/:id'
DELETE '/users/:id'
Reservations
GET '/reservations'
POST '/reservations'
PATCH '/reservations/:id'
DELETE '/reservations/:id'
Listings
GET '/listings'
POST '/listings'
PATCH '/listings/:id'
DELETE '/listings/:id'
Testing Strategy:
Test Plan:
feature test:
sign up/login/logout routes + sessions controller
all model associations + relationship routes + controllers
unit test:
all models + relationships + validations
integration test:
listing controller show page renders correctly w all info needed rendered properly
Model Specs:
user spec:
can save w correct attrs passed in hash?
can't save w invalid attrs passed?
has many reservations through listings?
has many listings?
valid email? validates uniqueness? validates presence?
valid password? validates length?
valid session token? validates uniqueness?
valid role enum?: validates inclusion?
valid name? validates presence?
listing spec:
can save w correct attrs passed in hash?
can't save w invalid attrs passed?
belongs_to user?
has many reservations?
valid title? validates length?, validates uniqueness?, validates presence?
valid description text? validates length?, validates presence?
valid price dollar integer positive number? validates numericality?, greater than zero?, less than max value?, integer?, inclusion?: {in => [10..100]}, range?: {in => [10..100]}, length?: {minimum =>10}, maximum?: {maximum =>100}, equality?: {equal_to =>50}
valid location string? validates length?, validates uniqueness?, validates presence?
valid image_url string? url validation regex pattern matching http(s)?
reservation spec:
can save w correct attrs passed in hash?
can't save w invalid attrs passed?
belongs_to listing
belongs_to user
check_in date present past date ? validate :presence ?, validate :past_date ? check_out date present future date ? validate :presence ?, validate :future_date ? guest_number int present positive number <=10 ? validate :presence ?, validate :numericality ?, validate :less_than_or_equal_to ?
View Specs:
index pages specs render correctly all info needed rendered properly
Other notes:
seed file contains fake data generated via faker gem installed
---------------------------------
Project Management Tools Used:GitHub
Trello
--------------------------------- Screenshots:


--------------------------------- Contributors:
Huon Le
Kevin Zheng
Christine Chiang
Joseph Schmit
Maggie Chen
--------------------------------- Video Walkthrough:
Link Here:
--------------------------------- Reflection:
What went well?
Our group worked very well together! We were very organized throughout development process! We divided tasks amongst ourselves equally so no one was overloaded or felt left out! Our group communication was excellent too! We held regular meetings/discussions/sessions throughout development process ensuring everyone was updated kept informed current progress being made. What challenges did you face?
There weren't really any major challenges faced throughout development process! However minor challenges faced included coordinating meeting times due different schedules/time zones individuals participating group! Additionally minor challenges faced included integrating various features functionality together smoothly ensuring everything worked properly!
How did you overcome these challenges?
To overcome challenge coordinating meeting times different schedules/time zones individuals participating group used various communication tools/apps e.g.: slack zoom google calendar allowing individuals communicate effectively despite differences schedules/time zones.
To overcome challenge integrating various features functionality together smoothly ensuring everything worked properly tested features thoroughly debugging issues encountered!
How did you ensure your product met specifications?
To ensure product met specifications tested features thoroughly debugged issues encountered ensuring everything worked properly!
How did you keep track of tasks?
To keep track tasks used trello board tracking progress tasks assigned individuals completing tasks accordingly!
How did you manage conflicts?
To manage conflicts communicated openly honestly discussing issues concerns respectfully addressing concerns resolving conflicts peacefully!
Did anyone ask for help outside class?
No one asked help outside class!
Would you approach anything differently next time?
No! Our group worked very well together throughout development process! We were very organized dividing tasks amongst ourselves equally no one felt overloaded left out! Our group communication was excellent holding regular meetings/discussions/sessions keeping everyone updated informed current progress being made.<| <|repo_name|>mikolaj-szpakowski/DS--Sprints---<|file_sep># Software Engineering & Design Here you'll find materials related specifically around lecture content! For more information about course structure please see [here](../../course_structure/course_structure.md). Please feel free to reach out via Slack if you have any questions! --------------- # Lecture Content For more information regarding lecture content please refer [here](./lecture.md). --------------- # Preparations Materials For more information regarding preparation materials please refer [here](./preparation_materials.md). --------------- # Student Resouces For more information regarding student resources please refer [here](./student_resources.md). --------------- --------------- <|repo_name|>mikolaj-szpakowski/DS--Sprints---<|file_sep prin('hello world') prin('hello world') prin('hello world') prin('hello world') prin('hello world') def print_hello_world(): print('hello world') for i in range(5): print_hello_world()<|repo_name|>mikolaj-szpakowski/DSCapstoneProjectTeam7-master<|file_sepattempts = [] def attempt(attempt): attempts.append(attempt) if len(attempts)>=3: return attempts[-3:] return attempts attempt(65) attempt(80) attempt(75) attempt(85)<|repo_name|>mikolaj-szpakowski/DSCapstoneProjectTeam7-master<|file_sep:: This folder contains materials related specifically around classroom activities! For more information about course structure please see [here](../../course_structure/course_structure.md). Please feel free to reach out via Slack if you have any questions! ---------------- # Class Activities Overview ------------- # Activity Name One This activity focuses primarily around... Learning objectives include... Preparations materials include... Student resources include... Instructor notes include... ------------- # Activity Name Two ------------- # Homework Assignments Overview ------------- Homework assignments focus primarily around... Homework assignment learning objectives include... Homework assignment preparations materials include... Homework assignment student resources include... Homework assignment instructor notes include... ------------- Homework assignment three ------------- Additional resources overview Additional resource includes... --------------- <|repo_name|>mikolaj-szpakowski/DSCapstoneProjectTeam7-master<|file_sep charged_bikes = [ { id: 'abc123', type:'road', distance_covered:'14', condition:'new', renter_id:'aaa' }, { id:'def456', type:'mountain', distance_covered:'37', condition:'normal', renter_id:'bbb' }, { id:'ghi789', type:'electric', distance_covered:'24', condition:'damaged', renter_id:null } ] charged_bikes.each do |bike| if bike[:renter_id] != nil && bike[:distance_covered].to_i >20 && bike[:condition] == 'normal' puts "#{bike[:id]} rented" end end <|repo_name|>mikolaj-szpakowski/DSCapstoneProjectTeam7-master<|file_sep ... class BikeShare { constructor(id,type,distance_covered){ this.id=id; this.type=type; this.distance_covered=distance_covered; this.renter_id=null; } charge(){ if(this.renter_id==null&&this.condition=='working'){ console.log(this.id+' charged'); } } rent(renterId){ if(this.distance_covered<=20&&this.condition=='working'&&this.renter_id==null){ this.renter_id=renterId; console.log(this.id+' rented'); }else{ console.log(this.id+' cannot rent'); } } return(bike){ if(this.renter_id!=null&&this.distance_covered<=20&&this.condition=='working'){ this.renter_id=null; console.log(this.id+' returned'); bike.renter_id=this.id; bike.distance_covered+=this.distance_covered; console.log(bike.id+' rented'); console.log(`total distance covered ${bike.distance_covered}`); }else{ console.log(this.id+' cannot return'); } } } const abc=new BikeShare('abc123','road',14); const def=new BikeShare('def456','mountain',37); const ghi=new BikeShare('ghi789','electric',24); abc.charge(); abc.rent('aaa'); ghi.charge(); ghi.return(def); def.charge(); def.return(ghi);e^{-frac{Delta E}{k_BT}}$ \ texttt{numpy.random.choice} ($a$, $size=None$, $replace=True$, $p=None$)& hspace{0cm} $a$: array-like \ & hspace{0cm} $size$: int or tuple \ & hspace{0cm} $replace$: boolean \ & hspace{0cm} $p$: array-like \ & hspace{0cm} Returns random samples from given array \ \ texttt{numpy.random.exponential(scale=$tau$)} ($tau$)& $tau$: float \ & hspace{0cm} Draw samples from exponential distribution \ \ texttt{numpy.random.multivariate_normal(mean=$mu$, cov=$Sigma$)} ($mu$, $Sigma$)& $mu$: mean vector \ & hspace{0cm} $Sigma$: covariance matrix\ & hspace{0cm} Draw random samples from multivariate normal distribution \ \ texttt{nose.tools.assert_equal($actual$, $desired$)} ($actual$, $desired$)& Assert actual equals desired\ \ texttt{nose.tools.assert_true($expr$)} ($expr$)& Assert expression evaluates True\ \ texttt{nose.tools.assert_false($expr$)} ($expr$)& Assert expression evaluates False\ \ texttt{nose.tools.assert_raises($expected$, $func$)} ($expected$, $func$)& Assert function raises expected exception\ \ texttt{nose.tools.raises($ast$args,**$ast$kwargs)} ($ast$args,**$ast$kwargs)& Decorator asserting function raises exception\ \ texttt{nose.tools.raises($ast$args,**$ast$kwargs)(func)} ($ast$args,**$ast$kwargs)(func)& Decorator asserting function raises exception\ \ %run ipynbtools.py --skip "__main__" --output exp.ipynb\ %matplotlib inline --no-import-all --pylab --no-export\ %config InlineBackend.figure_format='retina' from numpy import array as nparray\ import numpy.random as nprandom\ import scipy.stats.distributions as spdist\ import nose.tools as notestools\ import matplotlib.pyplot as pltmplplot\%matplotlib inline --no-import-all --pylab --no-export\%config InlineBackend.figure_format='retina' class Metropolis(object):\\ def __init__(self,state,pdf,xrange=(-np.inf,np.inf),burn_in=10000,take_every=10):\\ self.state=nparray(state,copy=True,dtype=float) self.pdffunction=pdf self.xrange=xrange self.burn_in=int(burn_in) self.take_every=int(take_every) self.iteration=-burn_in\ def iterate(self,newstate=None):\\ if newstate is None: self.newstate=self.possible_state() else: self.newstate=newstate\ pold=self.evaluate_pdf(self.state) pnew=self.evaluate_pdf(self.newstate) ap=pnew-pold\ if ap>=nplog(nprandom.rand()):\ self.accept_new_state() else: pass\ def possible_state(self): newstate=nprandom.uniform(low=self.xrange[0],high=self.xrange[1]) return newstate\ def evaluate_pdf(self,state): return spdist.norm.cdf(state)-spdist.norm.cdf(state-.5) def accept_new_state(self): self.state=self.newstate self.iteration+=self.take_every\ def get_chain(self,nsteps=None): chain=[] if nsteps: nsteps=int(nsteps) else: nsteps=(self.iteration+self.burn_in+self.take_every)/self.take_every\ chain=[self.state] for _step,_iterate_n_times(nsteps): chain+=[self.iterate()] return chain[-(len(chain)-self.burn_in/self.take_every)::self.take_every] metropolis=Metropolis([(15.)],spdist.norm(loc=.5,scale=(.25) ),(xrange=(-np.inf,np.inf),burn_in=50000,take_every=100) ) chain=metropolis.get_chain() pltmplplot.hist(chain,bins='auto',normed=True,label='Metropolis Chain') xvals=np.linspace(-.75,.75,num=(500) ) pltmplplot.plot(xvals,[metropolis.pdffunction(xval,)for xval (in xvals) ],label='True PDF') pltmplplot.legend(loc='best') pltmplplot.show() notestools.assert_true(metropolis.possible_state()>-(.75) ) notestools.assert_true(metropolis.possible_state()<.75) ) notestools.assert_equal(metropolis.evaluate_pdf((.25) ),(spdist.norm.cdf(.25)-spdist.norm.cdf(.25-.5) )) notestools.assert_raises(AssertionError,Metropolis,([],None,-np.inf,np.inf,burn_in=.01,take_every=.001) ) notestools.assert_raises(AssertionError,Metropolis,([],None,-np.inf,np.inf,burn_in=-100000,take_every=.001) ) notestools.assert_raises(AssertionError,Metropolis,([],None,-np.inf,np.inf,burn_in=.01,take_every=-100000) ) @notestools.raises(AssertionError)@notestools.raises(ValueError)@classmethodn def bad_init(cls,state,pdf,xrange=(-npinf,npinf) ):... passn @classmethodn @notestools.raises(TypeError)@notestools.raises(ValueError)@classmethodn def bad_init(cls,state,pdf,xrange=(-npinf,npinf) ):... passn @classmethodn @notestools.raises(TypeError)@notestools.raises(AssertionError)@classmethodn def bad_init(cls,state,pdf,xrange=(-npinf,npinf) ):... passn @classmethodn @notestools.raises(AssertionError)@classmethodn def bad_iterate(cls,newstate=None):... passn @classmethodn @notestools.raises(TypeError)@classmethodn def bad_possible_state(cls):... passn @classmethodn @notestools.raises(AssertionError)@classmethodn def bad_possible_state(cls):... passn Metropolis.bad_init=bad_init.__get__(None,Metropolis) Metropolis.bad_iterate=bad_iterate.__get__(None,Metropolis) Metropolis.bad_possible_state=bad_possible_state.__get__(None,Metropolis) with notetestoolstemporaryDirectory():... tempdir=tempdir() metropostemp=Metropolistempdir.joinpath('temp.pkl') metropostemp.writebytes(pickle.dumps(Metropolismetatempdir.joinpath('temp.pkl') ) ) loadedmetropostemp=pickle.loads(metropostemp.readbytes()) with notetestoolstemporaryDirectory():... tempdir=tempdir() metropostemp=Metropolistempdir.joinpath('temp.pkl') metropostemp.writebytes(pickle.dumps(Metropolismetatempdir.joinpath('temp.pkl') ) ) loadedmetropostemp=pickle.loads(metropostemp.readbytes()) assert isinstance(loadedmetropostemp,Metropolismetatempdir.joinpath('temp.pkl') ) assert isinstance(loadedmetropostemp.metadatadict['initial-state'],(listoffloatslikeMetropolismetatempdir