prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>counter.py<|end_file_name|><|fim▁begin|>import cv2
import numpy as np
import datetime as dt
# constant
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
OPENCV_METHODS = {
"Correlation": 0,
"Chi-Squared": 1,
"Intersection": 2,
"Hellinger": 3}
hist_limit = 0.6
ttl = 1 * 60
q_limit = 3
# init variables
total_count = 0
prev_count = 0
total_delta = 0
stm = {}
q = []
term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
video_capture = cv2.VideoCapture(0)
while True:
for t in list(stm): # short term memory
if (dt.datetime.now() - t).seconds > ttl:
stm.pop(t, None)
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
count = len(faces)
if len(q) >= q_limit: del q[0]
q.append(count)
isSame = True
for c in q: # Protect from fluctuation
if c != count: isSame = False
if isSame is False: continue
max_hist = 0
total_delta = 0
for (x, y, w, h) in faces:
# Draw a rectangle around the faces
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
if count == prev_count: <|fim_middle|>
# set up the ROI
face = frame[y: y + h, x: x + w]
hsv_roi = cv2.cvtColor(face, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(face, np.array((0., 60., 32.)), np.array((180., 255., 255.)))
face_hist = cv2.calcHist([face], [0], mask, [180], [0, 180])
cv2.normalize(face_hist, face_hist, 0, 255, cv2.NORM_MINMAX)
isFound = False
for t in stm:
hist_compare = cv2.compareHist(stm[t], face_hist, OPENCV_METHODS["Correlation"])
if hist_compare > max_hist: max_hist = hist_compare
if hist_compare >= hist_limit: isFound = True
if (len(stm) == 0) or (isFound is False and max_hist > 0):
total_delta += 1
stm[dt.datetime.now()] = face_hist
if prev_count != count:
total_count += total_delta
print("", count, " > ", total_count)
prev_count = count
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
<|fim▁end|> | continue |
<|file_name|>counter.py<|end_file_name|><|fim▁begin|>import cv2
import numpy as np
import datetime as dt
# constant
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
OPENCV_METHODS = {
"Correlation": 0,
"Chi-Squared": 1,
"Intersection": 2,
"Hellinger": 3}
hist_limit = 0.6
ttl = 1 * 60
q_limit = 3
# init variables
total_count = 0
prev_count = 0
total_delta = 0
stm = {}
q = []
term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
video_capture = cv2.VideoCapture(0)
while True:
for t in list(stm): # short term memory
if (dt.datetime.now() - t).seconds > ttl:
stm.pop(t, None)
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
count = len(faces)
if len(q) >= q_limit: del q[0]
q.append(count)
isSame = True
for c in q: # Protect from fluctuation
if c != count: isSame = False
if isSame is False: continue
max_hist = 0
total_delta = 0
for (x, y, w, h) in faces:
# Draw a rectangle around the faces
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
if count == prev_count: continue
# set up the ROI
face = frame[y: y + h, x: x + w]
hsv_roi = cv2.cvtColor(face, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(face, np.array((0., 60., 32.)), np.array((180., 255., 255.)))
face_hist = cv2.calcHist([face], [0], mask, [180], [0, 180])
cv2.normalize(face_hist, face_hist, 0, 255, cv2.NORM_MINMAX)
isFound = False
for t in stm:
hist_compare = cv2.compareHist(stm[t], face_hist, OPENCV_METHODS["Correlation"])
if hist_compare > max_hist: <|fim_middle|>
if hist_compare >= hist_limit: isFound = True
if (len(stm) == 0) or (isFound is False and max_hist > 0):
total_delta += 1
stm[dt.datetime.now()] = face_hist
if prev_count != count:
total_count += total_delta
print("", count, " > ", total_count)
prev_count = count
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
<|fim▁end|> | max_hist = hist_compare |
<|file_name|>counter.py<|end_file_name|><|fim▁begin|>import cv2
import numpy as np
import datetime as dt
# constant
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
OPENCV_METHODS = {
"Correlation": 0,
"Chi-Squared": 1,
"Intersection": 2,
"Hellinger": 3}
hist_limit = 0.6
ttl = 1 * 60
q_limit = 3
# init variables
total_count = 0
prev_count = 0
total_delta = 0
stm = {}
q = []
term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
video_capture = cv2.VideoCapture(0)
while True:
for t in list(stm): # short term memory
if (dt.datetime.now() - t).seconds > ttl:
stm.pop(t, None)
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
count = len(faces)
if len(q) >= q_limit: del q[0]
q.append(count)
isSame = True
for c in q: # Protect from fluctuation
if c != count: isSame = False
if isSame is False: continue
max_hist = 0
total_delta = 0
for (x, y, w, h) in faces:
# Draw a rectangle around the faces
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
if count == prev_count: continue
# set up the ROI
face = frame[y: y + h, x: x + w]
hsv_roi = cv2.cvtColor(face, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(face, np.array((0., 60., 32.)), np.array((180., 255., 255.)))
face_hist = cv2.calcHist([face], [0], mask, [180], [0, 180])
cv2.normalize(face_hist, face_hist, 0, 255, cv2.NORM_MINMAX)
isFound = False
for t in stm:
hist_compare = cv2.compareHist(stm[t], face_hist, OPENCV_METHODS["Correlation"])
if hist_compare > max_hist: max_hist = hist_compare
if hist_compare >= hist_limit: <|fim_middle|>
if (len(stm) == 0) or (isFound is False and max_hist > 0):
total_delta += 1
stm[dt.datetime.now()] = face_hist
if prev_count != count:
total_count += total_delta
print("", count, " > ", total_count)
prev_count = count
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
<|fim▁end|> | isFound = True |
<|file_name|>counter.py<|end_file_name|><|fim▁begin|>import cv2
import numpy as np
import datetime as dt
# constant
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
OPENCV_METHODS = {
"Correlation": 0,
"Chi-Squared": 1,
"Intersection": 2,
"Hellinger": 3}
hist_limit = 0.6
ttl = 1 * 60
q_limit = 3
# init variables
total_count = 0
prev_count = 0
total_delta = 0
stm = {}
q = []
term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
video_capture = cv2.VideoCapture(0)
while True:
for t in list(stm): # short term memory
if (dt.datetime.now() - t).seconds > ttl:
stm.pop(t, None)
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
count = len(faces)
if len(q) >= q_limit: del q[0]
q.append(count)
isSame = True
for c in q: # Protect from fluctuation
if c != count: isSame = False
if isSame is False: continue
max_hist = 0
total_delta = 0
for (x, y, w, h) in faces:
# Draw a rectangle around the faces
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
if count == prev_count: continue
# set up the ROI
face = frame[y: y + h, x: x + w]
hsv_roi = cv2.cvtColor(face, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(face, np.array((0., 60., 32.)), np.array((180., 255., 255.)))
face_hist = cv2.calcHist([face], [0], mask, [180], [0, 180])
cv2.normalize(face_hist, face_hist, 0, 255, cv2.NORM_MINMAX)
isFound = False
for t in stm:
hist_compare = cv2.compareHist(stm[t], face_hist, OPENCV_METHODS["Correlation"])
if hist_compare > max_hist: max_hist = hist_compare
if hist_compare >= hist_limit: isFound = True
if (len(stm) == 0) or (isFound is False and max_hist > 0):
<|fim_middle|>
stm[dt.datetime.now()] = face_hist
if prev_count != count:
total_count += total_delta
print("", count, " > ", total_count)
prev_count = count
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
<|fim▁end|> | total_delta += 1 |
<|file_name|>counter.py<|end_file_name|><|fim▁begin|>import cv2
import numpy as np
import datetime as dt
# constant
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
OPENCV_METHODS = {
"Correlation": 0,
"Chi-Squared": 1,
"Intersection": 2,
"Hellinger": 3}
hist_limit = 0.6
ttl = 1 * 60
q_limit = 3
# init variables
total_count = 0
prev_count = 0
total_delta = 0
stm = {}
q = []
term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
video_capture = cv2.VideoCapture(0)
while True:
for t in list(stm): # short term memory
if (dt.datetime.now() - t).seconds > ttl:
stm.pop(t, None)
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
count = len(faces)
if len(q) >= q_limit: del q[0]
q.append(count)
isSame = True
for c in q: # Protect from fluctuation
if c != count: isSame = False
if isSame is False: continue
max_hist = 0
total_delta = 0
for (x, y, w, h) in faces:
# Draw a rectangle around the faces
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
if count == prev_count: continue
# set up the ROI
face = frame[y: y + h, x: x + w]
hsv_roi = cv2.cvtColor(face, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(face, np.array((0., 60., 32.)), np.array((180., 255., 255.)))
face_hist = cv2.calcHist([face], [0], mask, [180], [0, 180])
cv2.normalize(face_hist, face_hist, 0, 255, cv2.NORM_MINMAX)
isFound = False
for t in stm:
hist_compare = cv2.compareHist(stm[t], face_hist, OPENCV_METHODS["Correlation"])
if hist_compare > max_hist: max_hist = hist_compare
if hist_compare >= hist_limit: isFound = True
if (len(stm) == 0) or (isFound is False and max_hist > 0):
total_delta += 1
stm[dt.datetime.now()] = face_hist
if prev_count != count:
<|fim_middle|>
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
<|fim▁end|> | total_count += total_delta
print("", count, " > ", total_count)
prev_count = count |
<|file_name|>counter.py<|end_file_name|><|fim▁begin|>import cv2
import numpy as np
import datetime as dt
# constant
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
OPENCV_METHODS = {
"Correlation": 0,
"Chi-Squared": 1,
"Intersection": 2,
"Hellinger": 3}
hist_limit = 0.6
ttl = 1 * 60
q_limit = 3
# init variables
total_count = 0
prev_count = 0
total_delta = 0
stm = {}
q = []
term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
video_capture = cv2.VideoCapture(0)
while True:
for t in list(stm): # short term memory
if (dt.datetime.now() - t).seconds > ttl:
stm.pop(t, None)
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
count = len(faces)
if len(q) >= q_limit: del q[0]
q.append(count)
isSame = True
for c in q: # Protect from fluctuation
if c != count: isSame = False
if isSame is False: continue
max_hist = 0
total_delta = 0
for (x, y, w, h) in faces:
# Draw a rectangle around the faces
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
if count == prev_count: continue
# set up the ROI
face = frame[y: y + h, x: x + w]
hsv_roi = cv2.cvtColor(face, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(face, np.array((0., 60., 32.)), np.array((180., 255., 255.)))
face_hist = cv2.calcHist([face], [0], mask, [180], [0, 180])
cv2.normalize(face_hist, face_hist, 0, 255, cv2.NORM_MINMAX)
isFound = False
for t in stm:
hist_compare = cv2.compareHist(stm[t], face_hist, OPENCV_METHODS["Correlation"])
if hist_compare > max_hist: max_hist = hist_compare
if hist_compare >= hist_limit: isFound = True
if (len(stm) == 0) or (isFound is False and max_hist > 0):
total_delta += 1
stm[dt.datetime.now()] = face_hist
if prev_count != count:
total_count += total_delta
print("", count, " > ", total_count)
prev_count = count
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
<|fim_middle|>
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
<|fim▁end|> | break |
<|file_name|>__openerp__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
{
'name': "Better validation for Attendance",
'summary': """
Short (1 phrase/line) summary of the module's purpose, used as
subtitle on modules listing or apps.openerp.com""",
<|fim▁hole|>
'author': "Jörn Mankiewicz",
'website': "http://www.yourcompany.com",
# Categories can be used to filter modules in modules listing
# Check https://github.com/odoo/odoo/blob/master/openerp/addons/base/module/module_data.xml
# for the full list
'category': 'Uncategorized',
'version': '8.0.0.1',
# any module necessary for this one to work correctly
'depends': ['base','hr_attendance','hr_timesheet_improvement'],
# always loaded
'data': [
# 'security/ir.model.access.csv',
'views/hr_attendance.xml',
],
# only loaded in demonstration mode
'demo': [
'demo.xml',
],
}<|fim▁end|> | 'description': """
Long description of module's purpose
""", |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa<|fim▁hole|>"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())<|fim▁end|> | end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other. |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
<|fim_middle|>
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())
<|fim▁end|> | """Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1]) |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
<|fim_middle|>
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())
<|fim▁end|> | point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
<|fim_middle|>
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())
<|fim▁end|> | return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text)) |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
<|fim_middle|>
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())
<|fim▁end|> | lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
<|fim_middle|>
def calculate_solution_1(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())
<|fim▁end|> | directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1])) |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
<|fim_middle|>
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())
<|fim▁end|> | return number_of_houses_covered(text) |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
<|fim_middle|>
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())
<|fim▁end|> | return number_of_houses_covered(text, robo_santa=True) |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
<|fim_middle|>
if __name__ == "__main__":
sys.exit(main())
<|fim▁end|> | """Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data))) |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
<|fim_middle|>
<|fim▁end|> | sys.exit(main()) |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def <|fim_middle|>(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())
<|fim▁end|> | update_point |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def <|fim_middle|>(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())
<|fim▁end|> | map_single_delivery |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def <|fim_middle|>(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())
<|fim▁end|> | number_of_houses_covered |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def <|fim_middle|>(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())
<|fim▁end|> | split_directions |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def <|fim_middle|>(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())
<|fim▁end|> | map_multiple_deliveries |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def <|fim_middle|>(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())
<|fim▁end|> | calculate_solution_1 |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
return number_of_houses_covered(text)
def <|fim_middle|>(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())
<|fim▁end|> | calculate_solution_2 |
<|file_name|>problem_03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def <|fim_middle|>(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())
<|fim▁end|> | main |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
recursely
"""
__version__ = "0.1"
__description__ = "Recursive importer for Python submodules"
__author__ = "Karol Kuczmarski"
__license__ = "Simplified BSD"
import sys
from recursely._compat import IS_PY3
from recursely.importer import RecursiveImporter
from recursely.utils import SentinelList
__all__ = ['install']
def install(retroactive=True):
"""Install the recursive import hook in ``sys.meta_path``,
enabling the use of ``__recursive__`` directive.
<|fim▁hole|> :param retroactive: Whether the hook should be retroactively applied
to module's that have been imported before
it was installed.
"""
if RecursiveImporter.is_installed():
return
importer = RecursiveImporter()
# because the hook is a catch-all one, we ensure that it's always
# at the very end of ``sys.meta_path``, so that it's tried only if
# no other (more specific) hook has been chosen by Python
if IS_PY3:
for i in reversed(range(len(sys.meta_path))):
ih_module = getattr(sys.meta_path[i], '__module__', '')
is_builtin = ih_module == '_frozen_importlib'
if not is_builtin:
break
sys.meta_path = SentinelList(
sys.meta_path[:i],
sentinels=[importer] + sys.meta_path[i:])
else:
sys.meta_path = SentinelList(sys.meta_path, sentinel=importer)
# look through already imported packages and recursively import
# their submodules, if they contain the ``__recursive__`` directive
if retroactive:
for module in list(sys.modules.values()):
importer.recurse(module)<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
recursely
"""
__version__ = "0.1"
__description__ = "Recursive importer for Python submodules"
__author__ = "Karol Kuczmarski"
__license__ = "Simplified BSD"
import sys
from recursely._compat import IS_PY3
from recursely.importer import RecursiveImporter
from recursely.utils import SentinelList
__all__ = ['install']
def install(retroactive=True):
<|fim_middle|>
<|fim▁end|> | """Install the recursive import hook in ``sys.meta_path``,
enabling the use of ``__recursive__`` directive.
:param retroactive: Whether the hook should be retroactively applied
to module's that have been imported before
it was installed.
"""
if RecursiveImporter.is_installed():
return
importer = RecursiveImporter()
# because the hook is a catch-all one, we ensure that it's always
# at the very end of ``sys.meta_path``, so that it's tried only if
# no other (more specific) hook has been chosen by Python
if IS_PY3:
for i in reversed(range(len(sys.meta_path))):
ih_module = getattr(sys.meta_path[i], '__module__', '')
is_builtin = ih_module == '_frozen_importlib'
if not is_builtin:
break
sys.meta_path = SentinelList(
sys.meta_path[:i],
sentinels=[importer] + sys.meta_path[i:])
else:
sys.meta_path = SentinelList(sys.meta_path, sentinel=importer)
# look through already imported packages and recursively import
# their submodules, if they contain the ``__recursive__`` directive
if retroactive:
for module in list(sys.modules.values()):
importer.recurse(module) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
recursely
"""
__version__ = "0.1"
__description__ = "Recursive importer for Python submodules"
__author__ = "Karol Kuczmarski"
__license__ = "Simplified BSD"
import sys
from recursely._compat import IS_PY3
from recursely.importer import RecursiveImporter
from recursely.utils import SentinelList
__all__ = ['install']
def install(retroactive=True):
"""Install the recursive import hook in ``sys.meta_path``,
enabling the use of ``__recursive__`` directive.
:param retroactive: Whether the hook should be retroactively applied
to module's that have been imported before
it was installed.
"""
if RecursiveImporter.is_installed():
<|fim_middle|>
importer = RecursiveImporter()
# because the hook is a catch-all one, we ensure that it's always
# at the very end of ``sys.meta_path``, so that it's tried only if
# no other (more specific) hook has been chosen by Python
if IS_PY3:
for i in reversed(range(len(sys.meta_path))):
ih_module = getattr(sys.meta_path[i], '__module__', '')
is_builtin = ih_module == '_frozen_importlib'
if not is_builtin:
break
sys.meta_path = SentinelList(
sys.meta_path[:i],
sentinels=[importer] + sys.meta_path[i:])
else:
sys.meta_path = SentinelList(sys.meta_path, sentinel=importer)
# look through already imported packages and recursively import
# their submodules, if they contain the ``__recursive__`` directive
if retroactive:
for module in list(sys.modules.values()):
importer.recurse(module)
<|fim▁end|> | return |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
recursely
"""
__version__ = "0.1"
__description__ = "Recursive importer for Python submodules"
__author__ = "Karol Kuczmarski"
__license__ = "Simplified BSD"
import sys
from recursely._compat import IS_PY3
from recursely.importer import RecursiveImporter
from recursely.utils import SentinelList
__all__ = ['install']
def install(retroactive=True):
"""Install the recursive import hook in ``sys.meta_path``,
enabling the use of ``__recursive__`` directive.
:param retroactive: Whether the hook should be retroactively applied
to module's that have been imported before
it was installed.
"""
if RecursiveImporter.is_installed():
return
importer = RecursiveImporter()
# because the hook is a catch-all one, we ensure that it's always
# at the very end of ``sys.meta_path``, so that it's tried only if
# no other (more specific) hook has been chosen by Python
if IS_PY3:
<|fim_middle|>
else:
sys.meta_path = SentinelList(sys.meta_path, sentinel=importer)
# look through already imported packages and recursively import
# their submodules, if they contain the ``__recursive__`` directive
if retroactive:
for module in list(sys.modules.values()):
importer.recurse(module)
<|fim▁end|> | for i in reversed(range(len(sys.meta_path))):
ih_module = getattr(sys.meta_path[i], '__module__', '')
is_builtin = ih_module == '_frozen_importlib'
if not is_builtin:
break
sys.meta_path = SentinelList(
sys.meta_path[:i],
sentinels=[importer] + sys.meta_path[i:]) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
recursely
"""
__version__ = "0.1"
__description__ = "Recursive importer for Python submodules"
__author__ = "Karol Kuczmarski"
__license__ = "Simplified BSD"
import sys
from recursely._compat import IS_PY3
from recursely.importer import RecursiveImporter
from recursely.utils import SentinelList
__all__ = ['install']
def install(retroactive=True):
"""Install the recursive import hook in ``sys.meta_path``,
enabling the use of ``__recursive__`` directive.
:param retroactive: Whether the hook should be retroactively applied
to module's that have been imported before
it was installed.
"""
if RecursiveImporter.is_installed():
return
importer = RecursiveImporter()
# because the hook is a catch-all one, we ensure that it's always
# at the very end of ``sys.meta_path``, so that it's tried only if
# no other (more specific) hook has been chosen by Python
if IS_PY3:
for i in reversed(range(len(sys.meta_path))):
ih_module = getattr(sys.meta_path[i], '__module__', '')
is_builtin = ih_module == '_frozen_importlib'
if not is_builtin:
<|fim_middle|>
sys.meta_path = SentinelList(
sys.meta_path[:i],
sentinels=[importer] + sys.meta_path[i:])
else:
sys.meta_path = SentinelList(sys.meta_path, sentinel=importer)
# look through already imported packages and recursively import
# their submodules, if they contain the ``__recursive__`` directive
if retroactive:
for module in list(sys.modules.values()):
importer.recurse(module)
<|fim▁end|> | break |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
recursely
"""
__version__ = "0.1"
__description__ = "Recursive importer for Python submodules"
__author__ = "Karol Kuczmarski"
__license__ = "Simplified BSD"
import sys
from recursely._compat import IS_PY3
from recursely.importer import RecursiveImporter
from recursely.utils import SentinelList
__all__ = ['install']
def install(retroactive=True):
"""Install the recursive import hook in ``sys.meta_path``,
enabling the use of ``__recursive__`` directive.
:param retroactive: Whether the hook should be retroactively applied
to module's that have been imported before
it was installed.
"""
if RecursiveImporter.is_installed():
return
importer = RecursiveImporter()
# because the hook is a catch-all one, we ensure that it's always
# at the very end of ``sys.meta_path``, so that it's tried only if
# no other (more specific) hook has been chosen by Python
if IS_PY3:
for i in reversed(range(len(sys.meta_path))):
ih_module = getattr(sys.meta_path[i], '__module__', '')
is_builtin = ih_module == '_frozen_importlib'
if not is_builtin:
break
sys.meta_path = SentinelList(
sys.meta_path[:i],
sentinels=[importer] + sys.meta_path[i:])
else:
<|fim_middle|>
# look through already imported packages and recursively import
# their submodules, if they contain the ``__recursive__`` directive
if retroactive:
for module in list(sys.modules.values()):
importer.recurse(module)
<|fim▁end|> | sys.meta_path = SentinelList(sys.meta_path, sentinel=importer) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
recursely
"""
__version__ = "0.1"
__description__ = "Recursive importer for Python submodules"
__author__ = "Karol Kuczmarski"
__license__ = "Simplified BSD"
import sys
from recursely._compat import IS_PY3
from recursely.importer import RecursiveImporter
from recursely.utils import SentinelList
__all__ = ['install']
def install(retroactive=True):
"""Install the recursive import hook in ``sys.meta_path``,
enabling the use of ``__recursive__`` directive.
:param retroactive: Whether the hook should be retroactively applied
to module's that have been imported before
it was installed.
"""
if RecursiveImporter.is_installed():
return
importer = RecursiveImporter()
# because the hook is a catch-all one, we ensure that it's always
# at the very end of ``sys.meta_path``, so that it's tried only if
# no other (more specific) hook has been chosen by Python
if IS_PY3:
for i in reversed(range(len(sys.meta_path))):
ih_module = getattr(sys.meta_path[i], '__module__', '')
is_builtin = ih_module == '_frozen_importlib'
if not is_builtin:
break
sys.meta_path = SentinelList(
sys.meta_path[:i],
sentinels=[importer] + sys.meta_path[i:])
else:
sys.meta_path = SentinelList(sys.meta_path, sentinel=importer)
# look through already imported packages and recursively import
# their submodules, if they contain the ``__recursive__`` directive
if retroactive:
<|fim_middle|>
<|fim▁end|> | for module in list(sys.modules.values()):
importer.recurse(module) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
recursely
"""
__version__ = "0.1"
__description__ = "Recursive importer for Python submodules"
__author__ = "Karol Kuczmarski"
__license__ = "Simplified BSD"
import sys
from recursely._compat import IS_PY3
from recursely.importer import RecursiveImporter
from recursely.utils import SentinelList
__all__ = ['install']
def <|fim_middle|>(retroactive=True):
"""Install the recursive import hook in ``sys.meta_path``,
enabling the use of ``__recursive__`` directive.
:param retroactive: Whether the hook should be retroactively applied
to module's that have been imported before
it was installed.
"""
if RecursiveImporter.is_installed():
return
importer = RecursiveImporter()
# because the hook is a catch-all one, we ensure that it's always
# at the very end of ``sys.meta_path``, so that it's tried only if
# no other (more specific) hook has been chosen by Python
if IS_PY3:
for i in reversed(range(len(sys.meta_path))):
ih_module = getattr(sys.meta_path[i], '__module__', '')
is_builtin = ih_module == '_frozen_importlib'
if not is_builtin:
break
sys.meta_path = SentinelList(
sys.meta_path[:i],
sentinels=[importer] + sys.meta_path[i:])
else:
sys.meta_path = SentinelList(sys.meta_path, sentinel=importer)
# look through already imported packages and recursively import
# their submodules, if they contain the ``__recursive__`` directive
if retroactive:
for module in list(sys.modules.values()):
importer.recurse(module)
<|fim▁end|> | install |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)<|fim▁hole|>
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page<|fim▁end|> | |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
<|fim_middle|>
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
<|fim_middle|>
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p)) |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
<|fim_middle|>
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
<|fim_middle|>
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | """Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented() |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
<|fim_middle|>
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | raise NotImplemented() |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
<|fim_middle|>
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | raise NotImplemented() |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
<|fim_middle|>
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | raise NotImplemented() |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
<|fim_middle|>
<|fim▁end|> | """PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
<|fim_middle|>
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | return db.engine.connect().execute(text(q_text), **q_params) |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
<|fim_middle|>
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
<|fim_middle|>
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw) |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
<|fim_middle|>
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw) |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
<|fim_middle|>
<|fim▁end|> | """pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
<|fim_middle|>
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw) |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
<|fim_middle|>
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | continue |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
<|fim_middle|>
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v}) |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
<|fim_middle|>
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | raise StorageError('Wrong *{}* param type.'.format(p)) |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
<|fim_middle|>
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | raise StorageError(err_duplicate) |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
<|fim_middle|>
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | query_params = {
'line_id': kw.get('line_id'),
} |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
<|fim_middle|>
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | return None |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
<|fim_middle|>
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | per_page = param_per_page |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
<|fim_middle|>
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | per_page = cls.per_page_default |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
<|fim_middle|>
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1 |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
<|fim_middle|>
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | offset = 0
next_page = 2
prev_page = None |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
<|fim_middle|>
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | return None, None, None, None |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
<|fim_middle|>
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | next_page = None |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def <|fim_middle|>(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | __init__ |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def <|fim_middle|>(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | cmpl_query |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def <|fim_middle|>(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | insert |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def <|fim_middle|>(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | get_single |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def <|fim_middle|>(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | get_many |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def <|fim_middle|>(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | rdbms_call |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def <|fim_middle|>(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | insert |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def <|fim_middle|>():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | query |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def <|fim_middle|>(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | get_single |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def <|fim_middle|>(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def create_dc(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | get_many |
<|file_name|>path.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(object):
params_allowed = {
'name': (
"AND name LIKE '%:name%'"),
}
cast_to_int = []
def __init__(self, **kw):
self.rule = []
self.q_params = {}
for p, v in kw.iteritems():
if p not in self.params_allowed.keys():
continue
elif isinstance(v, (unicode, basestring)):
self.rule.append(self.params_allowed[p][0])
self.q_params.update({p: v})
else:
raise StorageError('Wrong *{}* param type.'.format(p))
def cmpl_query(self):
sql_text = '\n' + ' '.join(self.rule)
return sql_text, self.q_params
class Dao(object):
"""Interface for line storage"""
@classmethod
def insert(cls, ammo):
raise NotImplemented()
@classmethod
def get_single(cls, **kw):
raise NotImplemented()
@classmethod
def get_many(cls, **kw):
raise NotImplemented()
class RDBMS(Dao):
"""PostgreSQL wrapper, implementing line.dao interface"""
per_page_default = app.config.get('LINE_PER_PAGE_DEFAULT') or 10
per_page_max = app.config.get('LINE_PER_PAGE_MAX') or 100
select_join_part = '''
SELECT l.*,
dc.name AS dc_name
FROM line l,
dc dc
WHERE l.dc_id = dc.id'''
@staticmethod
def rdbms_call(q_text, q_params):
return db.engine.connect().execute(text(q_text), **q_params)
@classmethod
def insert(cls, line):
kw = LineAdaptor.to_dict(line)
kw['dc_name'] = kw['dc']['name']
pp(kw)
def query():
return cls.rdbms_call('''
INSERT INTO line
(
id,
name,
dc_id
)
VALUES (
:id,
:name,
(SELECT id FROM dc WHERE name = :dc_name)
)
returning id''', kw)
err_duplicate = 'line:{} allready exists'.format(kw.get('name'))
try:
pk_id = [r for r in query()].pop()[0]
except exc.IntegrityError as e:
if 'unique constraint "line_pkey"' in str(e):
raise StorageError(err_duplicate)
raise StorageError('Some kind of IntegrityError')
return pk_id
@classmethod
def get_single(cls, **kw):
if kw.get('line_id'):
query_params = {
'line_id': kw.get('line_id'),
}
rv = cls.rdbms_call(' '.join([cls.select_join_part, 'AND l.id = :line_id']), query_params)
row = rv.first()
if not row:
return None
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
@classmethod
def get_many(cls, **kw):
"""pagination"""
pagination_part = '\nORDER BY id DESC\nLIMIT :limit OFFSET :offset'
param_per_page = kw.get('per_page')
if param_per_page and (param_per_page <= cls.per_page_max):
per_page = param_per_page
else:
per_page = cls.per_page_default
page_num = kw.get('page')
# page number starts from 1, page 0 and 1 mean the same -
# first slice from data set.
if page_num and isinstance(page_num, int) and (page_num >= 2):
offset = (page_num - 1) * per_page
next_page = page_num + 1
prev_page = page_num - 1
else:
offset = 0
next_page = 2
prev_page = None
query_params = {
'limit': per_page,
'offset': offset,
}
"""filtering"""
f = Filter(**kw)
filter_part, q_params_up = f.cmpl_query()
query_params.update(q_params_up)
rv = cls.rdbms_call(
''.join([cls.select_join_part, filter_part, pagination_part]),
query_params)
rows = rv.fetchall()
if len(rows) == 0:
return None, None, None, None
elif len(rows) < per_page: # last chunk of data
next_page = None
def <|fim_middle|>(row):
t_kw = dict(zip(rv.keys(), row))
return LineBuilder.from_row(**t_kw)
return map(create_dc, rows), per_page, next_page, prev_page
<|fim▁end|> | create_dc |
<|file_name|>sample.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# sample module
from jira.client import JIRA<|fim▁hole|>def main():
jira = JIRA()
JIRA(options={'server': 'http://localhost:8100'})
projects = jira.projects()
print projects
for project in projects:
print project.key
# Standard boilerplate to call the main() function.
if __name__ == '__main__':
main()<|fim▁end|> | |
<|file_name|>sample.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# sample module
from jira.client import JIRA
def main():
<|fim_middle|>
# Standard boilerplate to call the main() function.
if __name__ == '__main__':
main()<|fim▁end|> | jira = JIRA()
JIRA(options={'server': 'http://localhost:8100'})
projects = jira.projects()
print projects
for project in projects:
print project.key |
<|file_name|>sample.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# sample module
from jira.client import JIRA
def main():
jira = JIRA()
JIRA(options={'server': 'http://localhost:8100'})
projects = jira.projects()
print projects
for project in projects:
print project.key
# Standard boilerplate to call the main() function.
if __name__ == '__main__':
<|fim_middle|>
<|fim▁end|> | main() |
<|file_name|>sample.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# sample module
from jira.client import JIRA
def <|fim_middle|>():
jira = JIRA()
JIRA(options={'server': 'http://localhost:8100'})
projects = jira.projects()
print projects
for project in projects:
print project.key
# Standard boilerplate to call the main() function.
if __name__ == '__main__':
main()<|fim▁end|> | main |
<|file_name|>util.py<|end_file_name|><|fim▁begin|>import json
from dateutil import parser as datetime_parser
from occam.app import get_redis
from occam.runtime import OCCAM_SERVER_CONFIG_KEY
def get_servers():
redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
return servers.items()
def iterate_servers():
redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
for server_name, server_location in servers.iteritems():
yield server_name, server_location
<|fim▁hole|> element_getter = lambda x: x
key_getter = lambda x: datetime_parser.parse(element_getter(x))
return sorted(l, key=key_getter)<|fim▁end|> |
def sorted_by_time_element(l, element_getter=None):
if not element_getter: |
<|file_name|>util.py<|end_file_name|><|fim▁begin|>import json
from dateutil import parser as datetime_parser
from occam.app import get_redis
from occam.runtime import OCCAM_SERVER_CONFIG_KEY
def get_servers():
<|fim_middle|>
def iterate_servers():
redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
for server_name, server_location in servers.iteritems():
yield server_name, server_location
def sorted_by_time_element(l, element_getter=None):
if not element_getter:
element_getter = lambda x: x
key_getter = lambda x: datetime_parser.parse(element_getter(x))
return sorted(l, key=key_getter)
<|fim▁end|> | redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
return servers.items() |
<|file_name|>util.py<|end_file_name|><|fim▁begin|>import json
from dateutil import parser as datetime_parser
from occam.app import get_redis
from occam.runtime import OCCAM_SERVER_CONFIG_KEY
def get_servers():
redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
return servers.items()
def iterate_servers():
<|fim_middle|>
def sorted_by_time_element(l, element_getter=None):
if not element_getter:
element_getter = lambda x: x
key_getter = lambda x: datetime_parser.parse(element_getter(x))
return sorted(l, key=key_getter)
<|fim▁end|> | redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
for server_name, server_location in servers.iteritems():
yield server_name, server_location |
<|file_name|>util.py<|end_file_name|><|fim▁begin|>import json
from dateutil import parser as datetime_parser
from occam.app import get_redis
from occam.runtime import OCCAM_SERVER_CONFIG_KEY
def get_servers():
redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
return servers.items()
def iterate_servers():
redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
for server_name, server_location in servers.iteritems():
yield server_name, server_location
def sorted_by_time_element(l, element_getter=None):
<|fim_middle|>
<|fim▁end|> | if not element_getter:
element_getter = lambda x: x
key_getter = lambda x: datetime_parser.parse(element_getter(x))
return sorted(l, key=key_getter) |
<|file_name|>util.py<|end_file_name|><|fim▁begin|>import json
from dateutil import parser as datetime_parser
from occam.app import get_redis
from occam.runtime import OCCAM_SERVER_CONFIG_KEY
def get_servers():
redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
return servers.items()
def iterate_servers():
redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
for server_name, server_location in servers.iteritems():
yield server_name, server_location
def sorted_by_time_element(l, element_getter=None):
if not element_getter:
<|fim_middle|>
key_getter = lambda x: datetime_parser.parse(element_getter(x))
return sorted(l, key=key_getter)
<|fim▁end|> | element_getter = lambda x: x |
<|file_name|>util.py<|end_file_name|><|fim▁begin|>import json
from dateutil import parser as datetime_parser
from occam.app import get_redis
from occam.runtime import OCCAM_SERVER_CONFIG_KEY
def <|fim_middle|>():
redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
return servers.items()
def iterate_servers():
redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
for server_name, server_location in servers.iteritems():
yield server_name, server_location
def sorted_by_time_element(l, element_getter=None):
if not element_getter:
element_getter = lambda x: x
key_getter = lambda x: datetime_parser.parse(element_getter(x))
return sorted(l, key=key_getter)
<|fim▁end|> | get_servers |
<|file_name|>util.py<|end_file_name|><|fim▁begin|>import json
from dateutil import parser as datetime_parser
from occam.app import get_redis
from occam.runtime import OCCAM_SERVER_CONFIG_KEY
def get_servers():
redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
return servers.items()
def <|fim_middle|>():
redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
for server_name, server_location in servers.iteritems():
yield server_name, server_location
def sorted_by_time_element(l, element_getter=None):
if not element_getter:
element_getter = lambda x: x
key_getter = lambda x: datetime_parser.parse(element_getter(x))
return sorted(l, key=key_getter)
<|fim▁end|> | iterate_servers |
<|file_name|>util.py<|end_file_name|><|fim▁begin|>import json
from dateutil import parser as datetime_parser
from occam.app import get_redis
from occam.runtime import OCCAM_SERVER_CONFIG_KEY
def get_servers():
redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
return servers.items()
def iterate_servers():
redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
for server_name, server_location in servers.iteritems():
yield server_name, server_location
def <|fim_middle|>(l, element_getter=None):
if not element_getter:
element_getter = lambda x: x
key_getter = lambda x: datetime_parser.parse(element_getter(x))
return sorted(l, key=key_getter)
<|fim▁end|> | sorted_by_time_element |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from pupa.scrape import Jurisdiction, Organization
from .bills import MNBillScraper
from .committees import MNCommitteeScraper
from .people import MNPersonScraper
from .vote_events import MNVoteScraper
from .events import MNEventScraper
from .common import url_xpath
"""
Minnesota legislative data can be found at the Office of the Revisor
of Statutes:
https://www.revisor.mn.gov/
Votes:
There are not detailed vote data for Senate votes, simply yes and no counts.
Bill pages have vote counts and links to House details, so it makes more
sense to get vote data from the bill pages.
"""
class Minnesota(Jurisdiction):
division_id = "ocd-division/country:us/state:mn"
classification = "government"
name = "Minnesota"
url = "http://state.mn.us/"
check_sessions = True
scrapers = {
"bills": MNBillScraper,
"committees": MNCommitteeScraper,
"people": MNPersonScraper,
"vote_events": MNVoteScraper,
"events": MNEventScraper,
}
parties = [{'name': 'Republican'},
{'name': 'Democratic-Farmer-Labor'}]
legislative_sessions = [
{
'_scraped_name': '86th Legislature, 2009-2010',
'classification': 'primary',
'identifier': '2009-2010',
'name': '2009-2010 Regular Session'
},
{
'_scraped_name': '86th Legislature, 2010 1st Special Session',
'classification': 'special',
'identifier': '2010 1st Special Session',
'name': '2010, 1st Special Session'
},
{
'_scraped_name': '86th Legislature, 2010 2nd Special Session',
'classification': 'special',
'identifier': '2010 2nd Special Session',
'name': '2010, 2nd Special Session'
},
{
'_scraped_name': '87th Legislature, 2011-2012',
'classification': 'primary',
'identifier': '2011-2012',
'name': '2011-2012 Regular Session'
},
{
'_scraped_name': '87th Legislature, 2011 1st Special Session',
'classification': 'special',
'identifier': '2011s1',
'name': '2011, 1st Special Session'
},
{
'_scraped_name': '87th Legislature, 2012 1st Special Session',
'classification': 'special',
'identifier': '2012s1',
'name': '2012, 1st Special Session'
},
{
'_scraped_name': '88th Legislature, 2013-2014',
'classification': 'primary',
'identifier': '2013-2014',
'name': '2013-2014 Regular Session'
},
{
'_scraped_name': '88th Legislature, 2013 1st Special Session',
'classification': 'special',
'identifier': '2013s1',
'name': '2013, 1st Special Session'
},
{
'_scraped_name': '89th Legislature, 2015-2016',
'classification': 'primary',
'identifier': '2015-2016',
'name': '2015-2016 Regular Session'
},
{
'_scraped_name': '89th Legislature, 2015 1st Special Session',
'classification': 'special',
'identifier': '2015s1',
'name': '2015, 1st Special Session'
},
{
'_scraped_name': '90th Legislature, 2017-2018',
'classification': 'primary',
'identifier': '2017-2018',
'name': '2017-2018 Regular Session'
},
]
ignored_scraped_sessions = [
'85th Legislature, 2007-2008',
'85th Legislature, 2007 1st Special Session',
'84th Legislature, 2005-2006',
'84th Legislature, 2005 1st Special Session',
'83rd Legislature, 2003-2004',
'83rd Legislature, 2003 1st Special Session',
'82nd Legislature, 2001-2002',
'82nd Legislature, 2002 1st Special Session',
'82nd Legislature, 2001 1st Special Session',
'81st Legislature, 1999-2000',
'80th Legislature, 1997-1998',
'80th Legislature, 1998 1st Special Session',
'80th Legislature, 1997 3rd Special Session',
'80th Legislature, 1997 2nd Special Session',
'80th Legislature, 1997 1st Special Session',
'79th Legislature, 1995-1996',
'79th Legislature, 1995 1st Special Session',
'89th Legislature, 2015-2016',
]
def get_organizations(self):
legis = Organization('Minnesota Legislature', classification='legislature')
upper = Organization('Minnesota Senate', classification='upper',
parent_id=legis._id)
lower = Organization('Minnesota House of Representatives',
classification='lower', parent_id=legis._id)
for n in range(1, 68):
upper.add_post(label=str(n), role='Senator',
division_id='ocd-division/country:us/state:mn/sldu:{}'.format(n))
lower.add_post(label=str(n) + 'A', role='Representative',
division_id='ocd-division/country:us/state:mn/sldl:{}a'.format(n))
lower.add_post(label=str(n) + 'B', role='Representative',
division_id='ocd-division/country:us/state:mn/sldl:{}b'.format(n))
yield legis
yield upper<|fim▁hole|>
def get_session_list(self):
return url_xpath('https://www.revisor.mn.gov/revisor/pages/'
'search_status/status_search.php?body=House',
'//select[@name="session"]/option/text()')<|fim▁end|> | yield lower |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from pupa.scrape import Jurisdiction, Organization
from .bills import MNBillScraper
from .committees import MNCommitteeScraper
from .people import MNPersonScraper
from .vote_events import MNVoteScraper
from .events import MNEventScraper
from .common import url_xpath
"""
Minnesota legislative data can be found at the Office of the Revisor
of Statutes:
https://www.revisor.mn.gov/
Votes:
There are not detailed vote data for Senate votes, simply yes and no counts.
Bill pages have vote counts and links to House details, so it makes more
sense to get vote data from the bill pages.
"""
class Minnesota(Jurisdiction):
<|fim_middle|>
<|fim▁end|> | division_id = "ocd-division/country:us/state:mn"
classification = "government"
name = "Minnesota"
url = "http://state.mn.us/"
check_sessions = True
scrapers = {
"bills": MNBillScraper,
"committees": MNCommitteeScraper,
"people": MNPersonScraper,
"vote_events": MNVoteScraper,
"events": MNEventScraper,
}
parties = [{'name': 'Republican'},
{'name': 'Democratic-Farmer-Labor'}]
legislative_sessions = [
{
'_scraped_name': '86th Legislature, 2009-2010',
'classification': 'primary',
'identifier': '2009-2010',
'name': '2009-2010 Regular Session'
},
{
'_scraped_name': '86th Legislature, 2010 1st Special Session',
'classification': 'special',
'identifier': '2010 1st Special Session',
'name': '2010, 1st Special Session'
},
{
'_scraped_name': '86th Legislature, 2010 2nd Special Session',
'classification': 'special',
'identifier': '2010 2nd Special Session',
'name': '2010, 2nd Special Session'
},
{
'_scraped_name': '87th Legislature, 2011-2012',
'classification': 'primary',
'identifier': '2011-2012',
'name': '2011-2012 Regular Session'
},
{
'_scraped_name': '87th Legislature, 2011 1st Special Session',
'classification': 'special',
'identifier': '2011s1',
'name': '2011, 1st Special Session'
},
{
'_scraped_name': '87th Legislature, 2012 1st Special Session',
'classification': 'special',
'identifier': '2012s1',
'name': '2012, 1st Special Session'
},
{
'_scraped_name': '88th Legislature, 2013-2014',
'classification': 'primary',
'identifier': '2013-2014',
'name': '2013-2014 Regular Session'
},
{
'_scraped_name': '88th Legislature, 2013 1st Special Session',
'classification': 'special',
'identifier': '2013s1',
'name': '2013, 1st Special Session'
},
{
'_scraped_name': '89th Legislature, 2015-2016',
'classification': 'primary',
'identifier': '2015-2016',
'name': '2015-2016 Regular Session'
},
{
'_scraped_name': '89th Legislature, 2015 1st Special Session',
'classification': 'special',
'identifier': '2015s1',
'name': '2015, 1st Special Session'
},
{
'_scraped_name': '90th Legislature, 2017-2018',
'classification': 'primary',
'identifier': '2017-2018',
'name': '2017-2018 Regular Session'
},
]
ignored_scraped_sessions = [
'85th Legislature, 2007-2008',
'85th Legislature, 2007 1st Special Session',
'84th Legislature, 2005-2006',
'84th Legislature, 2005 1st Special Session',
'83rd Legislature, 2003-2004',
'83rd Legislature, 2003 1st Special Session',
'82nd Legislature, 2001-2002',
'82nd Legislature, 2002 1st Special Session',
'82nd Legislature, 2001 1st Special Session',
'81st Legislature, 1999-2000',
'80th Legislature, 1997-1998',
'80th Legislature, 1998 1st Special Session',
'80th Legislature, 1997 3rd Special Session',
'80th Legislature, 1997 2nd Special Session',
'80th Legislature, 1997 1st Special Session',
'79th Legislature, 1995-1996',
'79th Legislature, 1995 1st Special Session',
'89th Legislature, 2015-2016',
]
def get_organizations(self):
legis = Organization('Minnesota Legislature', classification='legislature')
upper = Organization('Minnesota Senate', classification='upper',
parent_id=legis._id)
lower = Organization('Minnesota House of Representatives',
classification='lower', parent_id=legis._id)
for n in range(1, 68):
upper.add_post(label=str(n), role='Senator',
division_id='ocd-division/country:us/state:mn/sldu:{}'.format(n))
lower.add_post(label=str(n) + 'A', role='Representative',
division_id='ocd-division/country:us/state:mn/sldl:{}a'.format(n))
lower.add_post(label=str(n) + 'B', role='Representative',
division_id='ocd-division/country:us/state:mn/sldl:{}b'.format(n))
yield legis
yield upper
yield lower
def get_session_list(self):
return url_xpath('https://www.revisor.mn.gov/revisor/pages/'
'search_status/status_search.php?body=House',
'//select[@name="session"]/option/text()') |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from pupa.scrape import Jurisdiction, Organization
from .bills import MNBillScraper
from .committees import MNCommitteeScraper
from .people import MNPersonScraper
from .vote_events import MNVoteScraper
from .events import MNEventScraper
from .common import url_xpath
"""
Minnesota legislative data can be found at the Office of the Revisor
of Statutes:
https://www.revisor.mn.gov/
Votes:
There are not detailed vote data for Senate votes, simply yes and no counts.
Bill pages have vote counts and links to House details, so it makes more
sense to get vote data from the bill pages.
"""
class Minnesota(Jurisdiction):
division_id = "ocd-division/country:us/state:mn"
classification = "government"
name = "Minnesota"
url = "http://state.mn.us/"
check_sessions = True
scrapers = {
"bills": MNBillScraper,
"committees": MNCommitteeScraper,
"people": MNPersonScraper,
"vote_events": MNVoteScraper,
"events": MNEventScraper,
}
parties = [{'name': 'Republican'},
{'name': 'Democratic-Farmer-Labor'}]
legislative_sessions = [
{
'_scraped_name': '86th Legislature, 2009-2010',
'classification': 'primary',
'identifier': '2009-2010',
'name': '2009-2010 Regular Session'
},
{
'_scraped_name': '86th Legislature, 2010 1st Special Session',
'classification': 'special',
'identifier': '2010 1st Special Session',
'name': '2010, 1st Special Session'
},
{
'_scraped_name': '86th Legislature, 2010 2nd Special Session',
'classification': 'special',
'identifier': '2010 2nd Special Session',
'name': '2010, 2nd Special Session'
},
{
'_scraped_name': '87th Legislature, 2011-2012',
'classification': 'primary',
'identifier': '2011-2012',
'name': '2011-2012 Regular Session'
},
{
'_scraped_name': '87th Legislature, 2011 1st Special Session',
'classification': 'special',
'identifier': '2011s1',
'name': '2011, 1st Special Session'
},
{
'_scraped_name': '87th Legislature, 2012 1st Special Session',
'classification': 'special',
'identifier': '2012s1',
'name': '2012, 1st Special Session'
},
{
'_scraped_name': '88th Legislature, 2013-2014',
'classification': 'primary',
'identifier': '2013-2014',
'name': '2013-2014 Regular Session'
},
{
'_scraped_name': '88th Legislature, 2013 1st Special Session',
'classification': 'special',
'identifier': '2013s1',
'name': '2013, 1st Special Session'
},
{
'_scraped_name': '89th Legislature, 2015-2016',
'classification': 'primary',
'identifier': '2015-2016',
'name': '2015-2016 Regular Session'
},
{
'_scraped_name': '89th Legislature, 2015 1st Special Session',
'classification': 'special',
'identifier': '2015s1',
'name': '2015, 1st Special Session'
},
{
'_scraped_name': '90th Legislature, 2017-2018',
'classification': 'primary',
'identifier': '2017-2018',
'name': '2017-2018 Regular Session'
},
]
ignored_scraped_sessions = [
'85th Legislature, 2007-2008',
'85th Legislature, 2007 1st Special Session',
'84th Legislature, 2005-2006',
'84th Legislature, 2005 1st Special Session',
'83rd Legislature, 2003-2004',
'83rd Legislature, 2003 1st Special Session',
'82nd Legislature, 2001-2002',
'82nd Legislature, 2002 1st Special Session',
'82nd Legislature, 2001 1st Special Session',
'81st Legislature, 1999-2000',
'80th Legislature, 1997-1998',
'80th Legislature, 1998 1st Special Session',
'80th Legislature, 1997 3rd Special Session',
'80th Legislature, 1997 2nd Special Session',
'80th Legislature, 1997 1st Special Session',
'79th Legislature, 1995-1996',
'79th Legislature, 1995 1st Special Session',
'89th Legislature, 2015-2016',
]
def get_organizations(self):
<|fim_middle|>
def get_session_list(self):
return url_xpath('https://www.revisor.mn.gov/revisor/pages/'
'search_status/status_search.php?body=House',
'//select[@name="session"]/option/text()')
<|fim▁end|> | legis = Organization('Minnesota Legislature', classification='legislature')
upper = Organization('Minnesota Senate', classification='upper',
parent_id=legis._id)
lower = Organization('Minnesota House of Representatives',
classification='lower', parent_id=legis._id)
for n in range(1, 68):
upper.add_post(label=str(n), role='Senator',
division_id='ocd-division/country:us/state:mn/sldu:{}'.format(n))
lower.add_post(label=str(n) + 'A', role='Representative',
division_id='ocd-division/country:us/state:mn/sldl:{}a'.format(n))
lower.add_post(label=str(n) + 'B', role='Representative',
division_id='ocd-division/country:us/state:mn/sldl:{}b'.format(n))
yield legis
yield upper
yield lower |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from pupa.scrape import Jurisdiction, Organization
from .bills import MNBillScraper
from .committees import MNCommitteeScraper
from .people import MNPersonScraper
from .vote_events import MNVoteScraper
from .events import MNEventScraper
from .common import url_xpath
"""
Minnesota legislative data can be found at the Office of the Revisor
of Statutes:
https://www.revisor.mn.gov/
Votes:
There are not detailed vote data for Senate votes, simply yes and no counts.
Bill pages have vote counts and links to House details, so it makes more
sense to get vote data from the bill pages.
"""
class Minnesota(Jurisdiction):
division_id = "ocd-division/country:us/state:mn"
classification = "government"
name = "Minnesota"
url = "http://state.mn.us/"
check_sessions = True
scrapers = {
"bills": MNBillScraper,
"committees": MNCommitteeScraper,
"people": MNPersonScraper,
"vote_events": MNVoteScraper,
"events": MNEventScraper,
}
parties = [{'name': 'Republican'},
{'name': 'Democratic-Farmer-Labor'}]
legislative_sessions = [
{
'_scraped_name': '86th Legislature, 2009-2010',
'classification': 'primary',
'identifier': '2009-2010',
'name': '2009-2010 Regular Session'
},
{
'_scraped_name': '86th Legislature, 2010 1st Special Session',
'classification': 'special',
'identifier': '2010 1st Special Session',
'name': '2010, 1st Special Session'
},
{
'_scraped_name': '86th Legislature, 2010 2nd Special Session',
'classification': 'special',
'identifier': '2010 2nd Special Session',
'name': '2010, 2nd Special Session'
},
{
'_scraped_name': '87th Legislature, 2011-2012',
'classification': 'primary',
'identifier': '2011-2012',
'name': '2011-2012 Regular Session'
},
{
'_scraped_name': '87th Legislature, 2011 1st Special Session',
'classification': 'special',
'identifier': '2011s1',
'name': '2011, 1st Special Session'
},
{
'_scraped_name': '87th Legislature, 2012 1st Special Session',
'classification': 'special',
'identifier': '2012s1',
'name': '2012, 1st Special Session'
},
{
'_scraped_name': '88th Legislature, 2013-2014',
'classification': 'primary',
'identifier': '2013-2014',
'name': '2013-2014 Regular Session'
},
{
'_scraped_name': '88th Legislature, 2013 1st Special Session',
'classification': 'special',
'identifier': '2013s1',
'name': '2013, 1st Special Session'
},
{
'_scraped_name': '89th Legislature, 2015-2016',
'classification': 'primary',
'identifier': '2015-2016',
'name': '2015-2016 Regular Session'
},
{
'_scraped_name': '89th Legislature, 2015 1st Special Session',
'classification': 'special',
'identifier': '2015s1',
'name': '2015, 1st Special Session'
},
{
'_scraped_name': '90th Legislature, 2017-2018',
'classification': 'primary',
'identifier': '2017-2018',
'name': '2017-2018 Regular Session'
},
]
ignored_scraped_sessions = [
'85th Legislature, 2007-2008',
'85th Legislature, 2007 1st Special Session',
'84th Legislature, 2005-2006',
'84th Legislature, 2005 1st Special Session',
'83rd Legislature, 2003-2004',
'83rd Legislature, 2003 1st Special Session',
'82nd Legislature, 2001-2002',
'82nd Legislature, 2002 1st Special Session',
'82nd Legislature, 2001 1st Special Session',
'81st Legislature, 1999-2000',
'80th Legislature, 1997-1998',
'80th Legislature, 1998 1st Special Session',
'80th Legislature, 1997 3rd Special Session',
'80th Legislature, 1997 2nd Special Session',
'80th Legislature, 1997 1st Special Session',
'79th Legislature, 1995-1996',
'79th Legislature, 1995 1st Special Session',
'89th Legislature, 2015-2016',
]
def get_organizations(self):
legis = Organization('Minnesota Legislature', classification='legislature')
upper = Organization('Minnesota Senate', classification='upper',
parent_id=legis._id)
lower = Organization('Minnesota House of Representatives',
classification='lower', parent_id=legis._id)
for n in range(1, 68):
upper.add_post(label=str(n), role='Senator',
division_id='ocd-division/country:us/state:mn/sldu:{}'.format(n))
lower.add_post(label=str(n) + 'A', role='Representative',
division_id='ocd-division/country:us/state:mn/sldl:{}a'.format(n))
lower.add_post(label=str(n) + 'B', role='Representative',
division_id='ocd-division/country:us/state:mn/sldl:{}b'.format(n))
yield legis
yield upper
yield lower
def get_session_list(self):
<|fim_middle|>
<|fim▁end|> | return url_xpath('https://www.revisor.mn.gov/revisor/pages/'
'search_status/status_search.php?body=House',
'//select[@name="session"]/option/text()') |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from pupa.scrape import Jurisdiction, Organization
from .bills import MNBillScraper
from .committees import MNCommitteeScraper
from .people import MNPersonScraper
from .vote_events import MNVoteScraper
from .events import MNEventScraper
from .common import url_xpath
"""
Minnesota legislative data can be found at the Office of the Revisor
of Statutes:
https://www.revisor.mn.gov/
Votes:
There are not detailed vote data for Senate votes, simply yes and no counts.
Bill pages have vote counts and links to House details, so it makes more
sense to get vote data from the bill pages.
"""
class Minnesota(Jurisdiction):
division_id = "ocd-division/country:us/state:mn"
classification = "government"
name = "Minnesota"
url = "http://state.mn.us/"
check_sessions = True
scrapers = {
"bills": MNBillScraper,
"committees": MNCommitteeScraper,
"people": MNPersonScraper,
"vote_events": MNVoteScraper,
"events": MNEventScraper,
}
parties = [{'name': 'Republican'},
{'name': 'Democratic-Farmer-Labor'}]
legislative_sessions = [
{
'_scraped_name': '86th Legislature, 2009-2010',
'classification': 'primary',
'identifier': '2009-2010',
'name': '2009-2010 Regular Session'
},
{
'_scraped_name': '86th Legislature, 2010 1st Special Session',
'classification': 'special',
'identifier': '2010 1st Special Session',
'name': '2010, 1st Special Session'
},
{
'_scraped_name': '86th Legislature, 2010 2nd Special Session',
'classification': 'special',
'identifier': '2010 2nd Special Session',
'name': '2010, 2nd Special Session'
},
{
'_scraped_name': '87th Legislature, 2011-2012',
'classification': 'primary',
'identifier': '2011-2012',
'name': '2011-2012 Regular Session'
},
{
'_scraped_name': '87th Legislature, 2011 1st Special Session',
'classification': 'special',
'identifier': '2011s1',
'name': '2011, 1st Special Session'
},
{
'_scraped_name': '87th Legislature, 2012 1st Special Session',
'classification': 'special',
'identifier': '2012s1',
'name': '2012, 1st Special Session'
},
{
'_scraped_name': '88th Legislature, 2013-2014',
'classification': 'primary',
'identifier': '2013-2014',
'name': '2013-2014 Regular Session'
},
{
'_scraped_name': '88th Legislature, 2013 1st Special Session',
'classification': 'special',
'identifier': '2013s1',
'name': '2013, 1st Special Session'
},
{
'_scraped_name': '89th Legislature, 2015-2016',
'classification': 'primary',
'identifier': '2015-2016',
'name': '2015-2016 Regular Session'
},
{
'_scraped_name': '89th Legislature, 2015 1st Special Session',
'classification': 'special',
'identifier': '2015s1',
'name': '2015, 1st Special Session'
},
{
'_scraped_name': '90th Legislature, 2017-2018',
'classification': 'primary',
'identifier': '2017-2018',
'name': '2017-2018 Regular Session'
},
]
ignored_scraped_sessions = [
'85th Legislature, 2007-2008',
'85th Legislature, 2007 1st Special Session',
'84th Legislature, 2005-2006',
'84th Legislature, 2005 1st Special Session',
'83rd Legislature, 2003-2004',
'83rd Legislature, 2003 1st Special Session',
'82nd Legislature, 2001-2002',
'82nd Legislature, 2002 1st Special Session',
'82nd Legislature, 2001 1st Special Session',
'81st Legislature, 1999-2000',
'80th Legislature, 1997-1998',
'80th Legislature, 1998 1st Special Session',
'80th Legislature, 1997 3rd Special Session',
'80th Legislature, 1997 2nd Special Session',
'80th Legislature, 1997 1st Special Session',
'79th Legislature, 1995-1996',
'79th Legislature, 1995 1st Special Session',
'89th Legislature, 2015-2016',
]
def <|fim_middle|>(self):
legis = Organization('Minnesota Legislature', classification='legislature')
upper = Organization('Minnesota Senate', classification='upper',
parent_id=legis._id)
lower = Organization('Minnesota House of Representatives',
classification='lower', parent_id=legis._id)
for n in range(1, 68):
upper.add_post(label=str(n), role='Senator',
division_id='ocd-division/country:us/state:mn/sldu:{}'.format(n))
lower.add_post(label=str(n) + 'A', role='Representative',
division_id='ocd-division/country:us/state:mn/sldl:{}a'.format(n))
lower.add_post(label=str(n) + 'B', role='Representative',
division_id='ocd-division/country:us/state:mn/sldl:{}b'.format(n))
yield legis
yield upper
yield lower
def get_session_list(self):
return url_xpath('https://www.revisor.mn.gov/revisor/pages/'
'search_status/status_search.php?body=House',
'//select[@name="session"]/option/text()')
<|fim▁end|> | get_organizations |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from pupa.scrape import Jurisdiction, Organization
from .bills import MNBillScraper
from .committees import MNCommitteeScraper
from .people import MNPersonScraper
from .vote_events import MNVoteScraper
from .events import MNEventScraper
from .common import url_xpath
"""
Minnesota legislative data can be found at the Office of the Revisor
of Statutes:
https://www.revisor.mn.gov/
Votes:
There are not detailed vote data for Senate votes, simply yes and no counts.
Bill pages have vote counts and links to House details, so it makes more
sense to get vote data from the bill pages.
"""
class Minnesota(Jurisdiction):
division_id = "ocd-division/country:us/state:mn"
classification = "government"
name = "Minnesota"
url = "http://state.mn.us/"
check_sessions = True
scrapers = {
"bills": MNBillScraper,
"committees": MNCommitteeScraper,
"people": MNPersonScraper,
"vote_events": MNVoteScraper,
"events": MNEventScraper,
}
parties = [{'name': 'Republican'},
{'name': 'Democratic-Farmer-Labor'}]
legislative_sessions = [
{
'_scraped_name': '86th Legislature, 2009-2010',
'classification': 'primary',
'identifier': '2009-2010',
'name': '2009-2010 Regular Session'
},
{
'_scraped_name': '86th Legislature, 2010 1st Special Session',
'classification': 'special',
'identifier': '2010 1st Special Session',
'name': '2010, 1st Special Session'
},
{
'_scraped_name': '86th Legislature, 2010 2nd Special Session',
'classification': 'special',
'identifier': '2010 2nd Special Session',
'name': '2010, 2nd Special Session'
},
{
'_scraped_name': '87th Legislature, 2011-2012',
'classification': 'primary',
'identifier': '2011-2012',
'name': '2011-2012 Regular Session'
},
{
'_scraped_name': '87th Legislature, 2011 1st Special Session',
'classification': 'special',
'identifier': '2011s1',
'name': '2011, 1st Special Session'
},
{
'_scraped_name': '87th Legislature, 2012 1st Special Session',
'classification': 'special',
'identifier': '2012s1',
'name': '2012, 1st Special Session'
},
{
'_scraped_name': '88th Legislature, 2013-2014',
'classification': 'primary',
'identifier': '2013-2014',
'name': '2013-2014 Regular Session'
},
{
'_scraped_name': '88th Legislature, 2013 1st Special Session',
'classification': 'special',
'identifier': '2013s1',
'name': '2013, 1st Special Session'
},
{
'_scraped_name': '89th Legislature, 2015-2016',
'classification': 'primary',
'identifier': '2015-2016',
'name': '2015-2016 Regular Session'
},
{
'_scraped_name': '89th Legislature, 2015 1st Special Session',
'classification': 'special',
'identifier': '2015s1',
'name': '2015, 1st Special Session'
},
{
'_scraped_name': '90th Legislature, 2017-2018',
'classification': 'primary',
'identifier': '2017-2018',
'name': '2017-2018 Regular Session'
},
]
ignored_scraped_sessions = [
'85th Legislature, 2007-2008',
'85th Legislature, 2007 1st Special Session',
'84th Legislature, 2005-2006',
'84th Legislature, 2005 1st Special Session',
'83rd Legislature, 2003-2004',
'83rd Legislature, 2003 1st Special Session',
'82nd Legislature, 2001-2002',
'82nd Legislature, 2002 1st Special Session',
'82nd Legislature, 2001 1st Special Session',
'81st Legislature, 1999-2000',
'80th Legislature, 1997-1998',
'80th Legislature, 1998 1st Special Session',
'80th Legislature, 1997 3rd Special Session',
'80th Legislature, 1997 2nd Special Session',
'80th Legislature, 1997 1st Special Session',
'79th Legislature, 1995-1996',
'79th Legislature, 1995 1st Special Session',
'89th Legislature, 2015-2016',
]
def get_organizations(self):
legis = Organization('Minnesota Legislature', classification='legislature')
upper = Organization('Minnesota Senate', classification='upper',
parent_id=legis._id)
lower = Organization('Minnesota House of Representatives',
classification='lower', parent_id=legis._id)
for n in range(1, 68):
upper.add_post(label=str(n), role='Senator',
division_id='ocd-division/country:us/state:mn/sldu:{}'.format(n))
lower.add_post(label=str(n) + 'A', role='Representative',
division_id='ocd-division/country:us/state:mn/sldl:{}a'.format(n))
lower.add_post(label=str(n) + 'B', role='Representative',
division_id='ocd-division/country:us/state:mn/sldl:{}b'.format(n))
yield legis
yield upper
yield lower
def <|fim_middle|>(self):
return url_xpath('https://www.revisor.mn.gov/revisor/pages/'
'search_status/status_search.php?body=House',
'//select[@name="session"]/option/text()')
<|fim▁end|> | get_session_list |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
from django import forms
class VoterCreationForm(UserCreationForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterCreationForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()<|fim▁hole|> return user
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')
class VoterChangeForm(UserChangeForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterChangeForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
model = User
exclude = ('',)
class VoterAdmin(UserAdmin):
form = VoterChangeForm
add_form = VoterCreationForm
list_filter = UserAdmin.list_filter + ('section',)
fieldsets = (
(None, {'fields': ('username', 'password')}),
(('Personal info'), {'fields': ('first_name', 'last_name', 'section')}),
(('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')}
),
)
admin.site.unregister(User)
admin.site.register(User, VoterAdmin)<|fim▁end|> | |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
from django import forms
class VoterCreationForm(UserCreationForm):
<|fim_middle|>
class VoterChangeForm(UserChangeForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterChangeForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
model = User
exclude = ('',)
class VoterAdmin(UserAdmin):
form = VoterChangeForm
add_form = VoterCreationForm
list_filter = UserAdmin.list_filter + ('section',)
fieldsets = (
(None, {'fields': ('username', 'password')}),
(('Personal info'), {'fields': ('first_name', 'last_name', 'section')}),
(('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')}
),
)
admin.site.unregister(User)
admin.site.register(User, VoterAdmin)<|fim▁end|> | section = forms.CharField()
def save(self, commit=True):
user = super(VoterCreationForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser') |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
from django import forms
class VoterCreationForm(UserCreationForm):
section = forms.CharField()
def save(self, commit=True):
<|fim_middle|>
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')
class VoterChangeForm(UserChangeForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterChangeForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
model = User
exclude = ('',)
class VoterAdmin(UserAdmin):
form = VoterChangeForm
add_form = VoterCreationForm
list_filter = UserAdmin.list_filter + ('section',)
fieldsets = (
(None, {'fields': ('username', 'password')}),
(('Personal info'), {'fields': ('first_name', 'last_name', 'section')}),
(('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')}
),
)
admin.site.unregister(User)
admin.site.register(User, VoterAdmin)<|fim▁end|> | user = super(VoterCreationForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
from django import forms
class VoterCreationForm(UserCreationForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterCreationForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
<|fim_middle|>
class VoterChangeForm(UserChangeForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterChangeForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
model = User
exclude = ('',)
class VoterAdmin(UserAdmin):
form = VoterChangeForm
add_form = VoterCreationForm
list_filter = UserAdmin.list_filter + ('section',)
fieldsets = (
(None, {'fields': ('username', 'password')}),
(('Personal info'), {'fields': ('first_name', 'last_name', 'section')}),
(('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')}
),
)
admin.site.unregister(User)
admin.site.register(User, VoterAdmin)<|fim▁end|> | model = User
fields = ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser') |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
from django import forms
class VoterCreationForm(UserCreationForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterCreationForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')
class VoterChangeForm(UserChangeForm):
<|fim_middle|>
class VoterAdmin(UserAdmin):
form = VoterChangeForm
add_form = VoterCreationForm
list_filter = UserAdmin.list_filter + ('section',)
fieldsets = (
(None, {'fields': ('username', 'password')}),
(('Personal info'), {'fields': ('first_name', 'last_name', 'section')}),
(('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')}
),
)
admin.site.unregister(User)
admin.site.register(User, VoterAdmin)<|fim▁end|> | section = forms.CharField()
def save(self, commit=True):
user = super(VoterChangeForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
model = User
exclude = ('',) |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
from django import forms
class VoterCreationForm(UserCreationForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterCreationForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')
class VoterChangeForm(UserChangeForm):
section = forms.CharField()
def save(self, commit=True):
<|fim_middle|>
class Meta:
model = User
exclude = ('',)
class VoterAdmin(UserAdmin):
form = VoterChangeForm
add_form = VoterCreationForm
list_filter = UserAdmin.list_filter + ('section',)
fieldsets = (
(None, {'fields': ('username', 'password')}),
(('Personal info'), {'fields': ('first_name', 'last_name', 'section')}),
(('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')}
),
)
admin.site.unregister(User)
admin.site.register(User, VoterAdmin)<|fim▁end|> | user = super(VoterChangeForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
from django import forms
class VoterCreationForm(UserCreationForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterCreationForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')
class VoterChangeForm(UserChangeForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterChangeForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
<|fim_middle|>
class VoterAdmin(UserAdmin):
form = VoterChangeForm
add_form = VoterCreationForm
list_filter = UserAdmin.list_filter + ('section',)
fieldsets = (
(None, {'fields': ('username', 'password')}),
(('Personal info'), {'fields': ('first_name', 'last_name', 'section')}),
(('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')}
),
)
admin.site.unregister(User)
admin.site.register(User, VoterAdmin)<|fim▁end|> | model = User
exclude = ('',) |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
from django import forms
class VoterCreationForm(UserCreationForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterCreationForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')
class VoterChangeForm(UserChangeForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterChangeForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
model = User
exclude = ('',)
class VoterAdmin(UserAdmin):
<|fim_middle|>
admin.site.unregister(User)
admin.site.register(User, VoterAdmin)<|fim▁end|> | form = VoterChangeForm
add_form = VoterCreationForm
list_filter = UserAdmin.list_filter + ('section',)
fieldsets = (
(None, {'fields': ('username', 'password')}),
(('Personal info'), {'fields': ('first_name', 'last_name', 'section')}),
(('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')}
),
) |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
from django import forms
class VoterCreationForm(UserCreationForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterCreationForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
<|fim_middle|>
return user
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')
class VoterChangeForm(UserChangeForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterChangeForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
model = User
exclude = ('',)
class VoterAdmin(UserAdmin):
form = VoterChangeForm
add_form = VoterCreationForm
list_filter = UserAdmin.list_filter + ('section',)
fieldsets = (
(None, {'fields': ('username', 'password')}),
(('Personal info'), {'fields': ('first_name', 'last_name', 'section')}),
(('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')}
),
)
admin.site.unregister(User)
admin.site.register(User, VoterAdmin)<|fim▁end|> | user.save() |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
from django import forms
class VoterCreationForm(UserCreationForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterCreationForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')
class VoterChangeForm(UserChangeForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterChangeForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
<|fim_middle|>
return user
class Meta:
model = User
exclude = ('',)
class VoterAdmin(UserAdmin):
form = VoterChangeForm
add_form = VoterCreationForm
list_filter = UserAdmin.list_filter + ('section',)
fieldsets = (
(None, {'fields': ('username', 'password')}),
(('Personal info'), {'fields': ('first_name', 'last_name', 'section')}),
(('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')}
),
)
admin.site.unregister(User)
admin.site.register(User, VoterAdmin)<|fim▁end|> | user.save() |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
from django import forms
class VoterCreationForm(UserCreationForm):
section = forms.CharField()
def <|fim_middle|>(self, commit=True):
user = super(VoterCreationForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')
class VoterChangeForm(UserChangeForm):
section = forms.CharField()
def save(self, commit=True):
user = super(VoterChangeForm, self).save(commit=False)
user.section = self.cleaned_data['section']
if commit:
user.save()
return user
class Meta:
model = User
exclude = ('',)
class VoterAdmin(UserAdmin):
form = VoterChangeForm
add_form = VoterCreationForm
list_filter = UserAdmin.list_filter + ('section',)
fieldsets = (
(None, {'fields': ('username', 'password')}),
(('Personal info'), {'fields': ('first_name', 'last_name', 'section')}),
(('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')}
),
)
admin.site.unregister(User)
admin.site.register(User, VoterAdmin)<|fim▁end|> | save |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.