Introduction
Welcome to Machine Learning with TensorFlow, an easy to follow book / blog about understanding machine learning concepts and their implementation in Python and TensorFlow. My goal is to create an intuitive explanation of machine learning methods, paired with practical knowledge of implementation with TensorFlow. This book does assume some small working knowledge of programming, but Python specific syntax will be briefly introduced as needed. In addition, some mathematics background will be useful, in particular linear algebra and calculus, but is not needed to follow the intuition and implementation. Resources to review relevant math concepts will be provided as required.
What exactly is machine learning?
Though the exact definition of machine learning is up for debate, we can roughly define machine learning as "a field of computer science that gives computers the ability to learn without being explicitly programmed" (Wikipedia). Traditionally, programming has been used to great effect to solve problems which have explicit steps. For example, consider the problem of determining if a number \(n\) is prime. We can easily determine if \(n\) is prime using fairly simple steps: check if \(n\) is divisible by \(2\), check if \(n\) is divisible by \(3\), \(\cdots\), check if \(n\) is divisible by \(n-1\). If \(n\) is divisible by any of these, then \(n\) is not prime, and otherwise it is prime. With traditional programming we then need to write these specific steps (an algorithm) in a programming language that our computer can interpret, and we have a working program which can classify numbers as prime much faster than a human ever could.
However, some tasks seem difficult or impossible to solve using specific steps like above. Rather than classifying prime numbers, let us instead try to classify images of dogs as either a Golden Retriever or Poodle.
| Golden Retriever | Poodle |
|---|---|
Most people would easily be able to differentiate the two breeds above, and accurately dogs of those breeds. But, can you explain how you came to this conclusion, in very specific steps? Perhaps, one might say that the hair of the Golden Retriever seems less curly, but then one would need to explain how to determine that the hair is less curly. There does not seem to exist a natural way to describe the curliness of hair in specific steps. Maybe, the shape of facial features such as nose shape are useful for determining dog breed, but it still seems nearly impossible to describe a precise algorithm that uses this data.
Qualitatively, humans do not seem to comprehend the beed of a dog by performing some precise algorithm, and this suggests that a computer program to solve this problem should not either. By using machine learning, we can use data to help the computer learn to recognize a dog breed, objects in general, human speech, etc., without explicitly programming it.
So, what is TensorFlow, and why do we need it?
Without diving into the details of various machine learning methods, I'll generally state that there could be a fairly significant amount of math involved. Not necessarily super difficult math, but some pretty cumbersome math. Roughly, TensorFlow takes care of the calculus grunt work for us: instead of spending a ton of time finding messy derivatives and many lines of code to compute them, TensorFlow lets us focus on the fairly elegant work of defining our machine learning methods, and the more important math necessary to obtain intuition.
So, without further ado, we can get started by installing Python, TensorFlow, and a few other useful tools. Just follow the appropriate directions for your operating system.
macOS Setup
Without a doubt, Python 3 is the future of Python, and thus we will use Python 3 with TensorFlow. While I summarize the instructions to install TensorFlow with Python 3 here, the official TensorFlow documentation should always provide up-to-date and comprehensive instructions for installation as well. If you run into any installation problems, please file a bug here.
Installing Python 3
macOS does not come installed with Python 3 (only Python 2.7), so we need to install it ourselves. The first step is to open terminal (Terminal.app on your Mac), and install the Homebrew package manager for macOS, if you haven't already installed it before. Just paste the appropriate command into terminal, and follow Homebrew's installation prompts:
# For bash, ksh, zsh, csh, and other shells:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
# For fish shell:
/usr/bin/ruby -e "(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Now that Homebrew is installed, we need to install Python 3:
brew install python3
You can test that python3
installed correctly by running the command python3
. You should see output similar to:
~ $ python3
Python 3.6.3 (default, Nov 20 2017, 14:17:35)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
The Python version should be 3.x.y instead of 2.x.y.
Installing TensorFlow and friends
Installing Python 3 (python3
) also installs the Python 3 package manager (pip3
). We can use pip3
to install a Python utility called virtualenv
. Virtualenv is an extremely easy and convenient way to install Python packages in a local and contained manner. The recommended way to install TensorFlow is by using virtualenv
, since this ensures that the installation will be self-contained, and will not affect the rest of your system. So, first we need to install virtualenv
:
pip3 install --upgrade virtualenv
Now, create a new virtualenv:
# In this command, ~/tensorflow is the destination directory where the virtualenv will be created.
# You can choose a different location if you prefer, but the rest of the installation tutorial will assume ~/tensorflow
virtualenv --system-site-packages -p python3 ~/tensorflow
Then, we need to activate the virtualenv so we can install things inside it:
source ~/tensorflow/bin/activate # If using bash, sh, ksh, zsh
source ~/tensorflow/bin/activate.csh # If using csh or tcsh
source ~/tensorflow/bin/activate.fish # If using fish
After activating the virtualenv, your command prompt should change to look like: (tensorflow)$
. At this point, we are finally ready to install TensorFlow:
pip3 install --upgrade tensorflow
In addition, we also install a few other Python packages that are useful for machine learning:
pip3 install --upgrade numpy # Used for linear algebra. Essential for using TensorFlow
pip3 install --upgrade matplotlib # Used for plotting data, which is very useful for machine learning
pip3 install --upgrade pandas # Used for loading data sets
Once everything is installed, you can exit the virtualenv using the command deactivate
.
Testing the installation
Let's just quickly test the installation, to verify everything is installed and ready to go! If it isn't currently activated, activate your virtualenv with the appropriate activate command from above. Then, run the python
command, and type the following code into Python:
import tensorflow as tf
import numpy as np
import pandas
import matplotlib.pyplot as plt
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
If everything is installed correctly, you should see the output:
Hello, TensorFlow!
If the above test produces errors, please see this list of common TensorFlow installation problems or Google it, and file a bug here.
Optional: Installing an IDE
At this point, everything we need for writing TensorFlow code is installed. We can write our Python code in a text editor of our choice, and run it using python
from terminal. In the future I won't assume use of an IDE specifically, but rather assume that you can create new Python files and run them, either from terminal or an IDE. However, some people may prefer using an IDE, which can reduce the time spent in Terminal, and help provide better syntax and semantic checking of Python code. Personally, I use and recommend PyCharm, which you can download for free here. I won't provide specific installation instructions, but I found it very easy to install and configure to use the ~/tensorflow
virtualenv.
Linux (Ubuntu) Setup
Without a doubt, Python 3 is the future of Python, and thus we will use Python 3 with TensorFlow. While I summarize the instructions to install TensorFlow with Python 3 here, the official TensorFlow documentation should always provide up-to-date and comprehensive instructions for installation as well. If you run into any installation problems, please file a bug here. Note that Ubuntu is the only officially supported Linux distribution for TensorFlow, but with a bit of effort TensorFlow can likely be installed on other distributions as well.
Optional: Install GPU Support
On Linux TensorFlow has the ability to run your machine learning models on a GPU, which can make computation significantly faster. However, the speed difference is negligible until we start building extremely large models with massive amounts of data. So if you have a supported GPU, you could choose to install GPU support now, or just wait until later. To see if your GPU is supported and instructions for installing GPU support, see here.
Installing Pip and Virtualenv
First, we need to install pip
, and virtualenv
. This should be easy using apt-get
:
sudo apt-get install python3-pip python3-dev python-virtualenv
Installing TensorFlow and friends
Now that we
Virtualenv is an extremely easy and convenient way to install Python packages in a local and contained manner. The recommended way to install TensorFlow is by using virtualenv
, since this ensures that the installation will be self-contained, and will not affect the rest of your system. Now, we need to create a new virtualenv:
# In this command, ~/tensorflow is the destination directory where the virtualenv will be created.
# You can choose a different location if you prefer, but the rest of the installation tutorial will assume ~/tensorflow
virtualenv --system-site-packages -p python3 ~/tensorflow
Then, we need to activate the virtualenv so we can install things inside it:
source ~/tensorflow/bin/activate # If using bash, sh, ksh, zsh
source ~/tensorflow/bin/activate.csh # If using csh or tcsh
source ~/tensorflow/bin/activate.fish # If using fish
After activating the virtualenv, your command prompt should change to look like: (tensorflow)$
. At this point, we are finally ready to install TensorFlow:
pip3 install --upgrade tensorflow # If installing WITHOUT GPU support
pip3 install --upgrade tensorflow-gpu # If installing WITH GPU support
In addition, we also install a few other Python packages that are useful for machine learning:
pip3 install --upgrade numpy # Used for linear algebra. Essential for using TensorFlow
pip3 install --upgrade matplotlib # Used for plotting data, which is very useful for machine learning
pip3 install --upgrade pandas # Used for loading data sets
Once everything is installed, you can exit the virtualenv using the command deactivate
.
Testing the installation
Let's just quickly test the installation, to verify everything is installed and ready to go! If it isn't currently activated, activate your virtualenv with the appropriate activate command from above. Then, run the python
command, and type the following code into Python:
import tensorflow as tf
import numpy as np
import pandas
import matplotlib.pyplot as plt
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
If everything is installed correctly, you should see the output:
Hello, TensorFlow!
If the above test produces errors, please see this list of common TensorFlow installation problems or Google it, and file a bug here.
Optional: Installing an IDE
At this point, everything we need for writing TensorFlow code is installed. We can write our Python code in a text editor of our choice, and run it using python
from terminal. In the future I won't assume use of an IDE specifically, but rather assume that you can create new Python files and run them, either from terminal or an IDE. However, some people may prefer using an IDE, which can reduce the time spent in terminal, and help provide better syntax and semantic checking of Python code. Personally, I use and recommend PyCharm, which you can download for free here. I won't provide specific installation instructions, but I found it very easy to install and configure to use the ~/tensorflow
virtualenv.
Windows Setup
To be blunt, I only use macOS and Linux, and I have no experience installing TensorFlow or even Python on Windows. Instead, I will simply direct you to the official documentation for TensorFlow on Windows.
When installing Python, please ensure that you use Python 3, rather than Python 2. Also, install the Python packages NumPy, Pandas and matplotlib in addition to TensorFlow.
Optional: Installing an IDE
At this point, everything we need for writing TensorFlow code in installed. We can write our Python code in a text editor of our choice, and run it using python
from terminal. In the future I won't assume use of an IDE specifically, but rather assume that you can create new Python files and run them, either from terminal or an IDE. However, some people may prefer using an IDE, which can reduce the time spent in terminal, and help provide better syntax and semantic checking of Python code. Personally, I use and recommend PyCharm, which you can download for free here. I won't provide specific installation instructions, but I found it very easy to install and configure.
Linear Regression
Roughly, there are two categories of machine learning:
- In supervised learning one already has access to a data set of example inputs and desired outputs, and teaches the computer to produce the desired outputs given the example inputs.
- In unsupervised learning one only has access to a data set: there is not necessarily any notion of "input" and "output". The goal is to teach the computer to autonomously discover underlying patterns in the data set.
For example, if we have a data set containing students' GPAs and SAT scores, we could attempt to train a supervised machine learning model to predict SAT scores given GPAs. Here, GPA would be the input, and SAT score would be the desired output. On the other hand, if we only have access to students' GPAs, then we could try to use unsupervised machine learning models to find patterns in the GPAs: perhaps there exist "clusters" in the data of similarly performing students.
Unsupervised machine learning will be touched on later, but for now we focus on supervised machine learning: in general it is easier, and the objective is clearer. Specifically, there are two main types of supervised learning:
- Regression aims to predict a continuous output, given the inputs.
- Classification aims to predict a classification, given the inputs.
The GPA and SAT score example from above is an example of regression, since we are trying to predict the continuous output variable of SAT scores. We aren't trying to classify students based on GPAs, we just want to estimate what their SAT score will be. On the other hand, suppose we also have data about UC Davis college admissions: we could then try to predict whether or not a student will be accepted based on their GPA. This would be an example of classification, since the output of the prediction is not continuous, it is a classification (accepted or rejected).
In this chapter we look at regression only, and specifically the simplest form: linear regression. We start with the most basic form of linear regression (single variable linear regression), and then move on to consider variants of linear regression. Using these variants we can obtain models that are both fairly simple and powerful.


Mahabalipuram
58 km south of Chennai is an ancient historic town dating to the time of Periplus (1st century CE) and Ptolemy (140 CE), from whence ancient Indian traders sailed to countries of South East Asia.
Shore Temple a structural temple with the entrance from the western side away from the sea. Recent excavations have revealed additional structures here.
Five Chariots Pancha Rathas (Hindi) – five monolithic pyramidal structures named after the Pandavas (Arjuna, Bhima, Yudhishtra, Nakula and Sahadeva) and Draupadi. An interesting aspect of the rathas is that, despite their sizes they are not assembled – each of these is carved from one single large piece of stone.
Krishna's Butterball Vaan Irai Kal – is a gigantic granite boulder resting on a short incline in the historical town of Mahabalipuram in India. The boulder is approximately 6 meters high and 5 meters wide and weighs around 250 tons.
Descent of the Ganges or Bagiratha's Penance is a giant open-air rock relief.


UltiAnalytics
UltiAnalytics is a mobile (iOS and Android) app and web site
for tracking statistics for your ultimate team(s). Users create one
or more teams in the mobile app and gather stats as the game is in
progress. The user can upload the statistics to their team website
(provided) at any time. The app also features a Twitter interface
that allows the user to "auto-tweet" game events as they happen.
Get
Started
Features
- Create one or more teams that can be uploaded and
downloaded to different mobile devices (for backup or passing on
the tracking duties...or a low battery situation).
- Gather stats while the game action progresses
- passes, drops, assists, goals, d's, throwaways with
additional detail as well (see screenshots)
- move players from field to bench with help on gender
and playing time
- all game events available to view and undo
- wind effect
- Upload games(s) to your team site (each team you create
get it's own statistics website) at any time during or after the
game. Example: Sample
Web Site
- Tweet the progress of the game for those that can't
attend. Use "auto-tweet" to have the app tweet progress for you
and/or use the integrated Tweet view to send ad-hoc tweets.
Action View - Our team has the disc
Action View - Their team has the disc
Updating the players on the field
Stats View (this is just a light view...on the
iPhone...much more on web site after upload)
Cloud (upload/download) View
Recent Tweets View (tweeted automatically by app)
‹ ›
Sample Website
(tap to view)


--- title: eval sidebar: function_reference_sidebar permalink: SO3FunRBF.eval.html folder: function_reference toc: false ---
evaluate sum of unimodal components at orientation g
general formula:
\[ f(r) = sum_j w_j \psi(r,c_j) \]
| SO3F | @SO3FunUnimodal |
| rot | rotation |
| exact | |
| epsilon |


{% extends 'layouts/base.html' %} {% from 'macros/forms.html' import horizontal_field %} {% block title %}Sponsorship Application - {{ super() }}{% endblock %} {% block content %}
By submitting a sponsorship application you are agreeing to the terms and conditions.


isNaN()
when checking for NaN
(use-isnan)In JavaScript, NaN
is a special value of the Number
type. It’s used to represent any of the “not-a-number” values represented by the double-precision 64-bit format as specified by the IEEE Standard for Binary Floating-Point Arithmetic.
Because NaN
is unique in JavaScript by not being equal to anything, including itself, the results of comparisons to NaN
are confusing:
NaN === NaN
or NaN == NaN
evaluate to falseNaN !== NaN
or NaN != NaN
evaluate to trueTherefore, use Number.isNaN()
or global isNaN()
functions to test whether a value is NaN
.
This rule disallows comparisons to ‘NaN’.
Examples of incorrect code for this rule:
/*eslint use-isnan: "error"*/
if (foo == NaN) {
// ...
}
if (foo != NaN) {
// ...
}
Examples of correct code for this rule:
/*eslint use-isnan: "error"*/
if (isNaN(foo)) {
// ...
}
if (!isNaN(foo)) {
// ...
}
This rule was introduced in ESLint 0.0.6.


To create a fill-in form, add 3 underlines where you want users to fill-in the blanks within your text. THE FILL-IN WILL AUTO EXPAND on the mobile device. User may email the form to themselves or any other email address.


Send us top 25 songs from Spotify for 25% off your next meal.
Send us most recently watched shows on Netflix and recieve a free Happy Meal.
Send us your most recent purchase history on Amazon and receive 30% off your next meal.


Validation demonstration
Client side form demonstration
*
Your name
Required element
*
Your email
A valid email address
*
Email confirm
*
A number from 10 - 50
A random number that you like
← Cancel and go back
Submit


Welcome to the Portfolio Webpage of Nam Hoon Kim, also known as "Alex". We all know Alex as a passionate and young adult who's interested in becoming the next big persona in the tech world, but nobody really knows about his background and upbringing.
Despite having majored in Mathematics, Alex knew in his heart that the theoretical concepts of mathematics alone cannot stand on its own. After graduation, Alex had a crisis in trying to find something to do with a math degree, ultimately failing to find a place to keep him happy. As a result, Alex decided to learn more coding and programming to supplement his mathematical background.
Here's the first big step into his newfound journey to becoming the next Mark Zuckerberg, Bill Gates, or Steve Jobs!
Feel free to provide some feedback, give suggestions, or to just say hello!


Image Form Validation
Price: $10/bottle:
Price: $8/bottle:
Price: $5/bottle:
Selection:
Shipping:
Pickup
US Postal:
FedEx
- Select -
selection One
selection Two


I am a freshmen enrolled full-time at Hartnell college and part-time at CSUMB, studying Computer Science with a focus on software development. I became interested in Computer Science after I took an "Intro to CS and Programming Fundamentals" course at Hartnell. I am passionate about giving back and I am currently a CSS-1 tutor at Hartnell, where I help students understand concepts using C++. Although I have not interned anywhere, I am open to any experience where I can show and gain my skills.
Tutor students during weekly office hours and assist in helping students as an embedded tutor during lab for a total of 5 hours a week in the Introduction to Programming course using C++. Position requires attention to detail, time management skills and a strong understanding of the concepts taught in the course.
Tutored 13 students for 14 hours each week throughout the summer semester in intermediate math up to Calculus I. Position requires a strong understanding of the material and excellent communication skills.
Participated in an intensive three week programming institute where CSUMB faculty and Google enginers taught participants how to develop web apps in HTML, CSS, JavaScript, Python, and Google AppEngine.
Selected as one of ten fellows to participate in a professional development program designed to prepare students for technical interviews to help them land their first summer internship and develop their leadership skills.
Attend weekly developmental/enriching workshops where I learn about programming fundamentals, career readiness, and college success.
Apart from being an aspiring Software Engineer, I enjoy playing soccer, painting, and photography.


resqdb package¶
Submodules¶
resqdb.Atalaia module¶
-
class
resqdb.Atalaia.
Calculation
(df, start_date=None, end_date=None)[source]¶ Bases:
resqdb.Atalaia.Filtration
-
get_afib_discharged_with_anticoagulants
()[source]¶ The function calculating number of patients who have been discharged with prescribed anticoagulants with aFib. The results are merged with the dataframe containing resulted statistic!
-
get_ct_mri
()[source]¶ The function calculating number of patients with IS, TIA and ICH stroke who have undergone the CT/MRI. The results are merged with the dataframe containing resulted statistic!
-
get_dysphagia_screening
()[source]¶ The function calculating number of patients with IS and ICH stroke who have undergone the dysphagia screening. The results are merged with the dataframe containing resulted statistic!
-
get_hospitalized_in
()[source]¶ The function calculating number of patients who have been hospitalized in a dedicated stroke unit / ICU. The results are merged with the dataframe containing resulted statistic!
-
get_patients_discharged_with_antiplatelets
()[source]¶ The function calculating number of ischemic patients who have been discharged with prescribed antiplatelets. The results are merged with the dataframe containing resulted statistic!
-
get_recan_below
(dtn, dtg, top)[source]¶ The function checking if at least one from the pair of number is lesser then maximum.
Parameters: - dtn (int) – door to needle time value
- dtg (int) – door to groin time value
- top (int) – limit value
Returns: True if one from the pair is lesser then maximum, False otherwise.
-
get_recan_rate
()[source]¶ The function calculating number of ischemic patients treated by recanalization procedure. The results are merged with the dataframe containing resulted statistic!
-
get_recan_therapy
()[source]¶ The function calculating number of patients treated within 60/45 minutes by thrombolysis and within 90/60 by thrombectomy. The results are merged with the dataframe containing resulted statistic!
-
get_stats_df
()[source]¶ The function calculating the statistics.
Returns: stats_df – dataframe with calculated statistics
-
get_total_patients
()[source]¶ The function calculating total number of patients per site.
Returns: the temporary dataframe containing Site ID and total number of patients
-
-
class
resqdb.Atalaia.
CheckTimes
(df, start_date=None, end_date=None)[source]¶ Bases:
object
Class calculating hospital days using discharge date and hospital date.
This class provides some basic algorithms to fix hospital and discharge dates if calculated hospital days were > 300 or < 0.
Parameters: - df (dataframe) – preprocessed data
- start_date (date) – first date included in the dataframe
- end_date (date) – last date included in the dataframe
-
calculate_hospital_days
(discharge_date, hospital_date)[source]¶ Return difference in days between hospital date and discharge date.
Parameters: - discharge_date (date) – the discharge date
- hospital_date (date) – the hospital date
Returns: int – the number of days
-
filter_null_dates
()[source]¶ Filter out null discharge dates and null hospital dates.
Returns: dataframe – the filtered dataframe
-
fix_negative_hospital_days
(discharge_date, hospital_date)[source]¶ Fix discharge date or hospital date if hospital days were < 0 or > 300.
Parameters: - discharge_date (date) – the discharge date
- hospital_date (date) – the hospital date
Returns: the fixed hospital days, the fixed hospital date, the fixed discharge date
-
class
resqdb.Atalaia.
Filtration
(df, start_date=None, end_date=None)[source]¶ Bases:
resqdb.Atalaia.CheckTimes
Class filtrating dataframe by discharge date.
-
filter_by_date
()[source]¶ Filter dataframe by discharge date. The start date and end date were defined in
resqdb.Atalaia.CheckTimes
class.Returns: the filtered dataframe
-
-
class
resqdb.Atalaia.
FormatStatistic
(df, path)[source]¶ Bases:
object
Class generating formatted excel file containing the calculated statistics!
Parameters: - df (dataframe) – the dataframe with calculated statistics
- path (str) – the path where the output file should be saved
-
class
resqdb.Atalaia.
GeneratePreprocessedData
(df, path)[source]¶ Bases:
object
Class generating preprocessed data in the excel format containing calculated statistics with intermediate columns!
Parameters: - df (dataframe) – the dataframe with calculated statistics
- path (str) – the path where the output file should be saved
resqdb.Calculation module¶
Created on Thu Jul 09 13:28:05 2017
@author: Marie Jankujova
-
class
resqdb.Calculation.
ComputeStats
(df, country=False, country_code='', comparison=False, patient_limit=0)[source]¶ Bases:
object
The class calculating the general statistics from the preprocessed and filtered data.
Parameters: - df (dataframe) – the dataframe containing preprocessed data
- country (bool) – the results for whole country included in the statistics
- country_code (str) – the country code used in the names of output files
- comparison (bool) – the value saying if it is comparative statistics
- patient_limit – the number of patients used as limit when evaluating angels awards
-
class
resqdb.Calculation.
FilterDataset
(df, country=None, date1=None, date2=None)[source]¶ Bases:
object
The class filtrating the dataframe by date or by country.
Parameters: - df (dataframe) – the dataframe containing preprocessed data
- country (str) – the country code to be included in the data
- date1 (date) – the first date included in the filtered dataframe
- date2 (date) – the last date included in the filtered dataframe
resqdb.CalculationSK module¶
-
class
resqdb.CalculationSK.
ComputeStats
(df, country=False, country_code='', comparison=False)[source]¶ Bases:
object
The class calculating the statistics from Slovakia data.
Parameters: - df (pandas dataframe) – the dataframe with preprocessed data
- country (bool) – True if country should be included as site into results
- country_code (str) – the country code of country
- comparison (bool) – True if comparison statistic is generated
-
class
resqdb.CalculationSK.
Connection
(nprocess=1)[source]¶ Bases:
object
The class connecting to the database and exporting the data for the Slovakia.
Parameters: nprocess (int) – number of processes -
config
(section)[source]¶ The function reading and parsing the config of database file.
Parameters: section (str) – the name of the section in database.ini file Returns: the dictionary with the parsed section values Raises: Exception
-
connect
(sql, section, nprocess, df_name=None)[source]¶ The function connecting to te database.
Parameters: - sql (str) – the sql query
- section (str) – the section from the database.ini
- nprocess (int) – the number of processes run simultaneously
- df_name (str) – the name of the dataframe used as key in the dictionary
Raises: Exception
-
prepare_df
(df, name)[source]¶ The function preparing the raw data from the database to be used for statistic calculation. The prepared dataframe is entered into dict_df and the name is used as key.
Parameters: - df (pandas dataframe) – the raw dataframe exported from the database
- name (str) – the name of the database
-
-
class
resqdb.CalculationSK.
FilterDataset
(df, country=None, date1=None, date2=None)[source]¶ Bases:
object
The class filtering preprocessed data by country or by date.
Parameters: - df (pandas dataframe) – the preprocessed dataframe
- country (str) – the country code of country included in the resulted dataframe
- date1 (date object) – the first date included in the filtered dataframe
- date2 (date object) – the last date included in the filtered dataframe
-
class
resqdb.CalculationSK.
GenerateFormattedAngelsAwards
(df, report=None, quarter=None, minimum_patients=30)[source]¶ Bases:
object
This class generate formatted statistics only for angels awards.
Parameters: - df (pandas dataframe) – the dataframe with angels awards statistics
- report (str) – the type of report, eg. quarter
- quarter (str) – the type of the period, eg. Q1_2019
-
class
resqdb.CalculationSK.
GenerateFormattedStats
(df, country=False, country_code=None, split_sites=False, site=None, report=None, quarter=None, comp=False)[source]¶ Bases:
object
The class generating the formatted statistics in Excel format. Angels Awards columns are colored based on the meeting of the condition.
Parameters: - df (pandas dataframe) – the dataframe with calculated statistics
- country (bool) – True if country should be included as site
- country_code (str) – the code of country used in filenames
- split_sites (bool) – True if the reports should be generated per sites
- site (str) – the site code
- report (str) – type of the report, eg. quarter
- quarter (str) – type of the period, eq. Q1_2019
- comp (bool) – True if the comparison reports are calculated
-
class
resqdb.CalculationSK.
GeneratePreprocessedData
(df, split_sites=False, site=None, report=None, quarter=None, country_code=None)[source]¶ Bases:
object
The class generating the preprocessed data and legend data in the excel file.
Parameters: - df (pandas dataframe) – the preprocessed data dataframe
- split_sites (bool) – True if for each site should be generated individual reports including whole country
- site (str) – site ID
- report (str) – the type of the report (quater, year, half)
- quarter (str) – the type of the period (Q1_2019, H1_2019, …)
-
convert_to_string
(format)[source]¶ The function converting the date, timestamp or time to the string.
Parameters: - datetime (date/timestamp/time) – the date, timestamp or time value to be converted
- format (the string) – the format of the date, timestamp or time
Returns: the datetime argument in the string
resqdb.CheckData module¶
File name: CheckData.py Package: resq Written by: Marie Jankujova -<EMAIL_ADDRESS>on 11-2017 Version: v1.0
-
class
resqdb.CheckData.
CheckData
(df, nprocess=None)[source]¶ Bases:
object
The class checking the dates and times in the dataframe.
Parameters: - df (pandas dataframe) – the dataframe containing the raw data
- nprocess (int) – the number of processes to be run simultaneously
-
get_preprocessed_data
(df, n=None, name=None)[source]¶ The function preparing the preprocessed data from the raw data.
Parameters: - df (pandas dataframe) – the dataframe with the raw data
- n (int) – the number of the process if more processes are run simultaneously
- name (str) – the name of dataframe used as key in the dictionary
Returns: preprocessed data if one process has been run
-
time_diff
(visit_date, hospital_date)[source]¶ The function calculating the difference in minutes between hospital date and visit date.
Parameters: - visit_date (the timestamp) – the last seen normal date
- hospital_date (the timestamp) – the date of hospitalization
Returns: the difference between two timestamps
resqdb.Connection module¶
-
class
resqdb.Connection.
Connection
(nprocess=1, data='resq')[source]¶ Bases:
object
The class connecting to the database and exporting the data for the Slovakia.
Parameters: - nprocess (int) – number of processes
- data (str) – the name of data (resq or atalaia)
-
check_data
(df, nprocess)[source]¶ The function calling the CheckData object. The dates and times are checked and if they are incorrect, they are fixed.
Parameters: - df (pandas dataframe) – the raw dataframe
- nprocess (int) – the number of processes run simulataneously
Returns: the dataframe with preprocessed data
-
config
(section)[source]¶ The function reading and parsing the config of database file.
Parameters: section (str) – the name of the section in database.ini file Returns: the dictionary with the parsed section values Raises: Exception
-
connect
(sql, section, nprocess, df_name=None)[source]¶ The function connecting to te database.
Parameters: - sql (str) – the sql query
- section (str) – the section from the database.ini
- nprocess (int) – the number of processes run simultaneously
- df_name (str) – the name of the dataframe used as key in the dictionary
Raises: Exception
-
fix_glucose
(value)[source]¶ The function fixing the glucose value. The issue is that users are entering glucose with comma or dot as seprator. Sometimes, also nonsense appears.
Parameters: value (str) – the entered value in the glucose field Returns: fixed number
-
get_ctmri_delta
(hosp_time, ct_time)[source]¶ The function calculating door to CT date time in minutes.
Parameters: - hosp_time (time) – the hospitalization time
- ct_time (time) – the time when CT/MRI has been performed
Returns: 1 if datetime > 0 and < 60, 2 if results > 60 else -2
-
prepare_atalaia_df
(df)[source]¶ The function preparing the atalaia dataframe if data is equal to atalaia. The column names are renamed.
Parameters: df (pandas dataframe) – the raw data exported from the database Returns: the prepared dataframe
-
prepare_df
(df, name)[source]¶ The function preparing the raw data from the database to be used for statistic calculation. The prepared dataframe is entered into dict_df and the name is used as key.
Parameters: - df (pandas dataframe) – the raw dataframe exported from the database
- name (str) – the name of the database
resqdb.FormatData module¶
File name: FormatData.py Package: resq Written by: Marie Jankujova -<EMAIL_ADDRESS>on 03/2019 Version: v1.0 Version comment: This script is used to generate formatted preprocessed data, presentations or excel files.
-
class
resqdb.FormatData.
GenerateFormattedAngelsAwards
(df, report=None, quarter=None, minimum_patients=30)[source]¶ Bases:
object
Class generating formatted excel file containing only Angels Awards results. !
Parameters: - df (pandas dataframe) – the dataframe with preprocessed data
- report (str) – the type of the report, eg. quarter
- quarter (str) – the type of the period, eg. H1_2018
- minimum_patients (int) – the minimum number of patients sites need to met condition for total patients
-
class
resqdb.FormatData.
GenerateFormattedStats
(df, country=False, country_code=None, split_sites=False, site=None, report=None, quarter=None, comp=False, minimum_patients=30)[source]¶ Bases:
object
Class generating formatted excel file containing all general statistics including formatted Angels Awards results. !
Parameters: - df (pandas dataframe) – the dataframe with preprocessed data
- country (bool) – True if country is included in the reports as site
- country_code (str) – the country code
- split_sites (bool) – True if preprocessed data should be generated per site
- site (str) – the site ID
- report (str) – the type of the report, eg. quarter
- quarter (str) – the type of the period, eg. H1_2018
- comp (bool) – True if the comparison calculation is in statistics
- minimum_patients (int) – the minimum number of patients sites need to met condition for total patients
-
class
resqdb.FormatData.
GeneratePreprocessedData
(df, split_sites=False, site=None, report=None, quarter=None, country_code=None, csv=False)[source]¶ Bases:
object
Class generating preprocessed data in the excel format containing calculated statistics with intermediate columns!
Parameters: - df (pandas dataframe) – the dataframe with preprocessed data
- split_sites (bool) – True if preprocessed data should be generated per site
- site (str) – the site ID
- report (str) – the type of the report, eg. quarter
- quarter (str) – the type of the period, eg. H1_2018
- country_code (str) – the country code
- csv (bool) – True if preprocessed data were read from csv
resqdb.GenerateComparisonPresentation module¶
File name: GenerateComparisonPresentation.py Package: resq Written by: Marie Jankujova -<EMAIL_ADDRESS>on 11-2018 Version: v1.0 Version comment: The first version of script which generate comaparison into presentation in PPTX format. Description: This script is used to generate comparison charts into presentation.
-
class
resqdb.GenerateComparisonPresentation.
GenerateCountriesCompGraphs
(ndf, presentation, column_name, title, sldf=None, subtitle='', graph_type=None, number_of_series=0, legend=None, samples=None)[source]¶ Bases:
object
The class generating comparison graphs in presentation for nationally samples vs. site samples.
Parameters: - ndf (pandas dataframe) – the calculated statistics for the national samples
- presentation (Presentation object) – the opened presentation document
- column_name (str) – the name of column to be included in the graph
- title (str) – the title of the slide
- sldf (pandas dataframe) – the calculated statistics for the site samples, can be None if Total Patients graph is generated
- subtitle (str) – the subtitle of the slide
- graph_type (str) – the type of graph to be generated (normal barplot or stacked barplot)
- number_of_series (int) – the number of columns included in the stacked barplot
- legend (list) – the list of values in the legend
- samples (list of string) – the list of countries which should be displayed with different color
-
class
resqdb.GenerateComparisonPresentation.
GenerateCountriesCompPresentation
(ndf, sldf, name='', samples=[])[source]¶ Bases:
object
The class creating presentation with the comparison between national samples and site samples in one period.
Parameters: - ndf (pandas dataframe) – the calculated statistics for the national samples
- sldf (pandas dataframe) – the calculated statistics for the site samples
- name (str) – the name of the period, eg. 2017
- samples (list of string) – the list of countries which should be colored by different color in the main graphs
-
class
resqdb.GenerateComparisonPresentation.
GeneratePeriodCompGraph
(df, presentation, column_name, title, subtitle='', number_of_series=0, legend=None)[source]¶ Bases:
object
The class generating comparison graphs for given periods .
Parameters: - df (pandas dataframe) – the temporary dataframe created in
resqdb.GenerateComparisonPresentation.GeneratePeriodCompPresentation
class - presentation (Presentation object) – the presentation opened in
resqdb.GenerateComparisonPresentation.GeneratePeriodCompPresentation
class - column_name (str) – the name of column which data should be shown in the graph
- title (str) – the title of the graph
- subtitle (str) – the subtitle of the graph
- number_of_series (int) – the number of columns to be shown (stacked graphs)
- legend (list of strings) – the legend if the graph is stacked
- df (pandas dataframe) – the temporary dataframe created in
-
class
resqdb.GenerateComparisonPresentation.
GeneratePeriodCompPresentation
(ndf1, ndf2, name1, name2)[source]¶ Bases:
object
The class generating comparison graphs for nationally samples between two periods of times.
Parameters: - ndf1 (pandas dataframe) – the dataframe containing calculated statistics for the first period
- ndf2 (pandas dataframe) – the dataframe containing calculated statistics for the second period
- name1 (str) – the name of the 1st period, eg. 2017
- name2 (str) – the name of the 2nd period, eg. 2017
-
class
resqdb.GenerateComparisonPresentation.
GenerateYearsCompGraphs
(presentation, df, df1=None, df2=None, df3=None, title='', titles=None, graph_types=None, legends=[], outcome=False)[source]¶ Bases:
object
The class generating graphs into presentation for country per years. If only one dataframe is provided than one graph is created on slide, two graphs is two dataframes are provided etc.
Parameters: - presentation (Presentation object) – the opened presentation document
- df (pandas dataframe) – dataframe containing calculated statistics
- df1 (pandas dataframe) – 2nd dataframe containing calculated statistics
- df2 (pandas dataframe) – 3rd dataframe containing calculated statistics
- df3 (pandas dataframe) – 4th dataframe containing calculated statistics
- title (str) – the title of the slide
- titles (list) – the titles of each graph
- graph_types (list) – the list of types of graphs
- legends (nested list) – the nested list containing lists of legends
- outcome (bool) – True if outcome calculation should be included in the presentation
-
class
resqdb.GenerateComparisonPresentation.
GenerateYearsCompPresentation
(df, name)[source]¶ Bases:
object
The class creating presentation with graphs representing country comparison through all years in the dataset (eg. 2016, 2017, 2018, 2019).
Parameters: - df (pandas dataframe) – the dataframe with calculated statistics per years or period
- name (str) – the name of the presentation
resqdb.GenerateGraphs module¶
File name: GenerateGraphs.py Package: resq Written by: Marie Jankujova -<EMAIL_ADDRESS>on 11-2017 Version: v1.0 Version comment: The first version of script which is used to generate charts in the PPTX format. Description: This script is used to generate PPTX file from the dataframe with computed statistics. This script is used by class GeneratePresentation.py. As a result, the presentation with chart is produced.
-
class
resqdb.GenerateGraphs.
GenerateGraphs
(dataframe, presentation, title, column_name, graph_type=None, number_of_series=0, legend=None, country=None)[source]¶ Bases:
object
The class generating presentation with graphs for general reports.
Parameters: - dataframe (pandas dataframe) – the dataframe with calculated statistics
- presentation (Presentation object) – the opened presentation document
- title (str) – the title of the slide
- column_name (str) – the column name from the dataframe to be shown in the graph
- graph_type (str) – the type of graph to be generated
- number_of_series (int) – the number of columns to be shown in the stacked barplot
- legend (list) – the list of names to be used in the legend in the stacked barplot
- country (str) – the country name used in the first slide
resqdb.GenerateGraphsCZ module¶
File name: GenerateGraphs.py Package: resq Written by: Marie Jankujova -<EMAIL_ADDRESS>on 11-2017 Version: v1.0 Version comment: The first version of script which is used to generate charts in the PPTX format. Description: This script is used to generate PPTX file from the dataframe with computed statistics. This script is used by class GeneratePresentation.py. As a result, the presentation with chart is produced.
-
class
resqdb.GenerateGraphsCZ.
GenerateGraphs
(dataframe, presentation, title, column_name, graph_type=None, number_of_series=0, legend=None, country=None)[source]¶ Bases:
object
This class is used to generate our typical presentation with graphs.
- Arguments:
- dataframe - dataframe with calculated statistics presentation - opened pptx document title - name of slide column_name - name of column name which should be used in graph (for more columns, the first column from all of them) graph_type - set which graph should be generated (normal, stacked or grouped) (default = normal) number_of_series - set number of series of graphs - this value is equal to length of legend (default = 0) legend - list of legend names (default = None) country - name of country (if dataset was filtered based on country) (default = None)
resqdb.GenerateNationalComparisonGraphs module¶
File name: GenerateNationalComparisonGraphs.py Package: resq Written by: Marie Jankujova -<EMAIL_ADDRESS>on 02-2019 Version: v1.0 Version comment: The first version of script which create national comaprison reports. Description: This script is used to call class GenerateGraphs and produce graphs into presentation.
-
class
resqdb.GenerateNationalComparisonGraphs.
GenerateNationalComparisonGraphs
(df, fdf, outcome=None, country=False, country_code=None, split_sites=False, site=None, report=None, quarter=None)[source]¶ Bases:
object
The class generating the presentation with graphs for national comparison reports.
Parameters: - df (pandas dataframe) – the dataframe with calculated statistic for the period of time
- fdf (pandas dataframe) – the dataframe with calculated comparison statistics eg. 2016, 2017, 2018, etc.
- outcome (pandas dataframe) – the dataframe with outcome results (default: None)
- country (bool) – True if country should be included in the results as site
- country_code (str) – the country code (default: None)
- split_sites (bool) – True if graphs for each site should be generated seperately
- site (str) – the site ID
- report (str) – the type of the report eg. quarter
- quarter (str) – the type of the period eg. Q1_2019
resqdb.GeneratePresentation module¶
File name: GeneratePresentation.py Package: resq Written by: Marie Jankujova -<EMAIL_ADDRESS>on 11-2017 Version: v1.0 Version comment: The first version of script which calls class GenerateGraphs and create graphs into presentation. Description: This script is used to call class GenerateGraphs and produce graphs into presentation.
-
class
resqdb.GeneratePresentation.
GeneratePresentation
(df, country=False, country_code=None, split_sites=False, site=None, report=None, quarter=None)[source]¶ Bases:
object
The class generating the general presentation for countries and sites.
Parameters: - df (pandas dataframe) – the dataframe with calculated statistics
- country (bool) – True if country is included in the statistics as site
- country_code (str) – the country code
- split_sites (bool) – True if presentation should be generated per sites seperately
- site (str) – the site code
- report (str) – the type of the report eg. quarter
- quarter (str) – the type of the period eg. Q1_2019
resqdb.Reports module¶
Created on May 20, 2019
@author: Marie Jankujova
-
class
resqdb.Reports.
GenerateGraphs
(df, presentation, title, column_name, country_name, axis_name=None, coloring=False, region=False, incorrect=False, maximum=0, content=None)[source]¶ Bases:
object
The class generating graphs into presentation and called inside the
resqdb.Reports.GeneratePresentation
.Parameters: - df (pandas dataframe) – the dataframe with calculated statistics
- presentation (Presentation object) – the opened document (pptx)
- title (str) – the title of the slide
- column_name (str) – the name of column which should be used in the graph (for stacked graph represent the first column to get index where the data included in the graph starts)
- country_name – the country name
- axis_name (str) – the label of x-axis
- coloring (bool) – True if rows should be colored by number, else False
- region (bool) – True if region graphs should be generated (coloring issue)
- incorrect (bool) – True if graphs displaying the incorrect times are generated
- maximum (int) – maximum value of x-axis for some graph
- content (list) – the small guide text displayed on the slide next to graph, each paragraphs is new value in list
-
class
resqdb.Reports.
GeneratePresentation
(df, year, month, country)[source]¶ Bases:
resqdb.Reports.Reports
The class generating graphs in the presentation.
-
class
resqdb.Reports.
Reports
(df, year, month, country)[source]¶ Bases:
object
The class generating the SITS-like reports for recanalization procedure.
Parameters: - df (pandas dataframe) – the preprocessed data
- year (int) – the year for which reports are generated
- month (int) – the last month to be included in the calculation
- country (str) – the country code (only CZ for now)
-
calculate_statistic_per_region
()[source]¶ The function calculating the result statistic for recanalization procedures per regions.
-
calculate_thrombectomy
()[source]¶ The function calculating the result statistic for patients who have recieved the thrombectomy.
-
calculate_thrombolysis
()[source]¶ The function calculating the result statistic for patients who have recieved the thrombolysis.
-
count_patients
(df, statistic)[source]¶ The function calculating the number of patients grouped by Protocol ID.
Parameters: - df (pandas dataframe) – the dataframe with preprocessed data
- statistic (pandas dataframe) – the dataframe with calculated statistics
Returns: the column with patient numbers
-
filter_dataframe
()[source]¶ The function filtering the preprocessed data for each month.
Returns: the dictionary of filtered dataframes
-
get_incorrect_times
(admission_time, recan_time, maximum)[source]¶ The function checking if time was incorrectly entered. Based on negative values, higher values than realistic value or zero value.
Parameters: - admission_time (time) – the time of the admission/hospitalization
- recan_time (time) – the time of recanalization procedures (needle time/groin time)
- maximum (int) – the realistic time for the recanalizaiton procedure
Returns: True if the condition was not met
-
get_region
(site_id)[source]¶ The function returning the region based on Site ID.
Parameters: site_id (str) – the site ID Returns: the name of the region
resqdb.XmlSplitter module¶
-
class
resqdb.XmlSplitter.
XmlSplitter
(xml_file, nprocess=1)[source]¶ Bases:
object
Call this module to convert XML file with data from forms in the combined csv file.
-
convert_xml_to_df
(root, xmlns, openclinica, lstudy, n)[source]¶ Find each element “ClinicalData” in xml file and converted each subject to the row in the dataframe. If two versions of the form was filled, select IVT_TBY instead of RESQv2.0, and select RESQv2.0 instead of RESQv1.2.
- Params:
- root: The root of xml file. xmlns: The base schema. openclinica: The base schema for openclinica.
- Returns:
- A new converted dataframe.
-
get_items
(root, xmlns, openclinica)[source]¶ Get all columns names in the xml file, to each column name get shorten name, version of form and comment.
- Params:
- root: The root of xml file. xmlns: The base schema. openclinica: The base schema for openclinica.
- Returns:
- New dictionary with all columns as keyword.
-
get_number_of_patient_per_site
(root, xmlns, study_ids)[source]¶ Get list of sites sorted by number of sites.
-
get_root
(xml_file)[source]¶ Get root of xml file and additional necessary values (schema and openclinica link).
-
get_studies
(root, xmlns)[source]¶ Get all studies in xml file, to each study also assign study name and protocol ID.
- Params:
- root: The root of xml file. xmlns: The base schema.
- Returns:
- New dictionary with all studies as keyword.
-
get_study_oids
(root, xmlns)[source]¶ Get all Study OIDs present in data.
- Params:
- root: The root of xml file. xmlns: The base schema.
- Returns:
- List of available IDs.
-
split_list
(data, total_patients, parts=2)[source]¶ Return number of lists equaled to processes and site ids in the list. Each process will get some sites.
-


Gateway
BOT
05-Dec-18 02:12 AM
[dscrdvrsc] <bishop> 50% POS plus dPOW, I'm not concerned about the security side as would otherwise be the case
[dscrdvrsc] <miketout> it is FUD, plain and simple, and it claims there is a problem, when that is not the issue. he's burning resources and costing the community time better spent solving issues. he's the definition of a troll at this point
[dscrdvrsc] <miketout> it is a LIE to say the network has "been taken over"
[dscrdvrsc] <bishop> the cost of entry to POW mine Verus pre-FPGA was a low bar
[dscrdvrsc] <miketout> total bullshit
[dscrdvrsc] <miketout> that implies some security issue, and he knows it
[dscrdvrsc] <miketout> this is not about me. this is about him lying to harm the project
[dscrdvrsc] <bishop> do FPGA miners make up more than half of the pow portion of verus
[dscrdvrsc] <bishop> the answer is yes
[dscrdvrsc] <bishop> for about $300-$400, you could get over 1GH between a 1700x and a GPU
[dscrdvrsc] <bishop> now, there is no point
[dscrdvrsc] <miketout> there is no way you can say they have taken over the network, and that is what he is implying. if you think this is good for the community or project in any way, please explain how
(edited)
[dscrdvrsc] <bishop> they have taken over the pow portion
[dscrdvrsc] <Badfish> I think with any project, FPGAs are inevitable. But the method of discussing this seems inappropriate and bad for the community
[dscrdvrsc] <miketout> exactly
[dscrdvrsc] <miketout> BS, and a malefactor of the community
[dscrdvrsc] <bishop> they have taken over the pow portion of verus, how is that inaccurate?
[dscrdvrsc] <bishop> sure, it's a bit misleading because it leaves out POS
[dscrdvrsc] <miketout> sorry @bishop it's strange for someone in the community to be an apologist for this
[dscrdvrsc] <Cruz> So how is it contructive, for a dev in the same ecosystem, to come in here and make a private disagreement public---and then go on Twitter and talk shit?  God damn
[dscrdvrsc] <miketout> no one who has an interest in Verus doing well would do or support such obvious spreading of FUD
[dscrdvrsc] <bishop> so if it was revised to specify the pow portion it would still be FUD?
[dscrdvrsc] <miketout> i am not going to engage, but it wouldn't be hard
[dscrdvrsc] <Cruz> I'm not trying to argue for or against, the statements...
I'm saying just what has happened, is some silly shit..
Is it not?
[dscrdvrsc] <Cruz> You can't do this is your Professional workplace...
Wtf is this
[dscrdvrsc] <Badfish> causing fear, uncertainty, and doubt @bishop
[dscrdvrsc] <bishop> again, if it was clarified to be the pow portion, how is it remotely FUD?
[dscrdvrsc] <miketout> i'm not even going to have the discussion. as @Badfish said, this approach is childish, attention seeking, and harmful to people making progress. i'm stepping off for a bit until more sense is conveyed. this is a lowly troll effort to smear, nothing else.
(edited)
[dscrdvrsc] <Badfish> Thats exactly what the tweet is doing
[dscrdvrsc] <bishop> maybe I am missing what the big deal is about the twitter post. It lacks some clarity, but completely accurate for the pow side of things
[dscrdvrsc] <Cruz> @Badfish He's entitled to his own opinion.
[dscrdvrsc] <Badfish> That part is true
[dscrdvrsc] <Badfish> But its not constructuive
[dscrdvrsc] <bishop> if there is more, I probably missed it
[dscrdvrsc] <Badfish> for the communityt
[dscrdvrsc] <Cruz> @bishop Hey, you're right. Now what?
[dscrdvrsc] <miketout> maybe people should go spread panic about every issue that every project has under control. it's strange to understand where you might be coming from @bishop
[dscrdvrsc] <Cruz> Let's lay it all out... What gives @bishop
[dscrdvrsc] <bishop> it's strange you seem so against hearing community members voicing their issue with with FPGAs on the network
[dscrdvrsc] <bishop> is it not a community coin?
[dscrdvrsc] <bishop> do none of the users have any input?
[dscrdvrsc] <miketout> we have two options, which is more than most coins would have for good reason. i'm going to take a break for a few
[dscrdvrsc] <Cruz> @bishop Of course the users has input ...
[dscrdvrsc] <Cruz> Why go about it like this?
[dscrdvrsc] <Cruz> This came off more as an attack
[dscrdvrsc] <bishop> I think you're reading way too much into it
[dscrdvrsc] <bishop> again, this is in reference to the tweet I saw
[dscrdvrsc] <Cruz> @bishopAnd that's it?
[dscrdvrsc] <miketout> @bishop your argument seems intentionally naive and possibly dishonest. i'm taking a break
[dscrdvrsc] <bishop> oh god, so now I'm fuding, christ mike
[dscrdvrsc] <Cruz> He just said he's taking a break
[dscrdvrsc] <Cruz> Take a breather guys
[dscrdvrsc] <miketout> do you not see how that tweet has no positive and is only harmful to every single person who actually has an interest in the right thing happening?
[dscrdvrsc] <bishop> perhaps many aren't in discord and are aware of what is going on
[dscrdvrsc] <bishop> come to think of it, no updates have been provided on BCT
(edited)
[dscrdvrsc] <miketout> you seem to argue that it is defensible as something good
[dscrdvrsc] <bishop> letting users or potential users aware of the current situation?
[dscrdvrsc] <Cruz> @bishop Here in the announcements?
[dscrdvrsc] <bishop> not everyone is in discord
[dscrdvrsc] <Cruz> He wrote a lengthy description
[dscrdvrsc] <bishop> people should be aware to know
[dscrdvrsc] <Cruz> It's the only outlet for Verus
[dscrdvrsc] <bishop> BCT, the official twitter, etc?
[dscrdvrsc] <Cruz> We aren't on Telegram
[dscrdvrsc] <miketout> i have been working on the agreement. there is no secret about the value of mining on any device, and there is no emergency or security issue. spreading unknowns when we will know quite soon is basically spreading exactly fear, uncertainty, and doubt. how does it help?
[dscrdvrsc] <bishop> Neither have been updated to show what is going on in the community around this issue
(edited)
[dscrdvrsc] <miketout> they are not even on the network right now, and may not be until we actually have a reason to be quite excited about the future. i'd get much further without people who are supposed to be devs on other coins trolling Verus and me
[dscrdvrsc] <bishop> They will be back when their hosting is back online on the 6th
[dscrdvrsc] <bishop> then you will see the nethash 25-30TH again
[dscrdvrsc] <bishop> Honestly, you should update both bitcointalk and your official twitter about what is going on so people or prospective users are aware
[dscrdvrsc] <bishop> that's all
[dscrdvrsc] <miketout> and we are talking to them and should be working on that, which is how we might get something good out of this for the community, not dealing with trolls trying to harm communication and decisionmaking
[dscrdvrsc] <bishop> discord is only one outlet
[dscrdvrsc] <Cruz> @bishop Does every project do this?
[dscrdvrsc] <Cruz> Write an official update about every situation they encounter? You are mad
[dscrdvrsc] <bishop> I would say this is a large enough situation to warrant in update on all forms of media
[dscrdvrsc] <Cruz> What are you getting, by doing this?
[dscrdvrsc] <bishop> A potential fork and weighing options should be put out there on all forums
[dscrdvrsc] <bishop> I'm not saying every little issue needs to be uniform across media
[dscrdvrsc] <bishop> but a fork is
[dscrdvrsc] <Badfish> What does any troll gain?
[dscrdvrsc] <bishop> I really hope I'm not being lumped into the troll category for voicing an opinion about keeping the community informed
[dscrdvrsc] <miketout> BS. it's communications 101, if you spread uncertainty, you spread FUD. we have things to say soon. nothing we say now helps anyone because they can do nothing until there are the options in front of us
[dscrdvrsc] <Cruz> All I know that there is more behind this, than can be seen at this moment
[dscrdvrsc] <bishop> A small update about the situation would have been welcomed to see on both twitter and BCT
[dscrdvrsc] <Cruz> Why haven't you mentioned this before Duke did all of this?
[dscrdvrsc] <bishop> unfortunately, Duke already did that for you
[dscrdvrsc] <Badfish> I didnt really see any update to be had
[dscrdvrsc] <Badfish> There is no imminent fork
[dscrdvrsc] <bishop> It will have to in some shape
[dscrdvrsc] <bishop> unless it is decided that CPU and GPU miners don't matter
[dscrdvrsc] <bishop> which is fine if that is what the ultimate community decision is
[dscrdvrsc] <Cruz> Why haven't you mentioned this before Duke did all of this? @bishop
[dscrdvrsc] <miketout> he attempted to harm the project, nothing more, and that should be recognize, IMO, just as we recognize when people contribute.
[dscrdvrsc] <bishop> try 10 hours ago @Cruz
(edited)
[dscrdvrsc] <Badfish> Let me ask this Bishop...Is the point to profit? or a quality, usefull project?
[dscrdvrsc] <bishop> I think a major selling point to verus is CPU and GPUs being on near level playing fields
[dscrdvrsc] <Cruz> @bishop Really? Okay
[dscrdvrsc] <bishop> I cannot think of another coin that can say that
[dscrdvrsc] <miketout> yes. we should make an update now, but that is just more make work, courtesy of Duke that only helps calm people he may have scared into realizing he spread incomplete, sensationalized FUD, not useful information


Use this menu option to save and name the active document. CrypTool displays the Save As dialog box so that you can specify a name for your document.
To save a document under its existing name and in its present directory, use the Save menu option.


--- layout: post status: publish published: true title: Array Segments author: display_name: Tomas Restrepo login: tomasr email<EMAIL_ADDRESS>url: http://winterdom.com/ author_login: tomasr author_email<EMAIL_ADDRESS>author_url: http://winterdom.com/ wordpress_id: 1020 wordpress_url: http://winterdom.com/2007/11/arraysegments date: '2007-11-15 07:13:35 +0000' date_gmt: '2007-11-15 07:13:35 +0000' categories: - ".NET" tags: [] comments: [] ---
The ArraySegment
I mean, honestly, without those, all ArraySegment does is saving you from passing a couple of parameters around, but doesn't make the code any simpler at all.


Drupal has two default states for content
Excerpt from the content outline:
1.d.iv.2.h The Contributor can submit the changes for approval.
We need more content states
Published
Unpublished
Review
Draft
Archive
What happens if you mark content as Draft?
Does the content get hidden from the user?
You need to be able to show a revision of content while working on a different revision
Exercise
Enable Workflow and Content Moderation
Add the necessary content states for GCR
Select the content types to apply workflow to
j
Have the class setup workflows for all content types they need it for
Workflow Permissions
Allow specific roles access to specific transitions
Have the class setup permissions
Excerpt from the content outline:
1.d.iv.2.h.iv The Contributor cannot revert changes once submitted for approval.
This functionality is not built in
You will need to write a custom module for this
Modify the Edit form for the state to add roles
Modify node_access so that contributors can't edit nodes in Review state
Create a node link on node View to transition state back to draft for editing
Out of scope for this training
Maybe day 3 topic??
I'll talk more about access control in a few minutes, after the break
Contributors Dashboard
Workbench module
Provides a page with views
Edits by User
Recent Content
Add your own views to this page
Content in a specific state
etc...
Exercise
Add "Content to Review" on dashboard
Views UI Crash Course
User Permissions
Masquerade
Views Concepts
Visual query builder within CMS
Display Format
Fields
Filters
Sort
Relationships
...bunch of other stuff too
Build the view
Ensure the correct permissions
Modify the Workbench configuration
Masquerade as the user


| 479 | (A) | late neuer ȝone laweles ledis laughe at hir harmes |
| 483 | (C) | And lette neuur þese laweles men . lawȝe at his harmes |
| 479 | (D) | lete neuere þes lawles ledis laugh at his harmys |
| 479 | (E) | & lat nat þese helle houndes . leyȝe at his harmes |
| (Ex) | ---- no text ---- | |
| 496 | (L) | lat neuer þis lawles ledis lauȝ at his harmys |
| 459 | (P) | Lat noght þis laules ledes laghe at his harmes |
| 477 | (U) | late neuer thise laweles ledes / laughen at his harmes |
| (V) | ---- no text ---- |


1 write to _commandRuntime
System.Management.Automation (1)
engine\MshCmdlet.cs (1)
250
_commandRuntime
= cmdlet.CommandRuntime as MshCommandRuntime;
4 references to _commandRuntime
System.Management.Automation (4)
engine\MshCmdlet.cs (4)
266
return
_commandRuntime
.PipelineProcessor.ExecutionFailed;
271
_commandRuntime
.PipelineProcessor.ExecutionFailed = value;
913
if (
_commandRuntime
!= null)
914
_commandRuntime
.ThrowIfStopping();


A RetroGit digest could not be generated for your account due to a GitHub authentication error. You may have revoked RetroGit's access (you can see this on your GitHub settings page). If you wish to grant it access again, use the button below:
{{template "email-footer"}}


Help the Salvos spread joy this Christmas
Adding just one extra item to your Christmas list for a child in need will help the Salvation Army make a difference to the lives of those less fortunate.
That is the message coming from Newcastle Permanent which is asking residents across the Hunter to chip in and support families doing it tough.
Donations for The Salvation Army's annual Christmas Appeal can be made at any of Newcastle Permanent's branches or head office and this year there is a focus on also including gifts for teenagers as well as small children.
The collection runs until Friday, December 20. Donation boxes are in all Newcastle Permanent branches and the head office on King Street, Newcastle West.


Massa says Formula E is the back up plan for F1 drivers
by Adam NewtonFormer F1 driver Felipe Massa says that F1 drivers on the fringe of the grid see Formula E as a back up plan if they fail to secure a seat in F1. The all-electric series features a number of recent F1 drivers, such as Stoffel Vandoorne, Jean-Eric Vergne and Brendon Hartley.
Even Alex Albon was set to race last season before Toro Rosso called him up to the F1 team, so Formula E really is a growing series and the former Sauber, Ferrari and Williams star says that more F1 drivers will make the move across.
He told The Mirror: “Formula E is doing exactly what needs to be done. It is growing.
“When a championship is growing and getting bigger and bigger, all the big names are interested. It was the only championship I was looking to come and race after Formula 1.”
“I concentrate on Formula E, because I believe in the future of Formula E more than I believe in the future of the other championship.
“I am sure that any driver that does not have the possibility to stay in Formula 1, they will try and come to Formula E. I am 100 per cent sure.
“Every driver here can race in Formula 1 and everyone here can be successful in Formula 1 in the end."


A Support Group for Depression and Anxiety
Listed below are therapists who can help you with your burden.


|
Elektra
0.8.24
|
Calling exported functions is a primary way for coordinating plugins in Elektra. Since some plugins encapsulate other plugins, exported functions from encapsulated plugins become unavailable.
Since encapsulating plugins cannot implement and forward calls for every function exported by encapsulated plugins a generic mechanism for function calls to these encapsulated plugins is needed.
Since some plugins also lazy-load encapsulated plugins the call mechanism is required to be able to defer these calls until the plugins are loaded.
For example when setting I/O bindings with elektraIoSetBinding()
the exported function setIoBinding
is called for all globally mounted plugins. Since global mounting is implemented using the "list" plugin which uses lazy-loading for its plugins the exported functions from the plugins are unavailable.
Other examples are the "dini" and "multifile" plugins which use multiple plugins to support different file formats. These plugins also "hide" functions exported by encapsulated plugins.
set
, open
, close
, ...). Callbacks can be used as return channel (see "Implications")getEncapsulatedPlugins
. This would break encapsulation and break lazy-loading since to return the encapsulated plugin handles they have to be loaded.Compatible plugins export a function called getInterfaces
. It returns a KeySet with well-known interface names like "notification" or "ioBinding" and the required functions (e.g. open
& close
for "notification" or set
for "ioBinding"). While normal plugins simply return their interfaces, encapsulating plugins collect interfaces from its plugins and combine them into a single KeySet.
The example below shows a KeySet from a plugin encapsulating two plugins "A" and "B". Both plugins implement the "notification" interface, plugin "B" also implements the "ioBinding" interface.
/notification/#0/open
: address of openNotification
of plugin "A"/notification/#0/close
: address of closeNotification
of plugin "A"/notification/#1/open
: address of openNotification
of plugin "B"/notification/#1/close
: address of closeNotification
of plugin "B"/ioBinding/#0/set
: address of setIoBinding
of plugin "B"The upside of this approach is that it makes encapsulating plugins transparent to the caller - it does not known whether the plugin encapsulates other plugins. This approach breaks lazy-loading since for combining all interfaces the plugins have to be loaded and their getInterfaces
functions have to be called.
Encapsulating plugins export a function called deferredCall
with the declaration void elektraDeferredCall (Plugin * plugin, char * name, KeySet * parameters)
. Encapsulating plugins shall save multiple deferred calls and call the exported functions specified by name
passing the parameters
KeySet when a plugin is initialized in the same order as received.
Plugins that support deferred calls shall have the following declaration for their functions void somePluginFunction (Plugin * plugin, KeySet * parameters)
. The calling developer is responsible for ensuring that the called functions have a compatible declaration. Encapsulated plugins that do not export a specified function name are omitted.
The solution allows to change encapsulating plugin implementations without breaking callers.
The called function receive their parameters via a KeySet.
While called functions could return data using the parameters
KeySet (or a separate KeySet) there is no defined moment when the data can be collected. Defining such a moment would break the lazy-loading constraint. It is recommended to use callbacks passed as parameters
. Callback function declarations are not limited by this decision.
int elektraInvokeFunctionDeferred (ElektraInvokeHandle * handle, const char * elektraPluginFunctionName, KeySet * ks)
which defers a call if the plugin exports deferredCall
.void elektraInvokeExecuteDeferredCalls (ElektraInvokeHandle * handle, ElektraDeferredCallList * list)
which executes deferred calls for a encapsulated plugin loaded with invoke.Utility functions that help with managing deferred calls would be nice:
ElektraDeferredCallList * elektraDeferredCallCreateList (void)
void elektraDeferredCallDeleteList (ElektraDeferredCallList * list)
int elektraDeferredCallAdd (ElektraDeferredCallList * list, char * name, KeySet * parameters)
void elektraDeferredCallsExecute (Plugin * plugin, ElektraDeferredCallList * list)


FEAR AND LOATHING IN LAS VEGAS
Director: Terry Gilliam Writers: Based on the book by Hunter S. Thompson. Screenplay by Terry Gilliam & Tony Grisoni, Tod Davies & Alex Cox Producers: Laila Nabulsi, Patrick Cassavetti, Stephen Nemeth
Characters: Johnny Depp - Raoul Duke Benicio Del Toro - Dr. Gonzo
Review:
This movie is not for everyone. It's important to get that out of the way at the outset. It's a strange, disturbing, confusing, and considerably offensive movie, and it's without question one of my all-time favorites.
When I first heard of this movie back before it was released in theaters, I was excited about it, though I'd never even heard of the book. I originally discovered it when I was trying to check up on whatever Terry Gilliam's new project might be. You might know him from any of a number of excellent movies he has directed including "12 Monkeys", "Brazil", and "The Fisher King". Anyway, I was very favorably surprised to find that this, his next movie, was going to star two of my favorite actors, Depp (go see "Donnie Brasco", "Ed Wood", and "Edward Scissorhands") and Del Toro ("The Usual Suspects" and many small but incredible roles).
Anyway, to the movie at hand. It is, simply put, about drugs. Slightly less simply put, it is "A Savage Journey to the Heart of the American Dream". The plot revolves around two compatriots, a doctor of journalism and his attorney, who are sent to Las Vegas to cover a motorcycle race for the magazine Raoul Duke (Depp) works for. This business trip (no pun intended) quickly turns into an extended orgy of drug use, mayhem, and (dare I say) hilarity. The movie is clearly a comedy, but there are many moments where the experience becomes oppressive -- too strange, too demented.
Like the book (which I rapidly bought and read after seeing the film), the movie is able to rapidly and seamlessly go from ridiculous humor to disturbing and uncomfortable strangeness to a really poetic and thought provoking narration. Actually, almost everything in the movie is word for word, image for image taken from the book. It's a very faithful reproduction.
As I said, it's definitely not something everyone would like, but I strongly urge everyone who thinks there is any chance they would like it to give it some serious thought.
- John Roberdeau -<EMAIL_ADDRESS>- http://www.dvdfuture.com/
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


STATUSBAR is a non-Interactive frame displaying a warcraft 3 model. Unlike Sprite it does not loop the animation but the current animationTime can be set using BlzFrameSetValue as % of Min/Max to AnimationTime. It is said "STATUSBAR" only supports 1s animations, sequzenzes after 1s are droped. This type is quite good createable with code only
BlzFrameSetSpriteAnimate birth = 0 death = 1 stand = 2 morph = 3 alternate = 4


simpleCount¶
$project will solve your problem of where to start with documentation, by providing a basic explanation of how to do it easily.
Look how easy it is to use:
import project # Get your stuff done project.do_stuff()
Getting Started¶
- Be awesome
- Make things faster
Design’s choices¶
- Issue Tracker: github.com/$project/$project/issues
- Source Code: github.com/$project/$project
Conception¶
If you are having issues, please let us know. We have a mailing list located at<EMAIL_ADDRESS>Informations¶
It will contains some variables
License¶
The project is licensed under the BSD license.


public class OpCVImage_using
extends android.support.v7.app.AppCompatActivity
| Constructor and Description |
|---|
OpCVImage_using() |
| Modifier and Type | Method and Description |
|---|---|
void |
backToMain(View view)
onClick method that takes in img_to_main_btn button view object
and finishes/closes activity_op_cvimage.xml view,
resumes activity_main.xml view
|
void |
canFilter(java.lang.String pictPath)
Canny filter method using OpenCV functions
method applies a canny filter to image
in attempt enhance image edges as it is converted to a binary image
method takes in the picture path to the selected image from
device image gallery and sets converted image to image view object
on screen
|
void |
dragModeViewSwitch(View view)
onClick method that takes in button view object
When drag_mode_switch_btn is clicked, changes widget/button
views visible on screen to display or remove zoom and pan buttons
This allows user to use multitouch functionality to zoom and pan
image, or use buttons to zoom and pan image
|
void |
imageDown(View view) |
void |
imageLeft(View view) |
void |
imageRight(View view) |
void |
imageUp(View view)
onClick methods that takes in button view objects that allows
the image on screen to be shifted based on directional button selected
img_up_btn, img_down_btn, img_left_btn, and img_right_btn
adding a constant value to the current x and y values
of where the image is located on screen, which will then
translate/shift where the image is located on screen
using setTranslationX and setTranslationY
|
void |
lapFilter(java.lang.String pictPath)
Laplacian filter method using OpenCV functions
method applies a laplacian filter to image
in attempt enhance image feature edges as binary image
method takes in the picture path to the selected image from
device image gallery and sets converted image to image view object
on screen
|
protected void |
onActivityResult(int requestCode,
int resultCode,
Intent data)
re-inflates activity_op_cvimage.xml after image is selected in from the device
image gallery by the user, and displays resulting image based after
image filters are applied
method takes in request code to identify which intent the callback is using,
resultCode from URI to ensure image will be returned, and intent including description
of action to be performed and passed in activity
|
protected void |
onCreate(Bundle savedInstanceState)
inflates activity_op_cvimage.xml and instantiates buttons and listeners
|
void |
onResume() |
boolean |
onTouchEvent(MotionEvent e)
onToucheEvent takes in motionEvent 'heard' and passes event to switch case to process
course of action based on event
always returns true
|
void |
sobANDcan(java.lang.String pictPath)
Combination Sobel and Canny filter method using OpenCV functions
method applies a combination of a sobel filter and canny filter to image
in attempt enhance image feature edges as binary image
method takes in the picture path to the selected image from
device image gallery and sets converted image to image view object
on screen
|
void |
sobFilter(java.lang.String pictPath)
Sobel filter method using OpenCV functions
method applies a sobel filter to image
in attempt enhance image feature edges as the image is converted to a binary image
method takes in the picture path to the selected image from
device image gallery and sets converted image to image view object
on screen
|
void |
zoomIn(View view)
onClick methods that takes in button view objects that changes
the scale factor of the image using constant
SCALE_CHANGE applied when zoom_in_btn or zoom_out_btn
is clicked
|
void |
zoomOut(View view) |
addContentView, closeOptionsMenu, dispatchKeyEvent, findViewById, getDelegate, getDrawerToggleDelegate, getMenuInflater, getResources, getSupportActionBar, getSupportParentActivityIntent, invalidateOptionsMenu, onConfigurationChanged, onContentChanged, onCreateSupportNavigateUpTaskStack, onDestroy, onKeyDown, onMenuItemSelected, onMenuOpened, onPanelClosed, onPostCreate, onPostResume, onPrepareSupportNavigateUpTaskStack, onSaveInstanceState, onStart, onStop, onSupportActionModeFinished, onSupportActionModeStarted, onSupportContentChanged, onSupportNavigateUp, onTitleChanged, onWindowStartingSupportActionMode, openOptionsMenu, setContentView, setContentView, setContentView, setSupportActionBar, setSupportProgress, setSupportProgressBarIndeterminate, setSupportProgressBarIndeterminateVisibility, setSupportProgressBarVisibility, setTheme, startSupportActionMode, supportInvalidateOptionsMenu, supportNavigateUpTo, supportRequestWindowFeature, supportShouldUpRecreateTask
dump, getLastCustomNonConfigurationInstance, getLifecycle, getSupportFragmentManager, getSupportLoaderManager, onAttachFragment, onBackPressed, onCreatePanelMenu, onLowMemory, onMultiWindowModeChanged, onNewIntent, onPause, onPictureInPictureModeChanged, onPrepareOptionsPanel, onPreparePanel, onRequestPermissionsResult, onResumeFragments, onRetainCustomNonConfigurationInstance, onRetainNonConfigurationInstance, onStateNotSaved, setEnterSharedElementCallback, setExitSharedElementCallback, startActivityForResult, startActivityFromFragment, startActivityFromFragment, startIntentSenderFromFragment, supportFinishAfterTransition, supportPostponeEnterTransition, supportStartPostponedEnterTransition, validateRequestPermissionsRequestCode
public void onResume()
onResume
in class android.support.v4.app.FragmentActivity
protected void onCreate(Bundle savedInstanceState)
onCreate
in class android.support.v7.app.AppCompatActivity
savedInstanceState
- public boolean onTouchEvent(MotionEvent e)
e
- protected void onActivityResult(int requestCode, int resultCode, Intent data)
onActivityResult
in class android.support.v4.app.FragmentActivity
requestCode
- resultCode
- data
- public void sobFilter(java.lang.String pictPath)
pictPath
- public void canFilter(java.lang.String pictPath)
pictPath
- public void lapFilter(java.lang.String pictPath)
pictPath
- public void sobANDcan(java.lang.String pictPath)
pictPath
- public void zoomIn(View view)
view
- public void zoomOut(View view)
public void imageUp(View view)
view
- public void imageDown(View view)
public void imageLeft(View view)
public void imageRight(View view)
public void dragModeViewSwitch(View view)
view
- public void backToMain(View view)
view
-


from datetime import datetime
from werkzeug.wrappers import Response
from werkzeug.http import http_date
from .http import codes, methods
Convenience function for checking for existent, callable methods
usable = lambda x, y: callable(getattr(x, y, None))
class ResourceMetaclass(type):
def __new__(cls, name, bases, attrs):
Create the new class as is to start. Subclass attributes can be
checked for in attrs
and handled as necessary relative to the base
classes.
new_cls = type.__new__(cls, name, bases, attrs)
If allowed_methods
is not defined explicitly in attrs, this
could mean one of two things: that the user wants it to inherit
from the parent class (if exists) or for it to be set implicitly.
The more explicit (and flexible) behavior will be to not inherit
it from the parent class, therefore the user must explicitly
re-set the attribute.
if 'allowed_methods' not in attrs or not new_cls.allowed_methods:
allowed_methods = []
for method in methods:
if usable(new_cls, method.lower()):
allowed_methods.append(method)
If the attribute is defined in this subclass, ensure all methods that are said to be allowed are actually defined and callable.
else:
allowed_methods = list(new_cls.allowed_methods)
for method in allowed_methods:
if not usable(new_cls, method.lower()):
raise ValueError('The {} method is not defined for the '
'resource {}'.format(method, new_cls.__name__))
If GET
is not allowed, remove HEAD
method.
if 'GET' not in allowed_methods and 'HEAD' in allowed_methods:
allowed_methods.remove('HEAD')
new_cls.allowed_methods = tuple(allowed_methods)
if not new_cls.supported_content_types:
new_cls.supported_content_types = new_cls.supported_accept_types
if not new_cls.supported_patch_types:
new_cls.supported_patch_types = new_cls.supported_content_types
return new_cls
Comprehensive Resource
class which implements sensible request
processing. The process flow is largely derived from Alan Dean's
status code activity diagram.
Section 2 of the HTTP/1.1 specification states:
The methods GET and HEAD MUST be supported by all general-purpose servers. All other methods are OPTIONAL;
The HEAD
handler is already implemented on the Resource
class, but
requires the GET
handler to be implemented. Although not required, the
OPTIONS
handler is also implemented.
Response representations should follow the rules outlined in Section 5.1.
Section 6.1 defines that GET
, HEAD
, OPTIONS
and TRACE
are
considered safe methods, thus ensure the implementation of these methods do
not have any side effects. In addition to the safe methods, PUT
and
DELETE
are considered idempotent which means subsequent identical requests
to the same resource does not result it different responses to the client.
Request bodies on GET
, HEAD
, OPTIONS
, and DELETE
requests are
ignored. The HTTP spec does not define any semantics surrounding this
situtation.
Typical uses of POST
requests are described in Section 6.5, but in most
cases should be assumed by clients as black box, neither safe nor idempotent.
If updating an existing resource, it is more appropriate to use PUT
.
[Section 7.2.1][5] defines that GET
, HEAD
, POST
, and 'TRACE' should have
a payload for status code of 200 OK. If not supplied, a different 2xx code may
be more appropriate.
class Resource(object):
__metaclass__ = ResourceMetaclass
Toggle this resource as unavailable. If True
, the service
will be unavailable indefinitely. If an integer or datetime is
used, the Retry-After
header will set. An integer can be used
to define a seconds delta from the current time (good for unexpected
downtimes). If a datetime is set, the number of seconds will be
calculated relative to the current time (good for planned downtime).
unavailable = False
If None
, the allowed methods will be determined based on the resource
methods define, e.g. get
, put
, post
. A list of methods can be
defined explicitly to have not expose defined methods.
allowed_methods = None
Enforce request rate limiting. Both rate_limit_count
and
rate_limit_seconds
must be defined and not zero to be active.
By default, the number of seconds defaults to 1 hour, but the count
is None
, therefore rate limiting is not enforced.
rate_limit_count = None
rate_limit_seconds = 60 * 60
If not None
, checks if the request entity body is too large to
be processed.
max_request_entity_length = None
If True
, PUT
and PATCH
requests are required to have a conditional
header for verifying the operation applies to the current state of the
resource on the server. This must be used in conjunction with either
the use_etags
or use_last_modified
option to take effect.
require_conditional_request = False
If True
, the ETag
header will be set on responses and conditional
requests are supported. This applies to GET, HEAD, PUT, PATCH
and DELETE requests.
use_etags = True
If True
, the Last-Modified
header will be set on responses and
conditional requests are supported. This applies to GET, HEAD, PUT,
PATCH and DELETE requests.
use_last_modified = False
Define a list of mimetypes supported for encoding response entity
bodies. Default to ('application/json',)
See also: supported_content_types
supported_accept_types = ('application/json',)
Define a list of mimetypes supported for decoding request entity bodies.
This is independent of the mimetypes encoders for request bodies.
Defaults to mimetypes defined in supported_accept_types
.
supported_content_types = None
Define a list of mimetypes supported for decoding request entity bodies
for PATCH
requests. Defaults to mimetypes defined in
supported_content_types
.
supported_patch_types = None
Every Resource
class can be initialized once since they are stateless
(and thus thread-safe).
def __call__(self, request, *args, **kwargs):
Initilize a new response for this request. Passing the response along the request cycle allows for gradual modification of the headers.
response = Response()
Process the request, this should modify the response
output = self.process(request, response, *args, **kwargs)
if output is not None:
response.data = output
return response
For composite resources, resource.apply
can be used on related resources
with the original request
.
def apply(self, request, *args, **kargs):
pass
def process(self, request, response, *args, **kwargs):
TODO keep track of a list of request headers used to determine the resource representation for the 'Vary' header.
The server does not need to be unavailable for a resource to be unavailable...
if self.check_service_unavailable(request, response):
response.status = codes.service_unavailable
return
Note that many services respond with this code when entities are unprocessable. This should really be a 422 Unprocessable Entity
if self.check_unauthorized(request, response):
response.status = codes.unauthorized
return
if self.check_forbidden(request, response):
response.status = codes.forbidden
return
This technically refers to a service-wide response for an unimplemented request method.
Both rate_limit_count
and rate_limit_seconds
must be none
falsy values to be checked.
if self.rate_limit_count and self.rate_limit_seconds:
if self.check_too_many_requests(request, response, *args, **kwargs):
response.status = codes.too_many_requests
return
if request.method == methods.options and 'OPTIONS' in self.allowed_methods:
return self.options(request, response)
if request.content_length:
if self.check_unsupported_media_type(request, response):
response.status = codes.unsupported_media_type
return
if self.max_request_entity_length:
if self.check_request_entity_too_large(request, response):
response.status = codes.request_entity_too_large
return
if self.check_method_not_allowed(request, response):
response.status = codes.method_not_allowed
return
if self.check_not_acceptable(request, response):
response.status = codes.not_acceptable
return
if self.check_not_found(request, response):
response.status = codes.not_found
return
if self.check_gone(request, response, *args, **kwargs):
response.status = codes.gone
return
Prevents the "lost udpate" problem and requires client to confirm
the state of the resource has not changed since the last GET
request. This applies to PUT
and PATCH
requests.
if self.require_conditional_request:
if request.method == methods.put or request.method == methods.patch:
if self.check_precondition_required(request, response, *args, **kwargs):
HTTP/1.1
response.headers['Cache-Control'] = 'no-cache'
HTTP/1.0
response.headers['Pragma'] = 'no-cache'
response.status = codes.precondition_required
return
Conditional requests applies to GET, HEAD, PUT, and PATCH.
For GET and HEAD, the request checks the either the entity changed
since the last time it requested it, If-Modified-Since
, or if the
entity tag (ETag) has changed, If-None-Match
.
if request.method == methods.put or request.method == methods.patch:
if self.check_precondition_failed(request, response, *args, **kwargs):
response.status = codes.precondition_failed
return
Check for conditional GET or HEAD request
if request.method == methods.get or request.method == methods.head:
if self.use_etags and 'if-none-match' in request.headers:
etag = self.get_etag(request, *args, **kwargs)
if request.headers['if-none-match'] == etag:
response.status = codes.not_modified
return
if self.use_last_modified and 'if-modified-since' in request.headers:
modified = self.get_last_modified(request, *args, **kwargs)
last_modified = http_date(modified)
if request.headers['if-modified-since'] == last_modified:
response.status = codes.not_modified
return
handler_output = getattr(self, request.method.lower())(request,
response, *args, **kwargs)
TODO implement post request method handling header augmentation
if self.use_etags and 'etag' not in response.headers:
pass
elif self.use_last_modified and 'last-modified' not in request.headers:
pass
return handler_output
Default handler for HEAD requests. For this to be available, a GET handler must be defined.
def head(self, request, response, *args, **kwargs):
self.get(request, response, *args, **kwargs)
response.data = ''
def options(self, request, response, *args, **kwargs):
if 'PATCH' in self.allowed_methods:
response.headers['Accept-Patch'] = ', '.join(self.supported_patch_types)
response.headers['Allow'] = ', '.join(sorted(self.allowed_methods))
response.headers['Content-Length'] = 0
HTTP/1.1
response.headers['Cache-Control'] = 'no-cache'
HTTP/1.0
response.headers['Pragma'] = 'no-cache'
Each handler prefixed with check_
corresponds to various client (4xx)
and server (5xx) error checking. For example, check_not_found
will
return True
if the resource does not exit. Note: all handlers are
must return True
to fail the check.
Checks if the service is unavailable based on the unavailable
flag.
Set the Retry-After
header if possible to inform clients when
the resource is expected to be available.
See also: unavailable
def check_service_unavailable(self, request, response):
if self.unavailable:
if type(self.unavailable) is int and self.unavailable > 0:
retry = self.unavailable
elif type(self.unavailable) is datetime:
retry = http_date(self.unavailable)
else:
retry = None
if retry:
response.headers['Retry-After'] = retry
return True
return False
def check_unauthorized(self, request, response):
return False
def check_forbidden(self, request, response, *args, **kwargs):
return False
def check_too_many_requests(self, request, response, *args, **kwargs):
return False
def check_request_entity_too_large(self, request, response):
if request.content_length > self.max_request_entity_length:
return True
def check_method_not_allowed(self, request, response):
if request.method not in self.allowed_methods:
response.headers['Allow'] = ', '.join(sorted(self.allowed_methods))
return True
return False
Check if this resource can process the request entity body. Note
Content-Type
is set as the empty string, so ensure it is not falsy
when processing it.
def check_unsupported_media_type(self, request, response):
if 'content-type' in request.headers and request.content_type:
if not self.content_type_supported(request, response):
return True
if 'content-encoding' in request.headers:
if not self.content_encoding_supported(request, response):
return True
if 'content-language' in request.headers:
if not self.content_language_supported(request, response):
return True
return False
def check_not_acceptable(self, request, response):
if not self.accept_type_supported(request, response):
return True
if 'accept-language' in request.headers:
if not self.accept_language_supported(request, response):
return True
if 'accept-charset' in request.headers:
if not self.accept_charset_supported(request, response):
return True
if 'accept-encoding' in request.headers:
if not self.accept_encoding_supported(request, response):
return True
return False
def check_precondition_required(self, request, response, *args, **kwargs):
if self.use_etags and 'if-match' not in request.headers:
response.data = 'This request is required to be conditional; '\
'try using "If-Match"'
return True
if self.use_last_modified and 'if-unmodified-since' not in request.headers:
response.data = 'This request is required to be conditional; '\
'try using "If-Unmodified-Since"'
return True
return False
def check_precondition_failed(self, request, response, *args, **kwargs):
ETags are enabled. Check for conditional request headers. The current ETag value is used for the conditional requests. After the request method handler has been processed, the new ETag will be calculated.
if self.use_etags and 'if-match' in request.headers:
etag = self.get_etag(request, *args, **kwargs)
if request.headers['if-match'] != etag:
return True
Last-Modified date enabled. check for conditional request headers. The current modification datetime value is used for the conditional requests. After the request method handler has been processed, the new Last-Modified datetime will be returned.
if self.use_last_modified and 'if-unmodified-since' in request.headers:
last_modified = self.get_last_modified(request, *args, **kwargs)
if request.headers['if-unmodified-since'] != http_date(last_modified):
return True
return False
def check_not_found(self, request, response, *args, **kwargs):
return False
def check_gone(self, request, response, *args, **kwargs):
return False
Checks if the requested Accept
mimetype is supported. Defaults
to using the first specified mimetype in supported_accept_types
.
def accept_type_supported(self, request, response):
if 'accept' in request.headers:
for mime in request.accept_mimetypes.values():
if mime in self.supported_accept_types:
response._accept_type = mime
return True
Only if Accept
explicitly contains a */*;q=0.0
does it preclude from returning a non-matching mimetype.
This may be desirable behavior (or not), so add this as an
option, e.g. force_accept_type
if not request.accept_mimetypes['*/*'] == 0:
return False
if len(self.supported_accept_types):
response._accept_type = self.supported_accept_types[0]
return True
Checks if the requested Accept-Charset
is supported.
def accept_charset_supported(self, request, response):
return True
Checks if the requested Accept-Encoding
is supported.
def accept_encoding_supported(self, request, response):
return True
Checks if the requested Accept-Language
is supported.
def accept_language_supported(self, request, response):
return True
Calculates an etag for the requested entity.
Provides the client an entity tag for future conditional
requests.
For GET and HEAD requests the If-None-Match
header may be
set to check if the entity has changed since the last request.
For PUT, PATCH, and DELETE requests, the If-Match
header may be
set to ensure the entity is the same as the cllient's so the current
operation is valid (optimistic concurrency).
def get_etag(self, request, *args, **kwargs):
pass
Calculates the last modified time for the requested entity. Provides the client the last modified of the entity for future conditional requests.
def get_last_modified(self, request, *args, **kwargs):
pass
Gets the expiry date and time for the requested entity. Informs the client when the entity will be invalid. This is most useful for clients to only refresh when they need to, otherwise the client's local cache is used.
def get_expiry(self, request, *args, **kwargs):
pass
def content_type_supported(self, request, response, *args, **kwargs):
return request.mimetype in self.supported_content_types
def content_encoding_supported(self, request, response, *args, **kwargs):
return True
def content_language_supported(self, request, response, *args, **kwargs):
return True