repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
asciimoo/drawille
drawille.py
Canvas.set_text
def set_text(self, x, y, text): """Set text to the given coords. :param x: x coordinate of the text start position :param y: y coordinate of the text start position """ col, row = get_pos(x, y) for i,c in enumerate(text): self.chars[row][col+i] = c
python
def set_text(self, x, y, text): """Set text to the given coords. :param x: x coordinate of the text start position :param y: y coordinate of the text start position """ col, row = get_pos(x, y) for i,c in enumerate(text): self.chars[row][col+i] = c
[ "def", "set_text", "(", "self", ",", "x", ",", "y", ",", "text", ")", ":", "col", ",", "row", "=", "get_pos", "(", "x", ",", "y", ")", "for", "i", ",", "c", "in", "enumerate", "(", "text", ")", ":", "self", ".", "chars", "[", "row", "]", "[...
Set text to the given coords. :param x: x coordinate of the text start position :param y: y coordinate of the text start position
[ "Set", "text", "to", "the", "given", "coords", "." ]
ab58bba76cad68674ce50df7382c235ed21ab5ae
https://github.com/asciimoo/drawille/blob/ab58bba76cad68674ce50df7382c235ed21ab5ae/drawille.py#L168-L177
train
206,100
asciimoo/drawille
drawille.py
Canvas.get
def get(self, x, y): """Get the state of a pixel. Returns bool. :param x: x coordinate of the pixel :param y: y coordinate of the pixel """ x = normalize(x) y = normalize(y) dot_index = pixel_map[y % 4][x % 2] col, row = get_pos(x, y) char = self.chars.get(row, {}).get(col) if not char: return False if type(char) != int: return True return bool(char & dot_index)
python
def get(self, x, y): """Get the state of a pixel. Returns bool. :param x: x coordinate of the pixel :param y: y coordinate of the pixel """ x = normalize(x) y = normalize(y) dot_index = pixel_map[y % 4][x % 2] col, row = get_pos(x, y) char = self.chars.get(row, {}).get(col) if not char: return False if type(char) != int: return True return bool(char & dot_index)
[ "def", "get", "(", "self", ",", "x", ",", "y", ")", ":", "x", "=", "normalize", "(", "x", ")", "y", "=", "normalize", "(", "y", ")", "dot_index", "=", "pixel_map", "[", "y", "%", "4", "]", "[", "x", "%", "2", "]", "col", ",", "row", "=", ...
Get the state of a pixel. Returns bool. :param x: x coordinate of the pixel :param y: y coordinate of the pixel
[ "Get", "the", "state", "of", "a", "pixel", ".", "Returns", "bool", "." ]
ab58bba76cad68674ce50df7382c235ed21ab5ae
https://github.com/asciimoo/drawille/blob/ab58bba76cad68674ce50df7382c235ed21ab5ae/drawille.py#L180-L198
train
206,101
asciimoo/drawille
drawille.py
Turtle.forward
def forward(self, step): """Move the turtle forward. :param step: Integer. Distance to move forward. """ x = self.pos_x + math.cos(math.radians(self.rotation)) * step y = self.pos_y + math.sin(math.radians(self.rotation)) * step prev_brush_state = self.brush_on self.brush_on = True self.move(x, y) self.brush_on = prev_brush_state
python
def forward(self, step): """Move the turtle forward. :param step: Integer. Distance to move forward. """ x = self.pos_x + math.cos(math.radians(self.rotation)) * step y = self.pos_y + math.sin(math.radians(self.rotation)) * step prev_brush_state = self.brush_on self.brush_on = True self.move(x, y) self.brush_on = prev_brush_state
[ "def", "forward", "(", "self", ",", "step", ")", ":", "x", "=", "self", ".", "pos_x", "+", "math", ".", "cos", "(", "math", ".", "radians", "(", "self", ".", "rotation", ")", ")", "*", "step", "y", "=", "self", ".", "pos_y", "+", "math", ".", ...
Move the turtle forward. :param step: Integer. Distance to move forward.
[ "Move", "the", "turtle", "forward", "." ]
ab58bba76cad68674ce50df7382c235ed21ab5ae
https://github.com/asciimoo/drawille/blob/ab58bba76cad68674ce50df7382c235ed21ab5ae/drawille.py#L329-L339
train
206,102
asciimoo/drawille
drawille.py
Turtle.move
def move(self, x, y): """Move the turtle to a coordinate. :param x: x coordinate :param y: y coordinate """ if self.brush_on: for lx, ly in line(self.pos_x, self.pos_y, x, y): self.set(lx, ly) self.pos_x = x self.pos_y = y
python
def move(self, x, y): """Move the turtle to a coordinate. :param x: x coordinate :param y: y coordinate """ if self.brush_on: for lx, ly in line(self.pos_x, self.pos_y, x, y): self.set(lx, ly) self.pos_x = x self.pos_y = y
[ "def", "move", "(", "self", ",", "x", ",", "y", ")", ":", "if", "self", ".", "brush_on", ":", "for", "lx", ",", "ly", "in", "line", "(", "self", ".", "pos_x", ",", "self", ".", "pos_y", ",", "x", ",", "y", ")", ":", "self", ".", "set", "(",...
Move the turtle to a coordinate. :param x: x coordinate :param y: y coordinate
[ "Move", "the", "turtle", "to", "a", "coordinate", "." ]
ab58bba76cad68674ce50df7382c235ed21ab5ae
https://github.com/asciimoo/drawille/blob/ab58bba76cad68674ce50df7382c235ed21ab5ae/drawille.py#L342-L353
train
206,103
karan/TPB
tpb/utils.py
URL
def URL(base, path, segments=None, defaults=None): """ URL segment handler capable of getting and setting segments by name. The URL is constructed by joining base, path and segments. For each segment a property capable of getting and setting that segment is created dynamically. """ # Make a copy of the Segments class url_class = type(Segments.__name__, Segments.__bases__, dict(Segments.__dict__)) segments = [] if segments is None else segments defaults = [] if defaults is None else defaults # For each segment attach a property capable of getting and setting it for segment in segments: setattr(url_class, segment, url_class._segment(segment)) # Instantiate the class with the actual parameters return url_class(base, path, segments, defaults)
python
def URL(base, path, segments=None, defaults=None): """ URL segment handler capable of getting and setting segments by name. The URL is constructed by joining base, path and segments. For each segment a property capable of getting and setting that segment is created dynamically. """ # Make a copy of the Segments class url_class = type(Segments.__name__, Segments.__bases__, dict(Segments.__dict__)) segments = [] if segments is None else segments defaults = [] if defaults is None else defaults # For each segment attach a property capable of getting and setting it for segment in segments: setattr(url_class, segment, url_class._segment(segment)) # Instantiate the class with the actual parameters return url_class(base, path, segments, defaults)
[ "def", "URL", "(", "base", ",", "path", ",", "segments", "=", "None", ",", "defaults", "=", "None", ")", ":", "# Make a copy of the Segments class", "url_class", "=", "type", "(", "Segments", ".", "__name__", ",", "Segments", ".", "__bases__", ",", "dict", ...
URL segment handler capable of getting and setting segments by name. The URL is constructed by joining base, path and segments. For each segment a property capable of getting and setting that segment is created dynamically.
[ "URL", "segment", "handler", "capable", "of", "getting", "and", "setting", "segments", "by", "name", ".", "The", "URL", "is", "constructed", "by", "joining", "base", "path", "and", "segments", "." ]
f424a73a10d4bcf4e363d7e7e8cb915a3a057671
https://github.com/karan/TPB/blob/f424a73a10d4bcf4e363d7e7e8cb915a3a057671/tpb/utils.py#L6-L23
train
206,104
karan/TPB
tpb/utils.py
Segments._segment
def _segment(cls, segment): """ Returns a property capable of setting and getting a segment. """ return property( fget=lambda x: cls._get_segment(x, segment), fset=lambda x, v: cls._set_segment(x, segment, v), )
python
def _segment(cls, segment): """ Returns a property capable of setting and getting a segment. """ return property( fget=lambda x: cls._get_segment(x, segment), fset=lambda x, v: cls._set_segment(x, segment, v), )
[ "def", "_segment", "(", "cls", ",", "segment", ")", ":", "return", "property", "(", "fget", "=", "lambda", "x", ":", "cls", ".", "_get_segment", "(", "x", ",", "segment", ")", ",", "fset", "=", "lambda", "x", ",", "v", ":", "cls", ".", "_set_segmen...
Returns a property capable of setting and getting a segment.
[ "Returns", "a", "property", "capable", "of", "setting", "and", "getting", "a", "segment", "." ]
f424a73a10d4bcf4e363d7e7e8cb915a3a057671
https://github.com/karan/TPB/blob/f424a73a10d4bcf4e363d7e7e8cb915a3a057671/tpb/utils.py#L56-L63
train
206,105
karan/TPB
tpb/tpb.py
self_if_parameters
def self_if_parameters(func): """ If any parameter is given, the method's binded object is returned after executing the function. Else the function's result is returned. """ @wraps(func) def wrapper(self, *args, **kwargs): result = func(self, *args, **kwargs) if args or kwargs: return self else: return result return wrapper
python
def self_if_parameters(func): """ If any parameter is given, the method's binded object is returned after executing the function. Else the function's result is returned. """ @wraps(func) def wrapper(self, *args, **kwargs): result = func(self, *args, **kwargs) if args or kwargs: return self else: return result return wrapper
[ "def", "self_if_parameters", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs",...
If any parameter is given, the method's binded object is returned after executing the function. Else the function's result is returned.
[ "If", "any", "parameter", "is", "given", "the", "method", "s", "binded", "object", "is", "returned", "after", "executing", "the", "function", ".", "Else", "the", "function", "s", "result", "is", "returned", "." ]
f424a73a10d4bcf4e363d7e7e8cb915a3a057671
https://github.com/karan/TPB/blob/f424a73a10d4bcf4e363d7e7e8cb915a3a057671/tpb/tpb.py#L29-L41
train
206,106
karan/TPB
tpb/tpb.py
List.items
def items(self): """ Request URL and parse response. Yield a ``Torrent`` for every torrent on page. """ request = get(str(self.url), headers={'User-Agent' : "Magic Browser","origin_req_host" : "thepiratebay.se"}) root = html.fromstring(request.text) items = [self._build_torrent(row) for row in self._get_torrent_rows(root)] for item in items: yield item
python
def items(self): """ Request URL and parse response. Yield a ``Torrent`` for every torrent on page. """ request = get(str(self.url), headers={'User-Agent' : "Magic Browser","origin_req_host" : "thepiratebay.se"}) root = html.fromstring(request.text) items = [self._build_torrent(row) for row in self._get_torrent_rows(root)] for item in items: yield item
[ "def", "items", "(", "self", ")", ":", "request", "=", "get", "(", "str", "(", "self", ".", "url", ")", ",", "headers", "=", "{", "'User-Agent'", ":", "\"Magic Browser\"", ",", "\"origin_req_host\"", ":", "\"thepiratebay.se\"", "}", ")", "root", "=", "ht...
Request URL and parse response. Yield a ``Torrent`` for every torrent on page.
[ "Request", "URL", "and", "parse", "response", ".", "Yield", "a", "Torrent", "for", "every", "torrent", "on", "page", "." ]
f424a73a10d4bcf4e363d7e7e8cb915a3a057671
https://github.com/karan/TPB/blob/f424a73a10d4bcf4e363d7e7e8cb915a3a057671/tpb/tpb.py#L54-L64
train
206,107
karan/TPB
tpb/tpb.py
List._build_torrent
def _build_torrent(self, row): """ Builds and returns a Torrent object for the given parsed row. """ # Scrape, strip and build!!! cols = row.findall('.//td') # split the row into it's columns # this column contains the categories [category, sub_category] = [c.text for c in cols[0].findall('.//a')] # this column with all important info links = cols[1].findall('.//a') # get 4 a tags from this columns title = unicode(links[0].text) url = self.url.build().path(links[0].get('href')) magnet_link = links[1].get('href') # the magnet download link try: torrent_link = links[2].get('href') # the torrent download link if not torrent_link.endswith('.torrent'): torrent_link = None except IndexError: torrent_link = None comments = 0 has_cover = 'No' images = cols[1].findall('.//img') for image in images: image_title = image.get('title') if image_title is None: continue if "comments" in image_title: comments = int(image_title.split(" ")[3]) if "cover" in image_title: has_cover = 'Yes' user_status = "MEMBER" if links[-2].get('href').startswith("/user/"): user_status = links[-2].find('.//img').get('title') meta_col = cols[1].find('.//font').text_content() # don't need user match = self._meta.match(meta_col) created = match.groups()[0].replace('\xa0', ' ') size = match.groups()[1].replace('\xa0', ' ') user = match.groups()[2] # uploaded by user # last 2 columns for seeders and leechers seeders = int(cols[2].text) leechers = int(cols[3].text) t = Torrent(title, url, category, sub_category, magnet_link, torrent_link, comments, has_cover, user_status, created, size, user, seeders, leechers) return t
python
def _build_torrent(self, row): """ Builds and returns a Torrent object for the given parsed row. """ # Scrape, strip and build!!! cols = row.findall('.//td') # split the row into it's columns # this column contains the categories [category, sub_category] = [c.text for c in cols[0].findall('.//a')] # this column with all important info links = cols[1].findall('.//a') # get 4 a tags from this columns title = unicode(links[0].text) url = self.url.build().path(links[0].get('href')) magnet_link = links[1].get('href') # the magnet download link try: torrent_link = links[2].get('href') # the torrent download link if not torrent_link.endswith('.torrent'): torrent_link = None except IndexError: torrent_link = None comments = 0 has_cover = 'No' images = cols[1].findall('.//img') for image in images: image_title = image.get('title') if image_title is None: continue if "comments" in image_title: comments = int(image_title.split(" ")[3]) if "cover" in image_title: has_cover = 'Yes' user_status = "MEMBER" if links[-2].get('href').startswith("/user/"): user_status = links[-2].find('.//img').get('title') meta_col = cols[1].find('.//font').text_content() # don't need user match = self._meta.match(meta_col) created = match.groups()[0].replace('\xa0', ' ') size = match.groups()[1].replace('\xa0', ' ') user = match.groups()[2] # uploaded by user # last 2 columns for seeders and leechers seeders = int(cols[2].text) leechers = int(cols[3].text) t = Torrent(title, url, category, sub_category, magnet_link, torrent_link, comments, has_cover, user_status, created, size, user, seeders, leechers) return t
[ "def", "_build_torrent", "(", "self", ",", "row", ")", ":", "# Scrape, strip and build!!!", "cols", "=", "row", ".", "findall", "(", "'.//td'", ")", "# split the row into it's columns", "# this column contains the categories", "[", "category", ",", "sub_category", "]", ...
Builds and returns a Torrent object for the given parsed row.
[ "Builds", "and", "returns", "a", "Torrent", "object", "for", "the", "given", "parsed", "row", "." ]
f424a73a10d4bcf4e363d7e7e8cb915a3a057671
https://github.com/karan/TPB/blob/f424a73a10d4bcf4e363d7e7e8cb915a3a057671/tpb/tpb.py#L80-L127
train
206,108
karan/TPB
tpb/tpb.py
Paginated.items
def items(self): """ Request URL and parse response. Yield a ``Torrent`` for every torrent on page. If in multipage mode, Torrents from next pages are automatically chained. """ if self._multipage: while True: # Pool for more torrents items = super(Paginated, self).items() # Stop if no more torrents first = next(items, None) if first is None: raise StopIteration() # Yield them if not else: yield first for item in items: yield item # Go to the next page self.next() else: for item in super(Paginated, self).items(): yield item
python
def items(self): """ Request URL and parse response. Yield a ``Torrent`` for every torrent on page. If in multipage mode, Torrents from next pages are automatically chained. """ if self._multipage: while True: # Pool for more torrents items = super(Paginated, self).items() # Stop if no more torrents first = next(items, None) if first is None: raise StopIteration() # Yield them if not else: yield first for item in items: yield item # Go to the next page self.next() else: for item in super(Paginated, self).items(): yield item
[ "def", "items", "(", "self", ")", ":", "if", "self", ".", "_multipage", ":", "while", "True", ":", "# Pool for more torrents", "items", "=", "super", "(", "Paginated", ",", "self", ")", ".", "items", "(", ")", "# Stop if no more torrents", "first", "=", "n...
Request URL and parse response. Yield a ``Torrent`` for every torrent on page. If in multipage mode, Torrents from next pages are automatically chained.
[ "Request", "URL", "and", "parse", "response", ".", "Yield", "a", "Torrent", "for", "every", "torrent", "on", "page", ".", "If", "in", "multipage", "mode", "Torrents", "from", "next", "pages", "are", "automatically", "chained", "." ]
f424a73a10d4bcf4e363d7e7e8cb915a3a057671
https://github.com/karan/TPB/blob/f424a73a10d4bcf4e363d7e7e8cb915a3a057671/tpb/tpb.py#L141-L164
train
206,109
karan/TPB
tpb/tpb.py
Paginated.page
def page(self, number=None): """ If page is given, modify the URL correspondingly, return the current page otherwise. """ if number is None: return int(self.url.page) self.url.page = str(number)
python
def page(self, number=None): """ If page is given, modify the URL correspondingly, return the current page otherwise. """ if number is None: return int(self.url.page) self.url.page = str(number)
[ "def", "page", "(", "self", ",", "number", "=", "None", ")", ":", "if", "number", "is", "None", ":", "return", "int", "(", "self", ".", "url", ".", "page", ")", "self", ".", "url", ".", "page", "=", "str", "(", "number", ")" ]
If page is given, modify the URL correspondingly, return the current page otherwise.
[ "If", "page", "is", "given", "modify", "the", "URL", "correspondingly", "return", "the", "current", "page", "otherwise", "." ]
f424a73a10d4bcf4e363d7e7e8cb915a3a057671
https://github.com/karan/TPB/blob/f424a73a10d4bcf4e363d7e7e8cb915a3a057671/tpb/tpb.py#L174-L181
train
206,110
karan/TPB
tpb/tpb.py
Search.query
def query(self, query=None): """ If query is given, modify the URL correspondingly, return the current query otherwise. """ if query is None: return self.url.query self.url.query = query
python
def query(self, query=None): """ If query is given, modify the URL correspondingly, return the current query otherwise. """ if query is None: return self.url.query self.url.query = query
[ "def", "query", "(", "self", ",", "query", "=", "None", ")", ":", "if", "query", "is", "None", ":", "return", "self", ".", "url", ".", "query", "self", ".", "url", ".", "query", "=", "query" ]
If query is given, modify the URL correspondingly, return the current query otherwise.
[ "If", "query", "is", "given", "modify", "the", "URL", "correspondingly", "return", "the", "current", "query", "otherwise", "." ]
f424a73a10d4bcf4e363d7e7e8cb915a3a057671
https://github.com/karan/TPB/blob/f424a73a10d4bcf4e363d7e7e8cb915a3a057671/tpb/tpb.py#L213-L220
train
206,111
karan/TPB
tpb/tpb.py
Search.order
def order(self, order=None): """ If order is given, modify the URL correspondingly, return the current order otherwise. """ if order is None: return int(self.url.order) self.url.order = str(order)
python
def order(self, order=None): """ If order is given, modify the URL correspondingly, return the current order otherwise. """ if order is None: return int(self.url.order) self.url.order = str(order)
[ "def", "order", "(", "self", ",", "order", "=", "None", ")", ":", "if", "order", "is", "None", ":", "return", "int", "(", "self", ".", "url", ".", "order", ")", "self", ".", "url", ".", "order", "=", "str", "(", "order", ")" ]
If order is given, modify the URL correspondingly, return the current order otherwise.
[ "If", "order", "is", "given", "modify", "the", "URL", "correspondingly", "return", "the", "current", "order", "otherwise", "." ]
f424a73a10d4bcf4e363d7e7e8cb915a3a057671
https://github.com/karan/TPB/blob/f424a73a10d4bcf4e363d7e7e8cb915a3a057671/tpb/tpb.py#L223-L230
train
206,112
karan/TPB
tpb/tpb.py
Search.category
def category(self, category=None): """ If category is given, modify the URL correspondingly, return the current category otherwise. """ if category is None: return int(self.url.category) self.url.category = str(category)
python
def category(self, category=None): """ If category is given, modify the URL correspondingly, return the current category otherwise. """ if category is None: return int(self.url.category) self.url.category = str(category)
[ "def", "category", "(", "self", ",", "category", "=", "None", ")", ":", "if", "category", "is", "None", ":", "return", "int", "(", "self", ".", "url", ".", "category", ")", "self", ".", "url", ".", "category", "=", "str", "(", "category", ")" ]
If category is given, modify the URL correspondingly, return the current category otherwise.
[ "If", "category", "is", "given", "modify", "the", "URL", "correspondingly", "return", "the", "current", "category", "otherwise", "." ]
f424a73a10d4bcf4e363d7e7e8cb915a3a057671
https://github.com/karan/TPB/blob/f424a73a10d4bcf4e363d7e7e8cb915a3a057671/tpb/tpb.py#L233-L240
train
206,113
karan/TPB
tpb/tpb.py
TPB.search
def search(self, query, page=0, order=7, category=0, multipage=False): """ Searches TPB for query and returns a list of paginated Torrents capable of changing query, categories and orders. """ search = Search(self.base_url, query, page, order, category) if multipage: search.multipage() return search
python
def search(self, query, page=0, order=7, category=0, multipage=False): """ Searches TPB for query and returns a list of paginated Torrents capable of changing query, categories and orders. """ search = Search(self.base_url, query, page, order, category) if multipage: search.multipage() return search
[ "def", "search", "(", "self", ",", "query", ",", "page", "=", "0", ",", "order", "=", "7", ",", "category", "=", "0", ",", "multipage", "=", "False", ")", ":", "search", "=", "Search", "(", "self", ".", "base_url", ",", "query", ",", "page", ",",...
Searches TPB for query and returns a list of paginated Torrents capable of changing query, categories and orders.
[ "Searches", "TPB", "for", "query", "and", "returns", "a", "list", "of", "paginated", "Torrents", "capable", "of", "changing", "query", "categories", "and", "orders", "." ]
f424a73a10d4bcf4e363d7e7e8cb915a3a057671
https://github.com/karan/TPB/blob/f424a73a10d4bcf4e363d7e7e8cb915a3a057671/tpb/tpb.py#L292-L300
train
206,114
karan/TPB
tpb/tpb.py
Torrent.created
def created(self): """ Attempt to parse the human readable torrent creation datetime. """ timestamp, current = self._created if timestamp.endswith('ago'): quantity, kind, ago = timestamp.split() quantity = int(quantity) if 'sec' in kind: current -= quantity elif 'min' in kind: current -= quantity * 60 elif 'hour' in kind: current -= quantity * 60 * 60 return datetime.datetime.fromtimestamp(current) current = datetime.datetime.fromtimestamp(current) timestamp = timestamp.replace( 'Y-day', str(current.date() - datetime.timedelta(days=1))) timestamp = timestamp.replace('Today', current.date().isoformat()) try: return dateutil.parser.parse(timestamp) except: return current
python
def created(self): """ Attempt to parse the human readable torrent creation datetime. """ timestamp, current = self._created if timestamp.endswith('ago'): quantity, kind, ago = timestamp.split() quantity = int(quantity) if 'sec' in kind: current -= quantity elif 'min' in kind: current -= quantity * 60 elif 'hour' in kind: current -= quantity * 60 * 60 return datetime.datetime.fromtimestamp(current) current = datetime.datetime.fromtimestamp(current) timestamp = timestamp.replace( 'Y-day', str(current.date() - datetime.timedelta(days=1))) timestamp = timestamp.replace('Today', current.date().isoformat()) try: return dateutil.parser.parse(timestamp) except: return current
[ "def", "created", "(", "self", ")", ":", "timestamp", ",", "current", "=", "self", ".", "_created", "if", "timestamp", ".", "endswith", "(", "'ago'", ")", ":", "quantity", ",", "kind", ",", "ago", "=", "timestamp", ".", "split", "(", ")", "quantity", ...
Attempt to parse the human readable torrent creation datetime.
[ "Attempt", "to", "parse", "the", "human", "readable", "torrent", "creation", "datetime", "." ]
f424a73a10d4bcf4e363d7e7e8cb915a3a057671
https://github.com/karan/TPB/blob/f424a73a10d4bcf4e363d7e7e8cb915a3a057671/tpb/tpb.py#L366-L388
train
206,115
karan/TPB
tpb/tpb.py
Torrent.print_torrent
def print_torrent(self): """ Print the details of a torrent """ print('Title: %s' % self.title) print('URL: %s' % self.url) print('Category: %s' % self.category) print('Sub-Category: %s' % self.sub_category) print('Magnet Link: %s' % self.magnet_link) print('Torrent Link: %s' % self.torrent_link) print('Uploaded: %s' % self.created) print('Comments: %d' % self.comments) print('Has Cover Image: %s' % self.has_cover) print('User Status: %s' % self.user_status) print('Size: %s' % self.size) print('User: %s' % self.user) print('Seeders: %d' % self.seeders) print('Leechers: %d' % self.leechers)
python
def print_torrent(self): """ Print the details of a torrent """ print('Title: %s' % self.title) print('URL: %s' % self.url) print('Category: %s' % self.category) print('Sub-Category: %s' % self.sub_category) print('Magnet Link: %s' % self.magnet_link) print('Torrent Link: %s' % self.torrent_link) print('Uploaded: %s' % self.created) print('Comments: %d' % self.comments) print('Has Cover Image: %s' % self.has_cover) print('User Status: %s' % self.user_status) print('Size: %s' % self.size) print('User: %s' % self.user) print('Seeders: %d' % self.seeders) print('Leechers: %d' % self.leechers)
[ "def", "print_torrent", "(", "self", ")", ":", "print", "(", "'Title: %s'", "%", "self", ".", "title", ")", "print", "(", "'URL: %s'", "%", "self", ".", "url", ")", "print", "(", "'Category: %s'", "%", "self", ".", "category", ")", "print", "(", "'Sub-...
Print the details of a torrent
[ "Print", "the", "details", "of", "a", "torrent" ]
f424a73a10d4bcf4e363d7e7e8cb915a3a057671
https://github.com/karan/TPB/blob/f424a73a10d4bcf4e363d7e7e8cb915a3a057671/tpb/tpb.py#L390-L407
train
206,116
instacart/lore
lore/ansi.py
foreground
def foreground(color, content, readline=False): """ Color the text of the content :param color: pick a constant, any constant :type color: int :param content: Whatever you want to say... :type content: unicode :return: ansi string :rtype: unicode """ return encode(color, readline=readline) + content + encode(DEFAULT, readline=readline)
python
def foreground(color, content, readline=False): """ Color the text of the content :param color: pick a constant, any constant :type color: int :param content: Whatever you want to say... :type content: unicode :return: ansi string :rtype: unicode """ return encode(color, readline=readline) + content + encode(DEFAULT, readline=readline)
[ "def", "foreground", "(", "color", ",", "content", ",", "readline", "=", "False", ")", ":", "return", "encode", "(", "color", ",", "readline", "=", "readline", ")", "+", "content", "+", "encode", "(", "DEFAULT", ",", "readline", "=", "readline", ")" ]
Color the text of the content :param color: pick a constant, any constant :type color: int :param content: Whatever you want to say... :type content: unicode :return: ansi string :rtype: unicode
[ "Color", "the", "text", "of", "the", "content" ]
0367bde9a52e69162832906acc61e8d65c5ec5d4
https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/ansi.py#L157-L167
train
206,117
instacart/lore
lore/metadata/__init__.py
Crud.get_or_create
def get_or_create(cls, **kwargs): ''' Creates an object or returns the object if exists credit to Kevin @ StackOverflow from: http://stackoverflow.com/questions/2546207/does-sqlalchemy-have-an-equivalent-of-djangos-get-or-create ''' session = Session() instance = session.query(cls).filter_by(**kwargs).first() session.close() if not instance: self = cls(**kwargs) self.save() else: self = instance return self
python
def get_or_create(cls, **kwargs): ''' Creates an object or returns the object if exists credit to Kevin @ StackOverflow from: http://stackoverflow.com/questions/2546207/does-sqlalchemy-have-an-equivalent-of-djangos-get-or-create ''' session = Session() instance = session.query(cls).filter_by(**kwargs).first() session.close() if not instance: self = cls(**kwargs) self.save() else: self = instance return self
[ "def", "get_or_create", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "session", "=", "Session", "(", ")", "instance", "=", "session", ".", "query", "(", "cls", ")", ".", "filter_by", "(", "*", "*", "kwargs", ")", ".", "first", "(", ")", "session"...
Creates an object or returns the object if exists credit to Kevin @ StackOverflow from: http://stackoverflow.com/questions/2546207/does-sqlalchemy-have-an-equivalent-of-djangos-get-or-create
[ "Creates", "an", "object", "or", "returns", "the", "object", "if", "exists", "credit", "to", "Kevin" ]
0367bde9a52e69162832906acc61e8d65c5ec5d4
https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/metadata/__init__.py#L77-L93
train
206,118
instacart/lore
lore/util.py
calling_logger
def calling_logger(height=1): """ Obtain a logger for the calling module. Uses the inspect module to find the name of the calling function and its position in the module hierarchy. With the optional height argument, logs for caller's caller, and so forth. see: http://stackoverflow.com/a/900404/48251 """ stack = inspect.stack() height = min(len(stack) - 1, height) caller = stack[height] scope = caller[0].f_globals path = scope['__name__'] if path == '__main__': path = scope['__package__'] or os.path.basename(sys.argv[0]) return logging.getLogger(path)
python
def calling_logger(height=1): """ Obtain a logger for the calling module. Uses the inspect module to find the name of the calling function and its position in the module hierarchy. With the optional height argument, logs for caller's caller, and so forth. see: http://stackoverflow.com/a/900404/48251 """ stack = inspect.stack() height = min(len(stack) - 1, height) caller = stack[height] scope = caller[0].f_globals path = scope['__name__'] if path == '__main__': path = scope['__package__'] or os.path.basename(sys.argv[0]) return logging.getLogger(path)
[ "def", "calling_logger", "(", "height", "=", "1", ")", ":", "stack", "=", "inspect", ".", "stack", "(", ")", "height", "=", "min", "(", "len", "(", "stack", ")", "-", "1", ",", "height", ")", "caller", "=", "stack", "[", "height", "]", "scope", "...
Obtain a logger for the calling module. Uses the inspect module to find the name of the calling function and its position in the module hierarchy. With the optional height argument, logs for caller's caller, and so forth. see: http://stackoverflow.com/a/900404/48251
[ "Obtain", "a", "logger", "for", "the", "calling", "module", "." ]
0367bde9a52e69162832906acc61e8d65c5ec5d4
https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/util.py#L266-L282
train
206,119
instacart/lore
lore/encoders.py
Base.fillna
def fillna(self, series, addition=0): """ Fills with encoder specific default values. :param data: examined to determine defaults :param addition: uniquely identify this set of fillnas if necessary :return: filled data """ if series.dtype == numpy.object: return series return series.fillna(self.missing_value + addition).astype(self.dtype)
python
def fillna(self, series, addition=0): """ Fills with encoder specific default values. :param data: examined to determine defaults :param addition: uniquely identify this set of fillnas if necessary :return: filled data """ if series.dtype == numpy.object: return series return series.fillna(self.missing_value + addition).astype(self.dtype)
[ "def", "fillna", "(", "self", ",", "series", ",", "addition", "=", "0", ")", ":", "if", "series", ".", "dtype", "==", "numpy", ".", "object", ":", "return", "series", "return", "series", ".", "fillna", "(", "self", ".", "missing_value", "+", "addition"...
Fills with encoder specific default values. :param data: examined to determine defaults :param addition: uniquely identify this set of fillnas if necessary :return: filled data
[ "Fills", "with", "encoder", "specific", "default", "values", "." ]
0367bde9a52e69162832906acc61e8d65c5ec5d4
https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/encoders.py#L130-L141
train
206,120
instacart/lore
lore/models/base.py
Base.hyper_parameter_search
def hyper_parameter_search( self, param_distributions, n_iter=10, scoring=None, fit_params={}, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*njobs', random_state=None, error_score='raise', return_train_score=True, test=True, score=True, save=True, custom_data=None ): """Random search hyper params """ params = locals() params.pop('self') self.fitting = lore.metadata.Fitting.create( model=self.name, custom_data=custom_data, snapshot=lore.metadata.Snapshot(pipeline=self.pipeline.name, head=str(self.pipeline.training_data.head(2)), tail=str(self.pipeline.training_data.tail(2)) ) ) result = RandomizedSearchCV( self.estimator, param_distributions, n_iter=n_iter, scoring=scoring, n_jobs=n_jobs, iid=iid, refit=refit, cv=cv, verbose=verbose, pre_dispatch=pre_dispatch, random_state=random_state, error_score=error_score, return_train_score=return_train_score ).fit( self.pipeline.encoded_training_data.x, y=self.pipeline.encoded_training_data.y, validation_x=self.pipeline.encoded_validation_data.x, validation_y=self.pipeline.encoded_validation_data.y, **fit_params ) self.estimator = result.best_estimator_ self.stats = {} self.estimator_kwargs = self.estimator.__getstate__() if test: self.stats['test'] = self.evaluate(self.pipeline.test_data) if score: self.stats['score'] = self.score(self.pipeline.test_data) self.complete_fitting() if save: self.save() return result
python
def hyper_parameter_search( self, param_distributions, n_iter=10, scoring=None, fit_params={}, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*njobs', random_state=None, error_score='raise', return_train_score=True, test=True, score=True, save=True, custom_data=None ): """Random search hyper params """ params = locals() params.pop('self') self.fitting = lore.metadata.Fitting.create( model=self.name, custom_data=custom_data, snapshot=lore.metadata.Snapshot(pipeline=self.pipeline.name, head=str(self.pipeline.training_data.head(2)), tail=str(self.pipeline.training_data.tail(2)) ) ) result = RandomizedSearchCV( self.estimator, param_distributions, n_iter=n_iter, scoring=scoring, n_jobs=n_jobs, iid=iid, refit=refit, cv=cv, verbose=verbose, pre_dispatch=pre_dispatch, random_state=random_state, error_score=error_score, return_train_score=return_train_score ).fit( self.pipeline.encoded_training_data.x, y=self.pipeline.encoded_training_data.y, validation_x=self.pipeline.encoded_validation_data.x, validation_y=self.pipeline.encoded_validation_data.y, **fit_params ) self.estimator = result.best_estimator_ self.stats = {} self.estimator_kwargs = self.estimator.__getstate__() if test: self.stats['test'] = self.evaluate(self.pipeline.test_data) if score: self.stats['score'] = self.score(self.pipeline.test_data) self.complete_fitting() if save: self.save() return result
[ "def", "hyper_parameter_search", "(", "self", ",", "param_distributions", ",", "n_iter", "=", "10", ",", "scoring", "=", "None", ",", "fit_params", "=", "{", "}", ",", "n_jobs", "=", "1", ",", "iid", "=", "True", ",", "refit", "=", "True", ",", "cv", ...
Random search hyper params
[ "Random", "search", "hyper", "params" ]
0367bde9a52e69162832906acc61e8d65c5ec5d4
https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/models/base.py#L166-L235
train
206,121
instacart/lore
lore/env.py
require
def require(packages): """Ensures that a pypi package has been installed into the App's python environment. If not, the package will be installed and your env will be rebooted. Example: :: lore.env.require('pandas') # -> pandas is required. Dependencies added to requirements.txt :param packages: requirements.txt style name and versions of packages :type packages: [unicode] """ global INSTALLED_PACKAGES, _new_requirements if _new_requirements: INSTALLED_PACKAGES = None set_installed_packages() if not INSTALLED_PACKAGES: return if not isinstance(packages, list): packages = [packages] missing = [] for package in packages: name = re.split(r'[!<>=]', package)[0].lower() if name not in INSTALLED_PACKAGES: print(ansi.info() + ' %s is required.' % package) missing += [package] if missing: mode = 'a' if os.path.exists(REQUIREMENTS) else 'w' with open(REQUIREMENTS, mode) as requirements: requirements.write('\n' + '\n'.join(missing) + '\n') print(ansi.info() + ' Dependencies added to requirements.txt. Rebooting.') _new_requirements = True import lore.__main__ lore.__main__.install(None, None) reboot('--env-checked')
python
def require(packages): """Ensures that a pypi package has been installed into the App's python environment. If not, the package will be installed and your env will be rebooted. Example: :: lore.env.require('pandas') # -> pandas is required. Dependencies added to requirements.txt :param packages: requirements.txt style name and versions of packages :type packages: [unicode] """ global INSTALLED_PACKAGES, _new_requirements if _new_requirements: INSTALLED_PACKAGES = None set_installed_packages() if not INSTALLED_PACKAGES: return if not isinstance(packages, list): packages = [packages] missing = [] for package in packages: name = re.split(r'[!<>=]', package)[0].lower() if name not in INSTALLED_PACKAGES: print(ansi.info() + ' %s is required.' % package) missing += [package] if missing: mode = 'a' if os.path.exists(REQUIREMENTS) else 'w' with open(REQUIREMENTS, mode) as requirements: requirements.write('\n' + '\n'.join(missing) + '\n') print(ansi.info() + ' Dependencies added to requirements.txt. Rebooting.') _new_requirements = True import lore.__main__ lore.__main__.install(None, None) reboot('--env-checked')
[ "def", "require", "(", "packages", ")", ":", "global", "INSTALLED_PACKAGES", ",", "_new_requirements", "if", "_new_requirements", ":", "INSTALLED_PACKAGES", "=", "None", "set_installed_packages", "(", ")", "if", "not", "INSTALLED_PACKAGES", ":", "return", "if", "not...
Ensures that a pypi package has been installed into the App's python environment. If not, the package will be installed and your env will be rebooted. Example: :: lore.env.require('pandas') # -> pandas is required. Dependencies added to requirements.txt :param packages: requirements.txt style name and versions of packages :type packages: [unicode]
[ "Ensures", "that", "a", "pypi", "package", "has", "been", "installed", "into", "the", "App", "s", "python", "environment", ".", "If", "not", "the", "package", "will", "be", "installed", "and", "your", "env", "will", "be", "rebooted", "." ]
0367bde9a52e69162832906acc61e8d65c5ec5d4
https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/env.py#L82-L123
train
206,122
instacart/lore
lore/env.py
launched
def launched(): """Test whether the current python environment is the correct lore env. :return: :any:`True` if the environment is launched :rtype: bool """ if not PREFIX: return False return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)
python
def launched(): """Test whether the current python environment is the correct lore env. :return: :any:`True` if the environment is launched :rtype: bool """ if not PREFIX: return False return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)
[ "def", "launched", "(", ")", ":", "if", "not", "PREFIX", ":", "return", "False", "return", "os", ".", "path", ".", "realpath", "(", "sys", ".", "prefix", ")", "==", "os", ".", "path", ".", "realpath", "(", "PREFIX", ")" ]
Test whether the current python environment is the correct lore env. :return: :any:`True` if the environment is launched :rtype: bool
[ "Test", "whether", "the", "current", "python", "environment", "is", "the", "correct", "lore", "env", "." ]
0367bde9a52e69162832906acc61e8d65c5ec5d4
https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/env.py#L135-L144
train
206,123
instacart/lore
lore/env.py
validate
def validate(): """Display error messages and exit if no lore environment can be found. """ if not os.path.exists(os.path.join(ROOT, APP, '__init__.py')): message = ansi.error() + ' Python module not found.' if os.environ.get('LORE_APP') is None: message += ' $LORE_APP is not set. Should it be different than "%s"?' % APP else: message += ' $LORE_APP is set to "%s". Should it be different?' % APP sys.exit(message) if exists(): return if len(sys.argv) > 1: command = sys.argv[1] else: command = 'lore' sys.exit( ansi.error() + ' %s is only available in lore ' 'app directories (missing %s)' % ( ansi.bold(command), ansi.underline(VERSION_PATH) ) )
python
def validate(): """Display error messages and exit if no lore environment can be found. """ if not os.path.exists(os.path.join(ROOT, APP, '__init__.py')): message = ansi.error() + ' Python module not found.' if os.environ.get('LORE_APP') is None: message += ' $LORE_APP is not set. Should it be different than "%s"?' % APP else: message += ' $LORE_APP is set to "%s". Should it be different?' % APP sys.exit(message) if exists(): return if len(sys.argv) > 1: command = sys.argv[1] else: command = 'lore' sys.exit( ansi.error() + ' %s is only available in lore ' 'app directories (missing %s)' % ( ansi.bold(command), ansi.underline(VERSION_PATH) ) )
[ "def", "validate", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "ROOT", ",", "APP", ",", "'__init__.py'", ")", ")", ":", "message", "=", "ansi", ".", "error", "(", ")", "+", "' Python mod...
Display error messages and exit if no lore environment can be found.
[ "Display", "error", "messages", "and", "exit", "if", "no", "lore", "environment", "can", "be", "found", "." ]
0367bde9a52e69162832906acc61e8d65c5ec5d4
https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/env.py#L147-L171
train
206,124
instacart/lore
lore/env.py
launch
def launch(): """Ensure that python is running from the Lore virtualenv past this point. """ if launched(): check_version() os.chdir(ROOT) return if not os.path.exists(BIN_LORE): missing = ' %s virtualenv is missing.' % APP if '--launched' in sys.argv: sys.exit(ansi.error() + missing + ' Please check for errors during:\n $ lore install\n') else: print(ansi.warning() + missing) import lore.__main__ lore.__main__.install(None, None) reboot('--env-launched')
python
def launch(): """Ensure that python is running from the Lore virtualenv past this point. """ if launched(): check_version() os.chdir(ROOT) return if not os.path.exists(BIN_LORE): missing = ' %s virtualenv is missing.' % APP if '--launched' in sys.argv: sys.exit(ansi.error() + missing + ' Please check for errors during:\n $ lore install\n') else: print(ansi.warning() + missing) import lore.__main__ lore.__main__.install(None, None) reboot('--env-launched')
[ "def", "launch", "(", ")", ":", "if", "launched", "(", ")", ":", "check_version", "(", ")", "os", ".", "chdir", "(", "ROOT", ")", "return", "if", "not", "os", ".", "path", ".", "exists", "(", "BIN_LORE", ")", ":", "missing", "=", "' %s virtualenv is ...
Ensure that python is running from the Lore virtualenv past this point.
[ "Ensure", "that", "python", "is", "running", "from", "the", "Lore", "virtualenv", "past", "this", "point", "." ]
0367bde9a52e69162832906acc61e8d65c5ec5d4
https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/env.py#L174-L191
train
206,125
instacart/lore
lore/env.py
reboot
def reboot(*args): """Reboot python in the Lore virtualenv """ args = list(sys.argv) + list(args) if args[0] == 'python' or not args[0]: args[0] = BIN_PYTHON elif os.path.basename(sys.argv[0]) in ['lore', 'lore.exe']: args[0] = BIN_LORE try: os.execv(args[0], args) except Exception as e: if args[0] == BIN_LORE and args[1] == 'console' and JUPYTER_KERNEL_PATH: print(ansi.error() + ' Your jupyter kernel may be corrupt. Please remove it so lore can reinstall:\n $ rm ' + JUPYTER_KERNEL_PATH) raise e
python
def reboot(*args): """Reboot python in the Lore virtualenv """ args = list(sys.argv) + list(args) if args[0] == 'python' or not args[0]: args[0] = BIN_PYTHON elif os.path.basename(sys.argv[0]) in ['lore', 'lore.exe']: args[0] = BIN_LORE try: os.execv(args[0], args) except Exception as e: if args[0] == BIN_LORE and args[1] == 'console' and JUPYTER_KERNEL_PATH: print(ansi.error() + ' Your jupyter kernel may be corrupt. Please remove it so lore can reinstall:\n $ rm ' + JUPYTER_KERNEL_PATH) raise e
[ "def", "reboot", "(", "*", "args", ")", ":", "args", "=", "list", "(", "sys", ".", "argv", ")", "+", "list", "(", "args", ")", "if", "args", "[", "0", "]", "==", "'python'", "or", "not", "args", "[", "0", "]", ":", "args", "[", "0", "]", "=...
Reboot python in the Lore virtualenv
[ "Reboot", "python", "in", "the", "Lore", "virtualenv" ]
0367bde9a52e69162832906acc61e8d65c5ec5d4
https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/env.py#L194-L207
train
206,126
instacart/lore
lore/env.py
check_version
def check_version(): """Sanity check version information for corrupt virtualenv symlinks """ if sys.version_info[0:3] == PYTHON_VERSION_INFO[0:3]: return sys.exit( ansi.error() + ' your virtual env points to the wrong python version. ' 'This is likely because you used a python installer that clobbered ' 'the system installation, which breaks virtualenv creation. ' 'To fix, check this symlink, and delete the installation of python ' 'that it is brokenly pointing to, then delete the virtual env itself ' 'and rerun lore install: ' + os.linesep + os.linesep + BIN_PYTHON + os.linesep )
python
def check_version(): """Sanity check version information for corrupt virtualenv symlinks """ if sys.version_info[0:3] == PYTHON_VERSION_INFO[0:3]: return sys.exit( ansi.error() + ' your virtual env points to the wrong python version. ' 'This is likely because you used a python installer that clobbered ' 'the system installation, which breaks virtualenv creation. ' 'To fix, check this symlink, and delete the installation of python ' 'that it is brokenly pointing to, then delete the virtual env itself ' 'and rerun lore install: ' + os.linesep + os.linesep + BIN_PYTHON + os.linesep )
[ "def", "check_version", "(", ")", ":", "if", "sys", ".", "version_info", "[", "0", ":", "3", "]", "==", "PYTHON_VERSION_INFO", "[", "0", ":", "3", "]", ":", "return", "sys", ".", "exit", "(", "ansi", ".", "error", "(", ")", "+", "' your virtual env p...
Sanity check version information for corrupt virtualenv symlinks
[ "Sanity", "check", "version", "information", "for", "corrupt", "virtualenv", "symlinks" ]
0367bde9a52e69162832906acc61e8d65c5ec5d4
https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/env.py#L210-L224
train
206,127
instacart/lore
lore/env.py
check_requirements
def check_requirements(): """Make sure all listed packages from requirements.txt have been installed into the virtualenv at boot. """ if not os.path.exists(REQUIREMENTS): sys.exit( ansi.error() + ' %s is missing. Please check it in.' % ansi.underline(REQUIREMENTS) ) with open(REQUIREMENTS, 'r', encoding='utf-8') as f: dependencies = f.readlines() vcs = [d for d in dependencies if re.match(r'^(-e )?(git|svn|hg|bzr).*', d)] dependencies = list(set(dependencies) - set(vcs)) missing = [] try: pkg_resources.require(dependencies) except ( pkg_resources.ContextualVersionConflict, pkg_resources.DistributionNotFound, pkg_resources.VersionConflict ) as error: missing.append(str(error)) except pkg_resources.RequirementParseError: pass if missing: missing = ' missing requirement:\n ' + os.linesep.join(missing) if '--env-checked' in sys.argv: sys.exit(ansi.error() + missing + '\nRequirement installation failure, please check for errors in:\n $ lore install\n') else: print(ansi.warning() + missing) import lore.__main__ lore.__main__.install_requirements(None) reboot('--env-checked')
python
def check_requirements(): """Make sure all listed packages from requirements.txt have been installed into the virtualenv at boot. """ if not os.path.exists(REQUIREMENTS): sys.exit( ansi.error() + ' %s is missing. Please check it in.' % ansi.underline(REQUIREMENTS) ) with open(REQUIREMENTS, 'r', encoding='utf-8') as f: dependencies = f.readlines() vcs = [d for d in dependencies if re.match(r'^(-e )?(git|svn|hg|bzr).*', d)] dependencies = list(set(dependencies) - set(vcs)) missing = [] try: pkg_resources.require(dependencies) except ( pkg_resources.ContextualVersionConflict, pkg_resources.DistributionNotFound, pkg_resources.VersionConflict ) as error: missing.append(str(error)) except pkg_resources.RequirementParseError: pass if missing: missing = ' missing requirement:\n ' + os.linesep.join(missing) if '--env-checked' in sys.argv: sys.exit(ansi.error() + missing + '\nRequirement installation failure, please check for errors in:\n $ lore install\n') else: print(ansi.warning() + missing) import lore.__main__ lore.__main__.install_requirements(None) reboot('--env-checked')
[ "def", "check_requirements", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "REQUIREMENTS", ")", ":", "sys", ".", "exit", "(", "ansi", ".", "error", "(", ")", "+", "' %s is missing. Please check it in.'", "%", "ansi", ".", "underline", ...
Make sure all listed packages from requirements.txt have been installed into the virtualenv at boot.
[ "Make", "sure", "all", "listed", "packages", "from", "requirements", ".", "txt", "have", "been", "installed", "into", "the", "virtualenv", "at", "boot", "." ]
0367bde9a52e69162832906acc61e8d65c5ec5d4
https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/env.py#L227-L262
train
206,128
instacart/lore
lore/env.py
get_config
def get_config(path): """Load a config from disk :param path: target config :type path: unicode :return: :rtype: configparser.Config """ if configparser is None: return None # Check for env specific configs first if os.path.exists(os.path.join(ROOT, 'config', NAME, path)): path = os.path.join(ROOT, 'config', NAME, path) else: path = os.path.join(ROOT, 'config', path) if not os.path.isfile(path): return None conf = open(path, 'rt').read() conf = os.path.expandvars(conf) config = configparser.SafeConfigParser() if sys.version_info[0] == 2: from io import StringIO config.readfp(StringIO(unicode(conf))) else: config.read_string(conf) return config
python
def get_config(path): """Load a config from disk :param path: target config :type path: unicode :return: :rtype: configparser.Config """ if configparser is None: return None # Check for env specific configs first if os.path.exists(os.path.join(ROOT, 'config', NAME, path)): path = os.path.join(ROOT, 'config', NAME, path) else: path = os.path.join(ROOT, 'config', path) if not os.path.isfile(path): return None conf = open(path, 'rt').read() conf = os.path.expandvars(conf) config = configparser.SafeConfigParser() if sys.version_info[0] == 2: from io import StringIO config.readfp(StringIO(unicode(conf))) else: config.read_string(conf) return config
[ "def", "get_config", "(", "path", ")", ":", "if", "configparser", "is", "None", ":", "return", "None", "# Check for env specific configs first", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "ROOT", ",", "'config'", ",",...
Load a config from disk :param path: target config :type path: unicode :return: :rtype: configparser.Config
[ "Load", "a", "config", "from", "disk" ]
0367bde9a52e69162832906acc61e8d65c5ec5d4
https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/env.py#L265-L294
train
206,129
instacart/lore
lore/env.py
read_version
def read_version(path): """Attempts to read a python version string from a runtime.txt file :param path: to source of the string :return: python version :rtype: unicode or None """ version = None if os.path.exists(path): version = open(path, 'r', encoding='utf-8').read().strip() if version: return re.sub(r'^python-', '', version) return version
python
def read_version(path): """Attempts to read a python version string from a runtime.txt file :param path: to source of the string :return: python version :rtype: unicode or None """ version = None if os.path.exists(path): version = open(path, 'r', encoding='utf-8').read().strip() if version: return re.sub(r'^python-', '', version) return version
[ "def", "read_version", "(", "path", ")", ":", "version", "=", "None", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "version", "=", "open", "(", "path", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", ".", "read", "(", ")", "."...
Attempts to read a python version string from a runtime.txt file :param path: to source of the string :return: python version :rtype: unicode or None
[ "Attempts", "to", "read", "a", "python", "version", "string", "from", "a", "runtime", ".", "txt", "file" ]
0367bde9a52e69162832906acc61e8d65c5ec5d4
https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/env.py#L297-L311
train
206,130
instacart/lore
lore/env.py
set_installed_packages
def set_installed_packages(): """Idempotently caches the list of packages installed in the virtualenv. Can be run safely before the virtualenv is created, and will be rerun afterwards. """ global INSTALLED_PACKAGES, REQUIRED_VERSION if INSTALLED_PACKAGES: return if os.path.exists(BIN_PYTHON): pip = subprocess.Popen( (BIN_PYTHON, '-m', 'pip', 'freeze'), stdout=subprocess.PIPE, stderr=subprocess.PIPE ) (stdout, stderr) = pip.communicate() pip.wait() INSTALLED_PACKAGES = [r.decode().split('==')[0].lower() for r in stdout.split()] REQUIRED_VERSION = next((package for package in INSTALLED_PACKAGES if re.match(r'^lore[!<>=]', package)), None) if REQUIRED_VERSION: REQUIRED_VERSION = re.split(r'[!<>=]', REQUIRED_VERSION)[-1]
python
def set_installed_packages(): """Idempotently caches the list of packages installed in the virtualenv. Can be run safely before the virtualenv is created, and will be rerun afterwards. """ global INSTALLED_PACKAGES, REQUIRED_VERSION if INSTALLED_PACKAGES: return if os.path.exists(BIN_PYTHON): pip = subprocess.Popen( (BIN_PYTHON, '-m', 'pip', 'freeze'), stdout=subprocess.PIPE, stderr=subprocess.PIPE ) (stdout, stderr) = pip.communicate() pip.wait() INSTALLED_PACKAGES = [r.decode().split('==')[0].lower() for r in stdout.split()] REQUIRED_VERSION = next((package for package in INSTALLED_PACKAGES if re.match(r'^lore[!<>=]', package)), None) if REQUIRED_VERSION: REQUIRED_VERSION = re.split(r'[!<>=]', REQUIRED_VERSION)[-1]
[ "def", "set_installed_packages", "(", ")", ":", "global", "INSTALLED_PACKAGES", ",", "REQUIRED_VERSION", "if", "INSTALLED_PACKAGES", ":", "return", "if", "os", ".", "path", ".", "exists", "(", "BIN_PYTHON", ")", ":", "pip", "=", "subprocess", ".", "Popen", "("...
Idempotently caches the list of packages installed in the virtualenv. Can be run safely before the virtualenv is created, and will be rerun afterwards.
[ "Idempotently", "caches", "the", "list", "of", "packages", "installed", "in", "the", "virtualenv", ".", "Can", "be", "run", "safely", "before", "the", "virtualenv", "is", "created", "and", "will", "be", "rerun", "afterwards", "." ]
0367bde9a52e69162832906acc61e8d65c5ec5d4
https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/env.py#L355-L376
train
206,131
GoogleCloudPlatform/flask-talisman
flask_talisman/talisman.py
Talisman._force_https
def _force_https(self): """Redirect any non-https requests to https. Based largely on flask-sslify. """ if self.session_cookie_secure: if not self.app.debug: self.app.config['SESSION_COOKIE_SECURE'] = True criteria = [ self.app.debug, flask.request.is_secure, flask.request.headers.get('X-Forwarded-Proto', 'http') == 'https', ] local_options = self._get_local_options() if local_options['force_https'] and not any(criteria): if flask.request.url.startswith('http://'): url = flask.request.url.replace('http://', 'https://', 1) code = 302 if self.force_https_permanent: code = 301 r = flask.redirect(url, code=code) return r
python
def _force_https(self): """Redirect any non-https requests to https. Based largely on flask-sslify. """ if self.session_cookie_secure: if not self.app.debug: self.app.config['SESSION_COOKIE_SECURE'] = True criteria = [ self.app.debug, flask.request.is_secure, flask.request.headers.get('X-Forwarded-Proto', 'http') == 'https', ] local_options = self._get_local_options() if local_options['force_https'] and not any(criteria): if flask.request.url.startswith('http://'): url = flask.request.url.replace('http://', 'https://', 1) code = 302 if self.force_https_permanent: code = 301 r = flask.redirect(url, code=code) return r
[ "def", "_force_https", "(", "self", ")", ":", "if", "self", ".", "session_cookie_secure", ":", "if", "not", "self", ".", "app", ".", "debug", ":", "self", ".", "app", ".", "config", "[", "'SESSION_COOKIE_SECURE'", "]", "=", "True", "criteria", "=", "[", ...
Redirect any non-https requests to https. Based largely on flask-sslify.
[ "Redirect", "any", "non", "-", "https", "requests", "to", "https", "." ]
c45a9a5b2671b9667856e281d2726c8bfd0f0fd7
https://github.com/GoogleCloudPlatform/flask-talisman/blob/c45a9a5b2671b9667856e281d2726c8bfd0f0fd7/flask_talisman/talisman.py#L193-L218
train
206,132
GoogleCloudPlatform/flask-talisman
flask_talisman/talisman.py
Talisman._set_response_headers
def _set_response_headers(self, response): """Applies all configured headers to the given response.""" options = self._get_local_options() self._set_feature_headers(response.headers, options) self._set_frame_options_headers(response.headers, options) self._set_content_security_policy_headers(response.headers, options) self._set_hsts_headers(response.headers) self._set_referrer_policy_headers(response.headers) return response
python
def _set_response_headers(self, response): """Applies all configured headers to the given response.""" options = self._get_local_options() self._set_feature_headers(response.headers, options) self._set_frame_options_headers(response.headers, options) self._set_content_security_policy_headers(response.headers, options) self._set_hsts_headers(response.headers) self._set_referrer_policy_headers(response.headers) return response
[ "def", "_set_response_headers", "(", "self", ",", "response", ")", ":", "options", "=", "self", ".", "_get_local_options", "(", ")", "self", ".", "_set_feature_headers", "(", "response", ".", "headers", ",", "options", ")", "self", ".", "_set_frame_options_heade...
Applies all configured headers to the given response.
[ "Applies", "all", "configured", "headers", "to", "the", "given", "response", "." ]
c45a9a5b2671b9667856e281d2726c8bfd0f0fd7
https://github.com/GoogleCloudPlatform/flask-talisman/blob/c45a9a5b2671b9667856e281d2726c8bfd0f0fd7/flask_talisman/talisman.py#L220-L228
train
206,133
daboth/pagan
pagan/hashgrinder.py
init_weapon_list
def init_weapon_list(): """Initialize the possible weapon combinations.""" twohand = [] for item in TWOHANDED_WEAPONS: twohand.append([item]) onehand = [] for item in ONEHANDED_WEAPONS: onehand.append([item]) shield = SHIELDS dualwield_variations = [] weapon_shield_variations = [] for item in ONEHANDED_WEAPONS: for i in ONEHANDED_WEAPONS: dualwield_variations.append([item, i]) for j in shield: weapon_shield_variations.append([j, item]) return twohand + onehand + dualwield_variations + weapon_shield_variations
python
def init_weapon_list(): """Initialize the possible weapon combinations.""" twohand = [] for item in TWOHANDED_WEAPONS: twohand.append([item]) onehand = [] for item in ONEHANDED_WEAPONS: onehand.append([item]) shield = SHIELDS dualwield_variations = [] weapon_shield_variations = [] for item in ONEHANDED_WEAPONS: for i in ONEHANDED_WEAPONS: dualwield_variations.append([item, i]) for j in shield: weapon_shield_variations.append([j, item]) return twohand + onehand + dualwield_variations + weapon_shield_variations
[ "def", "init_weapon_list", "(", ")", ":", "twohand", "=", "[", "]", "for", "item", "in", "TWOHANDED_WEAPONS", ":", "twohand", ".", "append", "(", "[", "item", "]", ")", "onehand", "=", "[", "]", "for", "item", "in", "ONEHANDED_WEAPONS", ":", "onehand", ...
Initialize the possible weapon combinations.
[ "Initialize", "the", "possible", "weapon", "combinations", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/hashgrinder.py#L69-L91
train
206,134
daboth/pagan
pagan/hashgrinder.py
split_sequence
def split_sequence(seq, n): """Generates tokens of length n from a sequence. The last token may be of smaller length.""" tokens = [] while seq: tokens.append(seq[:n]) seq = seq[n:] return tokens
python
def split_sequence(seq, n): """Generates tokens of length n from a sequence. The last token may be of smaller length.""" tokens = [] while seq: tokens.append(seq[:n]) seq = seq[n:] return tokens
[ "def", "split_sequence", "(", "seq", ",", "n", ")", ":", "tokens", "=", "[", "]", "while", "seq", ":", "tokens", ".", "append", "(", "seq", "[", ":", "n", "]", ")", "seq", "=", "seq", "[", "n", ":", "]", "return", "tokens" ]
Generates tokens of length n from a sequence. The last token may be of smaller length.
[ "Generates", "tokens", "of", "length", "n", "from", "a", "sequence", ".", "The", "last", "token", "may", "be", "of", "smaller", "length", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/hashgrinder.py#L124-L131
train
206,135
daboth/pagan
pagan/hashgrinder.py
grind_hash_for_weapon
def grind_hash_for_weapon(hashcode): """ Grinds the given hashcode for a weapon to draw on the pixelmap. Utilizes the second six characters from the hashcode.""" weaponlist = init_weapon_list() # The second six characters of the hash # control the weapon decision. weapon_control = hashcode[ASPECT_CONTROL_LEN:(ASPECT_CONTROL_LEN * 2)] # Decimal value of the hash chunk to map. hash_dec_value = int(weapon_control, HEX_BASE) decision = map_decision(MAX_DECISION_VALUE, len(weaponlist), hash_dec_value) return choose_weapon(decision, weaponlist)
python
def grind_hash_for_weapon(hashcode): """ Grinds the given hashcode for a weapon to draw on the pixelmap. Utilizes the second six characters from the hashcode.""" weaponlist = init_weapon_list() # The second six characters of the hash # control the weapon decision. weapon_control = hashcode[ASPECT_CONTROL_LEN:(ASPECT_CONTROL_LEN * 2)] # Decimal value of the hash chunk to map. hash_dec_value = int(weapon_control, HEX_BASE) decision = map_decision(MAX_DECISION_VALUE, len(weaponlist), hash_dec_value) return choose_weapon(decision, weaponlist)
[ "def", "grind_hash_for_weapon", "(", "hashcode", ")", ":", "weaponlist", "=", "init_weapon_list", "(", ")", "# The second six characters of the hash", "# control the weapon decision.", "weapon_control", "=", "hashcode", "[", "ASPECT_CONTROL_LEN", ":", "(", "ASPECT_CONTROL_LEN...
Grinds the given hashcode for a weapon to draw on the pixelmap. Utilizes the second six characters from the hashcode.
[ "Grinds", "the", "given", "hashcode", "for", "a", "weapon", "to", "draw", "on", "the", "pixelmap", ".", "Utilizes", "the", "second", "six", "characters", "from", "the", "hashcode", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/hashgrinder.py#L146-L160
train
206,136
daboth/pagan
pagan/hashgrinder.py
choose_weapon
def choose_weapon(decision, weapons): """Chooses a weapon from a given list based on the decision.""" choice = [] for i in range(len(weapons)): if (i < decision): choice = weapons[i] return choice
python
def choose_weapon(decision, weapons): """Chooses a weapon from a given list based on the decision.""" choice = [] for i in range(len(weapons)): if (i < decision): choice = weapons[i] return choice
[ "def", "choose_weapon", "(", "decision", ",", "weapons", ")", ":", "choice", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "weapons", ")", ")", ":", "if", "(", "i", "<", "decision", ")", ":", "choice", "=", "weapons", "[", "i", "]", ...
Chooses a weapon from a given list based on the decision.
[ "Chooses", "a", "weapon", "from", "a", "given", "list", "based", "on", "the", "decision", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/hashgrinder.py#L163-L170
train
206,137
daboth/pagan
pagan/hashgrinder.py
choose_aspect
def choose_aspect(decision): """Chooses a style from ASPECTSTYLES based on the decision.""" choice = [] for i in range(len(ASPECTSTYLES)): if (i < decision): choice = ASPECTSTYLES[i] return choice
python
def choose_aspect(decision): """Chooses a style from ASPECTSTYLES based on the decision.""" choice = [] for i in range(len(ASPECTSTYLES)): if (i < decision): choice = ASPECTSTYLES[i] return choice
[ "def", "choose_aspect", "(", "decision", ")", ":", "choice", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "ASPECTSTYLES", ")", ")", ":", "if", "(", "i", "<", "decision", ")", ":", "choice", "=", "ASPECTSTYLES", "[", "i", "]", "return"...
Chooses a style from ASPECTSTYLES based on the decision.
[ "Chooses", "a", "style", "from", "ASPECTSTYLES", "based", "on", "the", "decision", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/hashgrinder.py#L173-L180
train
206,138
daboth/pagan
pagan/hashgrinder.py
hex2rgb
def hex2rgb(hexvalue): """Converts a given hex color to its respective rgb color.""" # Make sure a possible '#' char is eliminated # before processing the color. if ('#' in hexvalue): hexcolor = hexvalue.replace('#', '') else: hexcolor = hexvalue # Hex colors have a fixed length of 6 characters excluding the '#' # TODO: Include custom exception here, even if it should never happen. if (len(hexcolor) != 6): print ("Unexpected length of hex color value.\nSix characters excluding \'#\' expected.") return 0 # Convert each two characters of # the hex to an RGB color value. r = int(hexcolor[0:2], HEX_BASE) g = int(hexcolor[2:4], HEX_BASE) b = int(hexcolor[4:6], HEX_BASE) return r, g, b
python
def hex2rgb(hexvalue): """Converts a given hex color to its respective rgb color.""" # Make sure a possible '#' char is eliminated # before processing the color. if ('#' in hexvalue): hexcolor = hexvalue.replace('#', '') else: hexcolor = hexvalue # Hex colors have a fixed length of 6 characters excluding the '#' # TODO: Include custom exception here, even if it should never happen. if (len(hexcolor) != 6): print ("Unexpected length of hex color value.\nSix characters excluding \'#\' expected.") return 0 # Convert each two characters of # the hex to an RGB color value. r = int(hexcolor[0:2], HEX_BASE) g = int(hexcolor[2:4], HEX_BASE) b = int(hexcolor[4:6], HEX_BASE) return r, g, b
[ "def", "hex2rgb", "(", "hexvalue", ")", ":", "# Make sure a possible '#' char is eliminated", "# before processing the color.", "if", "(", "'#'", "in", "hexvalue", ")", ":", "hexcolor", "=", "hexvalue", ".", "replace", "(", "'#'", ",", "''", ")", "else", ":", "h...
Converts a given hex color to its respective rgb color.
[ "Converts", "a", "given", "hex", "color", "to", "its", "respective", "rgb", "color", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/hashgrinder.py#L188-L211
train
206,139
daboth/pagan
tools/webserver/webserver.py
index
def index(): """main functionality of webserver""" default = ["pagan", "python", "avatar", "github"] slogan = request.forms.get("slogan") if not slogan: if request.get_cookie("hist1"): slogan = request.get_cookie("hist1") else: slogan = "pagan" if not request.get_cookie("hist1"): hist1, hist2, hist3, hist4 = default[:] else: hist1 = request.get_cookie("hist1") hist2 = request.get_cookie("hist2") hist3 = request.get_cookie("hist3") hist4 = request.get_cookie("hist4") if slogan in (hist1, hist2, hist3, hist4): history = [hist1, hist2, hist3, hist4] history.remove(slogan) hist1, hist2, hist3 = history[0], history[1], history[2] response.set_cookie("hist1", slogan, max_age=60*60*24*30, httponly=True) response.set_cookie("hist2", hist1, max_age=60*60*24*30, httponly=True) response.set_cookie("hist3", hist2, max_age=60*60*24*30, httponly=True) response.set_cookie("hist4", hist3, max_age=60*60*24*30, httponly=True) # slogan, hist1, hist2, hist3 = escape(slogan), escape(hist1),\ # escape(hist2), escape(hist3) md5 = hashlib.md5() md5.update(slogan) slogan_hash = md5.hexdigest() md5.update(hist1) hist1_hash = md5.hexdigest() md5.update(hist2) hist2_hash = md5.hexdigest() md5.update(hist3) hist3_hash = md5.hexdigest() return template(TEMPLATEINDEX, slogan=slogan, hist1=hist1, hist2=hist2, hist3=hist3, sloganHash=slogan_hash, hist1Hash=hist1_hash, hist2Hash=hist2_hash, hist3Hash=hist3_hash)
python
def index(): """main functionality of webserver""" default = ["pagan", "python", "avatar", "github"] slogan = request.forms.get("slogan") if not slogan: if request.get_cookie("hist1"): slogan = request.get_cookie("hist1") else: slogan = "pagan" if not request.get_cookie("hist1"): hist1, hist2, hist3, hist4 = default[:] else: hist1 = request.get_cookie("hist1") hist2 = request.get_cookie("hist2") hist3 = request.get_cookie("hist3") hist4 = request.get_cookie("hist4") if slogan in (hist1, hist2, hist3, hist4): history = [hist1, hist2, hist3, hist4] history.remove(slogan) hist1, hist2, hist3 = history[0], history[1], history[2] response.set_cookie("hist1", slogan, max_age=60*60*24*30, httponly=True) response.set_cookie("hist2", hist1, max_age=60*60*24*30, httponly=True) response.set_cookie("hist3", hist2, max_age=60*60*24*30, httponly=True) response.set_cookie("hist4", hist3, max_age=60*60*24*30, httponly=True) # slogan, hist1, hist2, hist3 = escape(slogan), escape(hist1),\ # escape(hist2), escape(hist3) md5 = hashlib.md5() md5.update(slogan) slogan_hash = md5.hexdigest() md5.update(hist1) hist1_hash = md5.hexdigest() md5.update(hist2) hist2_hash = md5.hexdigest() md5.update(hist3) hist3_hash = md5.hexdigest() return template(TEMPLATEINDEX, slogan=slogan, hist1=hist1, hist2=hist2, hist3=hist3, sloganHash=slogan_hash, hist1Hash=hist1_hash, hist2Hash=hist2_hash, hist3Hash=hist3_hash)
[ "def", "index", "(", ")", ":", "default", "=", "[", "\"pagan\"", ",", "\"python\"", ",", "\"avatar\"", ",", "\"github\"", "]", "slogan", "=", "request", ".", "forms", ".", "get", "(", "\"slogan\"", ")", "if", "not", "slogan", ":", "if", "request", ".",...
main functionality of webserver
[ "main", "functionality", "of", "webserver" ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/tools/webserver/webserver.py#L63-L105
train
206,140
daboth/pagan
pagan/pagan.py
Avatar.__create_image
def __create_image(self, inpt, hashfun): """Creates the avatar based on the input and the chosen hash function.""" if hashfun not in generator.HASHES.keys(): print ("Unknown or unsupported hash function. Using default: %s" % self.DEFAULT_HASHFUN) algo = self.DEFAULT_HASHFUN else: algo = hashfun return generator.generate(inpt, algo)
python
def __create_image(self, inpt, hashfun): """Creates the avatar based on the input and the chosen hash function.""" if hashfun not in generator.HASHES.keys(): print ("Unknown or unsupported hash function. Using default: %s" % self.DEFAULT_HASHFUN) algo = self.DEFAULT_HASHFUN else: algo = hashfun return generator.generate(inpt, algo)
[ "def", "__create_image", "(", "self", ",", "inpt", ",", "hashfun", ")", ":", "if", "hashfun", "not", "in", "generator", ".", "HASHES", ".", "keys", "(", ")", ":", "print", "(", "\"Unknown or unsupported hash function. Using default: %s\"", "%", "self", ".", "D...
Creates the avatar based on the input and the chosen hash function.
[ "Creates", "the", "avatar", "based", "on", "the", "input", "and", "the", "chosen", "hash", "function", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/pagan.py#L20-L29
train
206,141
daboth/pagan
pagan/pagan.py
Avatar.change
def change(self, inpt, hashfun=DEFAULT_HASHFUN): """Change the avatar by providing a new input. Uses the standard hash function if no one is given.""" self.img = self.__create_image(inpt, hashfun)
python
def change(self, inpt, hashfun=DEFAULT_HASHFUN): """Change the avatar by providing a new input. Uses the standard hash function if no one is given.""" self.img = self.__create_image(inpt, hashfun)
[ "def", "change", "(", "self", ",", "inpt", ",", "hashfun", "=", "DEFAULT_HASHFUN", ")", ":", "self", ".", "img", "=", "self", ".", "__create_image", "(", "inpt", ",", "hashfun", ")" ]
Change the avatar by providing a new input. Uses the standard hash function if no one is given.
[ "Change", "the", "avatar", "by", "providing", "a", "new", "input", ".", "Uses", "the", "standard", "hash", "function", "if", "no", "one", "is", "given", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/pagan.py#L36-L39
train
206,142
daboth/pagan
pagan/generator.py
create_shield_deco_layer
def create_shield_deco_layer(weapons, ip): '''Reads the SHIELD_DECO.pgn file and creates the shield decal layer.''' layer = [] if weapons[0] in hashgrinder.SHIELDS: layer = pgnreader.parse_pagan_file(FILE_SHIELD_DECO, ip, invert=False, sym=False) return layer
python
def create_shield_deco_layer(weapons, ip): '''Reads the SHIELD_DECO.pgn file and creates the shield decal layer.''' layer = [] if weapons[0] in hashgrinder.SHIELDS: layer = pgnreader.parse_pagan_file(FILE_SHIELD_DECO, ip, invert=False, sym=False) return layer
[ "def", "create_shield_deco_layer", "(", "weapons", ",", "ip", ")", ":", "layer", "=", "[", "]", "if", "weapons", "[", "0", "]", "in", "hashgrinder", ".", "SHIELDS", ":", "layer", "=", "pgnreader", ".", "parse_pagan_file", "(", "FILE_SHIELD_DECO", ",", "ip"...
Reads the SHIELD_DECO.pgn file and creates the shield decal layer.
[ "Reads", "the", "SHIELD_DECO", ".", "pgn", "file", "and", "creates", "the", "shield", "decal", "layer", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/generator.py#L116-L122
train
206,143
daboth/pagan
pagan/generator.py
create_hair_layer
def create_hair_layer(aspect, ip): '''Reads the HAIR.pgn file and creates the hair layer.''' layer = [] if 'HAIR' in aspect: layer = pgnreader.parse_pagan_file(FILE_HAIR, ip, invert=False, sym=True) return layer
python
def create_hair_layer(aspect, ip): '''Reads the HAIR.pgn file and creates the hair layer.''' layer = [] if 'HAIR' in aspect: layer = pgnreader.parse_pagan_file(FILE_HAIR, ip, invert=False, sym=True) return layer
[ "def", "create_hair_layer", "(", "aspect", ",", "ip", ")", ":", "layer", "=", "[", "]", "if", "'HAIR'", "in", "aspect", ":", "layer", "=", "pgnreader", ".", "parse_pagan_file", "(", "FILE_HAIR", ",", "ip", ",", "invert", "=", "False", ",", "sym", "=", ...
Reads the HAIR.pgn file and creates the hair layer.
[ "Reads", "the", "HAIR", ".", "pgn", "file", "and", "creates", "the", "hair", "layer", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/generator.py#L125-L131
train
206,144
daboth/pagan
pagan/generator.py
create_torso_layer
def create_torso_layer(aspect, ip): '''Reads the TORSO.pgn file and creates the torso layer.''' layer = [] if 'TOP' in aspect: layer = pgnreader.parse_pagan_file(FILE_TORSO, ip, invert=False, sym=True) return layer
python
def create_torso_layer(aspect, ip): '''Reads the TORSO.pgn file and creates the torso layer.''' layer = [] if 'TOP' in aspect: layer = pgnreader.parse_pagan_file(FILE_TORSO, ip, invert=False, sym=True) return layer
[ "def", "create_torso_layer", "(", "aspect", ",", "ip", ")", ":", "layer", "=", "[", "]", "if", "'TOP'", "in", "aspect", ":", "layer", "=", "pgnreader", ".", "parse_pagan_file", "(", "FILE_TORSO", ",", "ip", ",", "invert", "=", "False", ",", "sym", "=",...
Reads the TORSO.pgn file and creates the torso layer.
[ "Reads", "the", "TORSO", ".", "pgn", "file", "and", "creates", "the", "torso", "layer", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/generator.py#L134-L140
train
206,145
daboth/pagan
pagan/generator.py
create_subfield_layer
def create_subfield_layer(aspect, ip): '''Reads the SUBFIELD.pgn file and creates the subfield layer.''' layer = [] if 'PANTS' in aspect: layer = pgnreader.parse_pagan_file(FILE_SUBFIELD, ip, invert=False, sym=True) else: layer = pgnreader.parse_pagan_file(FILE_MIN_SUBFIELD, ip, invert=False, sym=True) return layer
python
def create_subfield_layer(aspect, ip): '''Reads the SUBFIELD.pgn file and creates the subfield layer.''' layer = [] if 'PANTS' in aspect: layer = pgnreader.parse_pagan_file(FILE_SUBFIELD, ip, invert=False, sym=True) else: layer = pgnreader.parse_pagan_file(FILE_MIN_SUBFIELD, ip, invert=False, sym=True) return layer
[ "def", "create_subfield_layer", "(", "aspect", ",", "ip", ")", ":", "layer", "=", "[", "]", "if", "'PANTS'", "in", "aspect", ":", "layer", "=", "pgnreader", ".", "parse_pagan_file", "(", "FILE_SUBFIELD", ",", "ip", ",", "invert", "=", "False", ",", "sym"...
Reads the SUBFIELD.pgn file and creates the subfield layer.
[ "Reads", "the", "SUBFIELD", ".", "pgn", "file", "and", "creates", "the", "subfield", "layer", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/generator.py#L143-L152
train
206,146
daboth/pagan
pagan/generator.py
create_boots_layer
def create_boots_layer(aspect, ip): '''Reads the BOOTS.pgn file and creates the boots layer.''' layer = [] if 'BOOTS' in aspect: layer = pgnreader.parse_pagan_file(FILE_BOOTS, ip, invert=False, sym=True) return layer
python
def create_boots_layer(aspect, ip): '''Reads the BOOTS.pgn file and creates the boots layer.''' layer = [] if 'BOOTS' in aspect: layer = pgnreader.parse_pagan_file(FILE_BOOTS, ip, invert=False, sym=True) return layer
[ "def", "create_boots_layer", "(", "aspect", ",", "ip", ")", ":", "layer", "=", "[", "]", "if", "'BOOTS'", "in", "aspect", ":", "layer", "=", "pgnreader", ".", "parse_pagan_file", "(", "FILE_BOOTS", ",", "ip", ",", "invert", "=", "False", ",", "sym", "=...
Reads the BOOTS.pgn file and creates the boots layer.
[ "Reads", "the", "BOOTS", ".", "pgn", "file", "and", "creates", "the", "boots", "layer", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/generator.py#L155-L161
train
206,147
daboth/pagan
pagan/generator.py
create_shield_layer
def create_shield_layer(shield, hashcode): """Creates the layer for shields.""" return pgnreader.parse_pagan_file(('%s%spgn%s' % (PACKAGE_DIR, os.sep, os.sep)) + shield + '.pgn', hashcode, sym=False, invert=False)
python
def create_shield_layer(shield, hashcode): """Creates the layer for shields.""" return pgnreader.parse_pagan_file(('%s%spgn%s' % (PACKAGE_DIR, os.sep, os.sep)) + shield + '.pgn', hashcode, sym=False, invert=False)
[ "def", "create_shield_layer", "(", "shield", ",", "hashcode", ")", ":", "return", "pgnreader", ".", "parse_pagan_file", "(", "(", "'%s%spgn%s'", "%", "(", "PACKAGE_DIR", ",", "os", ".", "sep", ",", "os", ".", "sep", ")", ")", "+", "shield", "+", "'.pgn'"...
Creates the layer for shields.
[ "Creates", "the", "layer", "for", "shields", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/generator.py#L164-L166
train
206,148
daboth/pagan
pagan/generator.py
create_weapon_layer
def create_weapon_layer(weapon, hashcode, isSecond=False): """Creates the layer for weapons.""" return pgnreader.parse_pagan_file(('%s%spgn%s' % (PACKAGE_DIR, os.sep, os.sep)) + weapon + '.pgn', hashcode, sym=False, invert=isSecond)
python
def create_weapon_layer(weapon, hashcode, isSecond=False): """Creates the layer for weapons.""" return pgnreader.parse_pagan_file(('%s%spgn%s' % (PACKAGE_DIR, os.sep, os.sep)) + weapon + '.pgn', hashcode, sym=False, invert=isSecond)
[ "def", "create_weapon_layer", "(", "weapon", ",", "hashcode", ",", "isSecond", "=", "False", ")", ":", "return", "pgnreader", ".", "parse_pagan_file", "(", "(", "'%s%spgn%s'", "%", "(", "PACKAGE_DIR", ",", "os", ".", "sep", ",", "os", ".", "sep", ")", ")...
Creates the layer for weapons.
[ "Creates", "the", "layer", "for", "weapons", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/generator.py#L169-L171
train
206,149
daboth/pagan
pagan/generator.py
scale_pixels
def scale_pixels(color, layer): """Scales the pixel to the virtual pixelmap.""" pixelmap = [] # Scaling the pixel offsets. for pix_x in range(MAX_X + 1): for pix_y in range(MAX_Y + 1): # Horizontal pixels y1 = pix_y * dotsize[0] x1 = pix_x * dotsize[1] # Vertical pixels y2 = pix_y * dotsize[0] + (dotsize[0] - 1) x2 = pix_x * dotsize[1] + (dotsize[1] - 1) if (y1 <= MAX_Y) and (y2 <= MAX_Y): if (x1 <= MAX_X) and (x2 <= MAX_X): if (pix_x, pix_y) in layer: pixelmap.append([(y1, x1), (y2, x2), color]) return pixelmap
python
def scale_pixels(color, layer): """Scales the pixel to the virtual pixelmap.""" pixelmap = [] # Scaling the pixel offsets. for pix_x in range(MAX_X + 1): for pix_y in range(MAX_Y + 1): # Horizontal pixels y1 = pix_y * dotsize[0] x1 = pix_x * dotsize[1] # Vertical pixels y2 = pix_y * dotsize[0] + (dotsize[0] - 1) x2 = pix_x * dotsize[1] + (dotsize[1] - 1) if (y1 <= MAX_Y) and (y2 <= MAX_Y): if (x1 <= MAX_X) and (x2 <= MAX_X): if (pix_x, pix_y) in layer: pixelmap.append([(y1, x1), (y2, x2), color]) return pixelmap
[ "def", "scale_pixels", "(", "color", ",", "layer", ")", ":", "pixelmap", "=", "[", "]", "# Scaling the pixel offsets.", "for", "pix_x", "in", "range", "(", "MAX_X", "+", "1", ")", ":", "for", "pix_y", "in", "range", "(", "MAX_Y", "+", "1", ")", ":", ...
Scales the pixel to the virtual pixelmap.
[ "Scales", "the", "pixel", "to", "the", "virtual", "pixelmap", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/generator.py#L174-L194
train
206,150
daboth/pagan
pagan/generator.py
draw_image
def draw_image(pixelmap, img): '''Draws the image based on the given pixelmap.''' for item in pixelmap: color = item[2] # Access the rectangle edges. pixelbox = (item[0][0], item[0][1], item[1][0], item[1][1]) draw = ImageDraw.Draw(img) draw.rectangle(pixelbox, fill=color)
python
def draw_image(pixelmap, img): '''Draws the image based on the given pixelmap.''' for item in pixelmap: color = item[2] # Access the rectangle edges. pixelbox = (item[0][0], item[0][1], item[1][0], item[1][1]) draw = ImageDraw.Draw(img) draw.rectangle(pixelbox, fill=color)
[ "def", "draw_image", "(", "pixelmap", ",", "img", ")", ":", "for", "item", "in", "pixelmap", ":", "color", "=", "item", "[", "2", "]", "# Access the rectangle edges.", "pixelbox", "=", "(", "item", "[", "0", "]", "[", "0", "]", ",", "item", "[", "0",...
Draws the image based on the given pixelmap.
[ "Draws", "the", "image", "based", "on", "the", "given", "pixelmap", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/generator.py#L197-L205
train
206,151
daboth/pagan
pagan/generator.py
setup_pixelmap
def setup_pixelmap(hashcode): """Creates and combines all required layers to build a pixelmap for creating the virtual pixels.""" # Color distribution. # colors = hashgrinder.grindIpForColors(ip) colors = hashgrinder.grind_hash_for_colors(hashcode) color_body = colors[0] color_subfield = colors[1] color_weapon_a = colors[2] color_weapon_b = colors[3] color_shield_deco = colors[4] color_boots = colors[5] color_hair = colors[6] color_top = colors[7] # Grinds for the aspect. aspect = hashgrinder.grind_hash_for_aspect(hashcode) #Determine weapons of the avatar. weapons = hashgrinder.grind_hash_for_weapon(hashcode) if DEBUG: print ("Current aspect: %r" % aspect) print ("Current weapons: %r" % weapons) # There is just one body template. The optional pixels need to be mirrored so # the body layout will be symmetric to avoid uncanny looks. layer_body = pgnreader.parse_pagan_file(FILE_BODY, hashcode, invert=False, sym=True) layer_hair = create_hair_layer(aspect, hashcode) layer_boots = create_boots_layer(aspect, hashcode) layer_torso = create_torso_layer(aspect, hashcode) has_shield = (weapons[0] in hashgrinder.SHIELDS) if has_shield: layer_weapon_a = create_shield_layer(weapons[0], hashcode) layer_weapon_b = create_weapon_layer(weapons[1], hashcode) else: layer_weapon_a = create_weapon_layer(weapons[0], hashcode) if (len(weapons) == 2): layer_weapon_b = create_weapon_layer(weapons[1], hashcode, True) layer_subfield = create_subfield_layer(aspect, hashcode) layer_deco = create_shield_deco_layer(weapons, hashcode) pixelmap = scale_pixels(color_body, layer_body) pixelmap += scale_pixels(color_top, layer_torso) pixelmap += scale_pixels(color_hair, layer_hair) pixelmap += scale_pixels(color_subfield, layer_subfield) pixelmap += scale_pixels(color_boots, layer_boots) pixelmap += scale_pixels(color_weapon_a, layer_weapon_a) if (len(weapons) == 2): pixelmap += scale_pixels(color_weapon_b, layer_weapon_b) pixelmap += scale_pixels(color_shield_deco, layer_deco) return pixelmap
python
def setup_pixelmap(hashcode): """Creates and combines all required layers to build a pixelmap for creating the virtual pixels.""" # Color distribution. # colors = hashgrinder.grindIpForColors(ip) colors = hashgrinder.grind_hash_for_colors(hashcode) color_body = colors[0] color_subfield = colors[1] color_weapon_a = colors[2] color_weapon_b = colors[3] color_shield_deco = colors[4] color_boots = colors[5] color_hair = colors[6] color_top = colors[7] # Grinds for the aspect. aspect = hashgrinder.grind_hash_for_aspect(hashcode) #Determine weapons of the avatar. weapons = hashgrinder.grind_hash_for_weapon(hashcode) if DEBUG: print ("Current aspect: %r" % aspect) print ("Current weapons: %r" % weapons) # There is just one body template. The optional pixels need to be mirrored so # the body layout will be symmetric to avoid uncanny looks. layer_body = pgnreader.parse_pagan_file(FILE_BODY, hashcode, invert=False, sym=True) layer_hair = create_hair_layer(aspect, hashcode) layer_boots = create_boots_layer(aspect, hashcode) layer_torso = create_torso_layer(aspect, hashcode) has_shield = (weapons[0] in hashgrinder.SHIELDS) if has_shield: layer_weapon_a = create_shield_layer(weapons[0], hashcode) layer_weapon_b = create_weapon_layer(weapons[1], hashcode) else: layer_weapon_a = create_weapon_layer(weapons[0], hashcode) if (len(weapons) == 2): layer_weapon_b = create_weapon_layer(weapons[1], hashcode, True) layer_subfield = create_subfield_layer(aspect, hashcode) layer_deco = create_shield_deco_layer(weapons, hashcode) pixelmap = scale_pixels(color_body, layer_body) pixelmap += scale_pixels(color_top, layer_torso) pixelmap += scale_pixels(color_hair, layer_hair) pixelmap += scale_pixels(color_subfield, layer_subfield) pixelmap += scale_pixels(color_boots, layer_boots) pixelmap += scale_pixels(color_weapon_a, layer_weapon_a) if (len(weapons) == 2): pixelmap += scale_pixels(color_weapon_b, layer_weapon_b) pixelmap += scale_pixels(color_shield_deco, layer_deco) return pixelmap
[ "def", "setup_pixelmap", "(", "hashcode", ")", ":", "# Color distribution.", "# colors = hashgrinder.grindIpForColors(ip)", "colors", "=", "hashgrinder", ".", "grind_hash_for_colors", "(", "hashcode", ")", "color_body", "=", "colors", "[", "0", "]", "color_subfield", "=...
Creates and combines all required layers to build a pixelmap for creating the virtual pixels.
[ "Creates", "and", "combines", "all", "required", "layers", "to", "build", "a", "pixelmap", "for", "creating", "the", "virtual", "pixels", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/generator.py#L208-L269
train
206,152
daboth/pagan
pagan/generator.py
generate
def generate(str, alg): """Generates an PIL image avatar based on the given input String. Acts as the main accessor to pagan.""" img = Image.new(IMAGE_MODE, IMAGE_SIZE, BACKGROUND_COLOR) hashcode = hash_input(str, alg) pixelmap = setup_pixelmap(hashcode) draw_image(pixelmap, img) return img
python
def generate(str, alg): """Generates an PIL image avatar based on the given input String. Acts as the main accessor to pagan.""" img = Image.new(IMAGE_MODE, IMAGE_SIZE, BACKGROUND_COLOR) hashcode = hash_input(str, alg) pixelmap = setup_pixelmap(hashcode) draw_image(pixelmap, img) return img
[ "def", "generate", "(", "str", ",", "alg", ")", ":", "img", "=", "Image", ".", "new", "(", "IMAGE_MODE", ",", "IMAGE_SIZE", ",", "BACKGROUND_COLOR", ")", "hashcode", "=", "hash_input", "(", "str", ",", "alg", ")", "pixelmap", "=", "setup_pixelmap", "(", ...
Generates an PIL image avatar based on the given input String. Acts as the main accessor to pagan.
[ "Generates", "an", "PIL", "image", "avatar", "based", "on", "the", "given", "input", "String", ".", "Acts", "as", "the", "main", "accessor", "to", "pagan", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/generator.py#L272-L279
train
206,153
daboth/pagan
pagan/generator.py
generate_by_hash
def generate_by_hash(hashcode): """Generates an PIL image avatar based on the given hash String. Acts as the main accessor to pagan.""" img = Image.new(IMAGE_MODE, IMAGE_SIZE, BACKGROUND_COLOR) if len(hashcode) < 32: print ("hashcode must have lenght >= 32, %s" % hashcode) raise FalseHashError allowed = "0123456789abcdef" hashcheck = [c in allowed for c in hashcode] if False in hashcheck: print ("hashcode has not allowed structure %s" % hashcode) raise FalseHashError pixelmap = setup_pixelmap(hashcode) draw_image(pixelmap, img) return img
python
def generate_by_hash(hashcode): """Generates an PIL image avatar based on the given hash String. Acts as the main accessor to pagan.""" img = Image.new(IMAGE_MODE, IMAGE_SIZE, BACKGROUND_COLOR) if len(hashcode) < 32: print ("hashcode must have lenght >= 32, %s" % hashcode) raise FalseHashError allowed = "0123456789abcdef" hashcheck = [c in allowed for c in hashcode] if False in hashcheck: print ("hashcode has not allowed structure %s" % hashcode) raise FalseHashError pixelmap = setup_pixelmap(hashcode) draw_image(pixelmap, img) return img
[ "def", "generate_by_hash", "(", "hashcode", ")", ":", "img", "=", "Image", ".", "new", "(", "IMAGE_MODE", ",", "IMAGE_SIZE", ",", "BACKGROUND_COLOR", ")", "if", "len", "(", "hashcode", ")", "<", "32", ":", "print", "(", "\"hashcode must have lenght >= 32, %s\"...
Generates an PIL image avatar based on the given hash String. Acts as the main accessor to pagan.
[ "Generates", "an", "PIL", "image", "avatar", "based", "on", "the", "given", "hash", "String", ".", "Acts", "as", "the", "main", "accessor", "to", "pagan", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/generator.py#L282-L298
train
206,154
daboth/pagan
pagan/pgnreader.py
enforce_vertical_symmetry
def enforce_vertical_symmetry(pixmap): '''Enforces vertical symmetry of the pixelmap. Returns a pixelmap with all pixels mirrored in the middle. The initial ones still remain.''' mirror = [] for item in pixmap: y = item[0] x = item[1] if x <= IMAGE_APEX: diff_x = diff(x, IMAGE_APEX) mirror.append((y, x + (2 * diff_x) - 1)) if x > IMAGE_APEX: diff_x = diff(x, IMAGE_APEX) mirror.append((y, x - (2 * diff_x) - 1)) return mirror + pixmap
python
def enforce_vertical_symmetry(pixmap): '''Enforces vertical symmetry of the pixelmap. Returns a pixelmap with all pixels mirrored in the middle. The initial ones still remain.''' mirror = [] for item in pixmap: y = item[0] x = item[1] if x <= IMAGE_APEX: diff_x = diff(x, IMAGE_APEX) mirror.append((y, x + (2 * diff_x) - 1)) if x > IMAGE_APEX: diff_x = diff(x, IMAGE_APEX) mirror.append((y, x - (2 * diff_x) - 1)) return mirror + pixmap
[ "def", "enforce_vertical_symmetry", "(", "pixmap", ")", ":", "mirror", "=", "[", "]", "for", "item", "in", "pixmap", ":", "y", "=", "item", "[", "0", "]", "x", "=", "item", "[", "1", "]", "if", "x", "<=", "IMAGE_APEX", ":", "diff_x", "=", "diff", ...
Enforces vertical symmetry of the pixelmap. Returns a pixelmap with all pixels mirrored in the middle. The initial ones still remain.
[ "Enforces", "vertical", "symmetry", "of", "the", "pixelmap", ".", "Returns", "a", "pixelmap", "with", "all", "pixels", "mirrored", "in", "the", "middle", ".", "The", "initial", "ones", "still", "remain", "." ]
1e6d31f78e312d242751e70566ca9a6278784915
https://github.com/daboth/pagan/blob/1e6d31f78e312d242751e70566ca9a6278784915/pagan/pgnreader.py#L79-L96
train
206,155
alephdata/fingerprints
fingerprints/replacers.py
replace_types
def replace_types(text): """Chomp down company types to a more convention form.""" if not hasattr(replace_types, '_replacer'): replace_types._replacer = build_replacer() return replace_types._replacer(text)
python
def replace_types(text): """Chomp down company types to a more convention form.""" if not hasattr(replace_types, '_replacer'): replace_types._replacer = build_replacer() return replace_types._replacer(text)
[ "def", "replace_types", "(", "text", ")", ":", "if", "not", "hasattr", "(", "replace_types", ",", "'_replacer'", ")", ":", "replace_types", ".", "_replacer", "=", "build_replacer", "(", ")", "return", "replace_types", ".", "_replacer", "(", "text", ")" ]
Chomp down company types to a more convention form.
[ "Chomp", "down", "company", "types", "to", "a", "more", "convention", "form", "." ]
7d909cd0e624d42cf1f8d2702479ef6a66adbcb7
https://github.com/alephdata/fingerprints/blob/7d909cd0e624d42cf1f8d2702479ef6a66adbcb7/fingerprints/replacers.py#L58-L62
train
206,156
alephdata/fingerprints
fingerprints/cleanup.py
clean_strict
def clean_strict(text, boundary=WS): """Super-hardcore string scrubbing.""" # transliterate to ascii text = ascii_text(text) # replace punctuation and symbols text = CHARACTERS_REMOVE_RE.sub('', text) text = category_replace(text) # pad out for company type replacements text = ''.join((boundary, collapse_spaces(text), boundary)) return text
python
def clean_strict(text, boundary=WS): """Super-hardcore string scrubbing.""" # transliterate to ascii text = ascii_text(text) # replace punctuation and symbols text = CHARACTERS_REMOVE_RE.sub('', text) text = category_replace(text) # pad out for company type replacements text = ''.join((boundary, collapse_spaces(text), boundary)) return text
[ "def", "clean_strict", "(", "text", ",", "boundary", "=", "WS", ")", ":", "# transliterate to ascii", "text", "=", "ascii_text", "(", "text", ")", "# replace punctuation and symbols", "text", "=", "CHARACTERS_REMOVE_RE", ".", "sub", "(", "''", ",", "text", ")", ...
Super-hardcore string scrubbing.
[ "Super", "-", "hardcore", "string", "scrubbing", "." ]
7d909cd0e624d42cf1f8d2702479ef6a66adbcb7
https://github.com/alephdata/fingerprints/blob/7d909cd0e624d42cf1f8d2702479ef6a66adbcb7/fingerprints/cleanup.py#L32-L41
train
206,157
bopen/elevation
elevation/util.py
selfcheck
def selfcheck(tools): """Audit the system for issues. :param tools: Tools description. Use elevation.TOOLS to test elevation. """ msg = [] for tool_name, check_cli in collections.OrderedDict(tools).items(): try: subprocess.check_output(check_cli, shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError: msg.append('%r not found or not usable.' % tool_name) return '\n'.join(msg) if msg else 'Your system is ready.'
python
def selfcheck(tools): """Audit the system for issues. :param tools: Tools description. Use elevation.TOOLS to test elevation. """ msg = [] for tool_name, check_cli in collections.OrderedDict(tools).items(): try: subprocess.check_output(check_cli, shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError: msg.append('%r not found or not usable.' % tool_name) return '\n'.join(msg) if msg else 'Your system is ready.'
[ "def", "selfcheck", "(", "tools", ")", ":", "msg", "=", "[", "]", "for", "tool_name", ",", "check_cli", "in", "collections", ".", "OrderedDict", "(", "tools", ")", ".", "items", "(", ")", ":", "try", ":", "subprocess", ".", "check_output", "(", "check_...
Audit the system for issues. :param tools: Tools description. Use elevation.TOOLS to test elevation.
[ "Audit", "the", "system", "for", "issues", "." ]
c982d7180f00aa1ea1465b3ac14ebcef74634be3
https://github.com/bopen/elevation/blob/c982d7180f00aa1ea1465b3ac14ebcef74634be3/elevation/util.py#L32-L43
train
206,158
bopen/elevation
elevation/datasource.py
seed
def seed(cache_dir=CACHE_DIR, product=DEFAULT_PRODUCT, bounds=None, max_download_tiles=9, **kwargs): """Seed the DEM to given bounds. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice. :param bounds: Output bounds in 'left bottom right top' order. :param max_download_tiles: Maximum number of tiles to process. :param kwargs: Pass additional kwargs to ensure_tiles. """ datasource_root, spec = ensure_setup(cache_dir, product) ensure_tiles_names = list(spec['tile_names'](*bounds)) # FIXME: emergency hack to enforce the no-bulk-download policy if len(ensure_tiles_names) > max_download_tiles: raise RuntimeError("Too many tiles: %d. Please consult the providers' websites " "for how to bulk download tiles." % len(ensure_tiles_names)) with util.lock_tiles(datasource_root, ensure_tiles_names): ensure_tiles(datasource_root, ensure_tiles_names, **kwargs) with util.lock_vrt(datasource_root, product): util.check_call_make(datasource_root, targets=['all']) return datasource_root
python
def seed(cache_dir=CACHE_DIR, product=DEFAULT_PRODUCT, bounds=None, max_download_tiles=9, **kwargs): """Seed the DEM to given bounds. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice. :param bounds: Output bounds in 'left bottom right top' order. :param max_download_tiles: Maximum number of tiles to process. :param kwargs: Pass additional kwargs to ensure_tiles. """ datasource_root, spec = ensure_setup(cache_dir, product) ensure_tiles_names = list(spec['tile_names'](*bounds)) # FIXME: emergency hack to enforce the no-bulk-download policy if len(ensure_tiles_names) > max_download_tiles: raise RuntimeError("Too many tiles: %d. Please consult the providers' websites " "for how to bulk download tiles." % len(ensure_tiles_names)) with util.lock_tiles(datasource_root, ensure_tiles_names): ensure_tiles(datasource_root, ensure_tiles_names, **kwargs) with util.lock_vrt(datasource_root, product): util.check_call_make(datasource_root, targets=['all']) return datasource_root
[ "def", "seed", "(", "cache_dir", "=", "CACHE_DIR", ",", "product", "=", "DEFAULT_PRODUCT", ",", "bounds", "=", "None", ",", "max_download_tiles", "=", "9", ",", "*", "*", "kwargs", ")", ":", "datasource_root", ",", "spec", "=", "ensure_setup", "(", "cache_...
Seed the DEM to given bounds. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice. :param bounds: Output bounds in 'left bottom right top' order. :param max_download_tiles: Maximum number of tiles to process. :param kwargs: Pass additional kwargs to ensure_tiles.
[ "Seed", "the", "DEM", "to", "given", "bounds", "." ]
c982d7180f00aa1ea1465b3ac14ebcef74634be3
https://github.com/bopen/elevation/blob/c982d7180f00aa1ea1465b3ac14ebcef74634be3/elevation/datasource.py#L136-L157
train
206,159
bopen/elevation
elevation/datasource.py
clip
def clip(bounds, output=DEFAULT_OUTPUT, margin=MARGIN, **kwargs): """Clip the DEM to given bounds. :param bounds: Output bounds in 'left bottom right top' order. :param output: Path to output file. Existing files will be overwritten. :param margin: Decimal degree margin added to the bounds. Use '%' for percent margin. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice. """ bounds = build_bounds(bounds, margin=margin) datasource_root = seed(bounds=bounds, **kwargs) do_clip(datasource_root, bounds, output, **kwargs)
python
def clip(bounds, output=DEFAULT_OUTPUT, margin=MARGIN, **kwargs): """Clip the DEM to given bounds. :param bounds: Output bounds in 'left bottom right top' order. :param output: Path to output file. Existing files will be overwritten. :param margin: Decimal degree margin added to the bounds. Use '%' for percent margin. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice. """ bounds = build_bounds(bounds, margin=margin) datasource_root = seed(bounds=bounds, **kwargs) do_clip(datasource_root, bounds, output, **kwargs)
[ "def", "clip", "(", "bounds", ",", "output", "=", "DEFAULT_OUTPUT", ",", "margin", "=", "MARGIN", ",", "*", "*", "kwargs", ")", ":", "bounds", "=", "build_bounds", "(", "bounds", ",", "margin", "=", "margin", ")", "datasource_root", "=", "seed", "(", "...
Clip the DEM to given bounds. :param bounds: Output bounds in 'left bottom right top' order. :param output: Path to output file. Existing files will be overwritten. :param margin: Decimal degree margin added to the bounds. Use '%' for percent margin. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice.
[ "Clip", "the", "DEM", "to", "given", "bounds", "." ]
c982d7180f00aa1ea1465b3ac14ebcef74634be3
https://github.com/bopen/elevation/blob/c982d7180f00aa1ea1465b3ac14ebcef74634be3/elevation/datasource.py#L171-L182
train
206,160
bopen/elevation
elevation/datasource.py
info
def info(cache_dir=CACHE_DIR, product=DEFAULT_PRODUCT): """Show info about the product cache. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice. """ datasource_root, _ = ensure_setup(cache_dir, product) util.check_call_make(datasource_root, targets=['info'])
python
def info(cache_dir=CACHE_DIR, product=DEFAULT_PRODUCT): """Show info about the product cache. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice. """ datasource_root, _ = ensure_setup(cache_dir, product) util.check_call_make(datasource_root, targets=['info'])
[ "def", "info", "(", "cache_dir", "=", "CACHE_DIR", ",", "product", "=", "DEFAULT_PRODUCT", ")", ":", "datasource_root", ",", "_", "=", "ensure_setup", "(", "cache_dir", ",", "product", ")", "util", ".", "check_call_make", "(", "datasource_root", ",", "targets"...
Show info about the product cache. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice.
[ "Show", "info", "about", "the", "product", "cache", "." ]
c982d7180f00aa1ea1465b3ac14ebcef74634be3
https://github.com/bopen/elevation/blob/c982d7180f00aa1ea1465b3ac14ebcef74634be3/elevation/datasource.py#L185-L192
train
206,161
tumblr/pytumblr
interactive_console.py
new_oauth
def new_oauth(yaml_path): ''' Return the consumer and oauth tokens with three-legged OAuth process and save in a yaml file in the user's home directory. ''' print('Retrieve consumer key and consumer secret from http://www.tumblr.com/oauth/apps') consumer_key = input('Paste the consumer key here: ').strip() consumer_secret = input('Paste the consumer secret here: ').strip() request_token_url = 'http://www.tumblr.com/oauth/request_token' authorize_url = 'http://www.tumblr.com/oauth/authorize' access_token_url = 'http://www.tumblr.com/oauth/access_token' # STEP 1: Obtain request token oauth_session = OAuth1Session(consumer_key, client_secret=consumer_secret) fetch_response = oauth_session.fetch_request_token(request_token_url) resource_owner_key = fetch_response.get('oauth_token') resource_owner_secret = fetch_response.get('oauth_token_secret') # STEP 2: Authorize URL + Rresponse full_authorize_url = oauth_session.authorization_url(authorize_url) # Redirect to authentication page print('\nPlease go here and authorize:\n{}'.format(full_authorize_url)) redirect_response = input('Allow then paste the full redirect URL here:\n').strip() # Retrieve oauth verifier oauth_response = oauth_session.parse_authorization_response(redirect_response) verifier = oauth_response.get('oauth_verifier') # STEP 3: Request final access token oauth_session = OAuth1Session( consumer_key, client_secret=consumer_secret, resource_owner_key=resource_owner_key, resource_owner_secret=resource_owner_secret, verifier=verifier ) oauth_tokens = oauth_session.fetch_access_token(access_token_url) tokens = { 'consumer_key': consumer_key, 'consumer_secret': consumer_secret, 'oauth_token': oauth_tokens.get('oauth_token'), 'oauth_token_secret': oauth_tokens.get('oauth_token_secret') } yaml_file = open(yaml_path, 'w+') yaml.dump(tokens, yaml_file, indent=2) yaml_file.close() return tokens
python
def new_oauth(yaml_path): ''' Return the consumer and oauth tokens with three-legged OAuth process and save in a yaml file in the user's home directory. ''' print('Retrieve consumer key and consumer secret from http://www.tumblr.com/oauth/apps') consumer_key = input('Paste the consumer key here: ').strip() consumer_secret = input('Paste the consumer secret here: ').strip() request_token_url = 'http://www.tumblr.com/oauth/request_token' authorize_url = 'http://www.tumblr.com/oauth/authorize' access_token_url = 'http://www.tumblr.com/oauth/access_token' # STEP 1: Obtain request token oauth_session = OAuth1Session(consumer_key, client_secret=consumer_secret) fetch_response = oauth_session.fetch_request_token(request_token_url) resource_owner_key = fetch_response.get('oauth_token') resource_owner_secret = fetch_response.get('oauth_token_secret') # STEP 2: Authorize URL + Rresponse full_authorize_url = oauth_session.authorization_url(authorize_url) # Redirect to authentication page print('\nPlease go here and authorize:\n{}'.format(full_authorize_url)) redirect_response = input('Allow then paste the full redirect URL here:\n').strip() # Retrieve oauth verifier oauth_response = oauth_session.parse_authorization_response(redirect_response) verifier = oauth_response.get('oauth_verifier') # STEP 3: Request final access token oauth_session = OAuth1Session( consumer_key, client_secret=consumer_secret, resource_owner_key=resource_owner_key, resource_owner_secret=resource_owner_secret, verifier=verifier ) oauth_tokens = oauth_session.fetch_access_token(access_token_url) tokens = { 'consumer_key': consumer_key, 'consumer_secret': consumer_secret, 'oauth_token': oauth_tokens.get('oauth_token'), 'oauth_token_secret': oauth_tokens.get('oauth_token_secret') } yaml_file = open(yaml_path, 'w+') yaml.dump(tokens, yaml_file, indent=2) yaml_file.close() return tokens
[ "def", "new_oauth", "(", "yaml_path", ")", ":", "print", "(", "'Retrieve consumer key and consumer secret from http://www.tumblr.com/oauth/apps'", ")", "consumer_key", "=", "input", "(", "'Paste the consumer key here: '", ")", ".", "strip", "(", ")", "consumer_secret", "=",...
Return the consumer and oauth tokens with three-legged OAuth process and save in a yaml file in the user's home directory.
[ "Return", "the", "consumer", "and", "oauth", "tokens", "with", "three", "-", "legged", "OAuth", "process", "and", "save", "in", "a", "yaml", "file", "in", "the", "user", "s", "home", "directory", "." ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/interactive_console.py#L14-L67
train
206,162
tumblr/pytumblr
pytumblr/helpers.py
validate_params
def validate_params(valid_options, params): """ Helps us validate the parameters for the request :param valid_options: a list of strings of valid options for the api request :param params: a dict, the key-value store which we really only care about the key which has tells us what the user is using for the API request :returns: None or throws an exception if the validation fails """ #crazy little if statement hanging by himself :( if not params: return #We only allow one version of the data parameter to be passed data_filter = ['data', 'source', 'external_url', 'embed'] multiple_data = [key for key in params.keys() if key in data_filter] if len(multiple_data) > 1: raise Exception("You can't mix and match data parameters") #No bad fields which are not in valid options can pass disallowed_fields = [key for key in params.keys() if key not in valid_options] if disallowed_fields: field_strings = ",".join(disallowed_fields) raise Exception("{} are not allowed fields".format(field_strings))
python
def validate_params(valid_options, params): """ Helps us validate the parameters for the request :param valid_options: a list of strings of valid options for the api request :param params: a dict, the key-value store which we really only care about the key which has tells us what the user is using for the API request :returns: None or throws an exception if the validation fails """ #crazy little if statement hanging by himself :( if not params: return #We only allow one version of the data parameter to be passed data_filter = ['data', 'source', 'external_url', 'embed'] multiple_data = [key for key in params.keys() if key in data_filter] if len(multiple_data) > 1: raise Exception("You can't mix and match data parameters") #No bad fields which are not in valid options can pass disallowed_fields = [key for key in params.keys() if key not in valid_options] if disallowed_fields: field_strings = ",".join(disallowed_fields) raise Exception("{} are not allowed fields".format(field_strings))
[ "def", "validate_params", "(", "valid_options", ",", "params", ")", ":", "#crazy little if statement hanging by himself :(", "if", "not", "params", ":", "return", "#We only allow one version of the data parameter to be passed", "data_filter", "=", "[", "'data'", ",", "'source...
Helps us validate the parameters for the request :param valid_options: a list of strings of valid options for the api request :param params: a dict, the key-value store which we really only care about the key which has tells us what the user is using for the API request :returns: None or throws an exception if the validation fails
[ "Helps", "us", "validate", "the", "parameters", "for", "the", "request" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/helpers.py#L3-L29
train
206,163
tumblr/pytumblr
pytumblr/request.py
TumblrRequest.get
def get(self, url, params): """ Issues a GET request against the API, properly formatting the params :param url: a string, the url you are requesting :param params: a dict, the key-value of all the paramaters needed in the request :returns: a dict parsed of the JSON response """ url = self.host + url if params: url = url + "?" + urllib.parse.urlencode(params) try: resp = requests.get(url, allow_redirects=False, headers=self.headers, auth=self.oauth) except TooManyRedirects as e: resp = e.response return self.json_parse(resp)
python
def get(self, url, params): """ Issues a GET request against the API, properly formatting the params :param url: a string, the url you are requesting :param params: a dict, the key-value of all the paramaters needed in the request :returns: a dict parsed of the JSON response """ url = self.host + url if params: url = url + "?" + urllib.parse.urlencode(params) try: resp = requests.get(url, allow_redirects=False, headers=self.headers, auth=self.oauth) except TooManyRedirects as e: resp = e.response return self.json_parse(resp)
[ "def", "get", "(", "self", ",", "url", ",", "params", ")", ":", "url", "=", "self", ".", "host", "+", "url", "if", "params", ":", "url", "=", "url", "+", "\"?\"", "+", "urllib", ".", "parse", ".", "urlencode", "(", "params", ")", "try", ":", "r...
Issues a GET request against the API, properly formatting the params :param url: a string, the url you are requesting :param params: a dict, the key-value of all the paramaters needed in the request :returns: a dict parsed of the JSON response
[ "Issues", "a", "GET", "request", "against", "the", "API", "properly", "formatting", "the", "params" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/request.py#L35-L53
train
206,164
tumblr/pytumblr
pytumblr/request.py
TumblrRequest.post
def post(self, url, params={}, files=[]): """ Issues a POST request against the API, allows for multipart data uploads :param url: a string, the url you are requesting :param params: a dict, the key-value of all the parameters needed in the request :param files: a list, the list of tuples of files :returns: a dict parsed of the JSON response """ url = self.host + url try: if files: return self.post_multipart(url, params, files) else: data = urllib.parse.urlencode(params) if not PY3: data = str(data) resp = requests.post(url, data=data, headers=self.headers, auth=self.oauth) return self.json_parse(resp) except HTTPError as e: return self.json_parse(e.response)
python
def post(self, url, params={}, files=[]): """ Issues a POST request against the API, allows for multipart data uploads :param url: a string, the url you are requesting :param params: a dict, the key-value of all the parameters needed in the request :param files: a list, the list of tuples of files :returns: a dict parsed of the JSON response """ url = self.host + url try: if files: return self.post_multipart(url, params, files) else: data = urllib.parse.urlencode(params) if not PY3: data = str(data) resp = requests.post(url, data=data, headers=self.headers, auth=self.oauth) return self.json_parse(resp) except HTTPError as e: return self.json_parse(e.response)
[ "def", "post", "(", "self", ",", "url", ",", "params", "=", "{", "}", ",", "files", "=", "[", "]", ")", ":", "url", "=", "self", ".", "host", "+", "url", "try", ":", "if", "files", ":", "return", "self", ".", "post_multipart", "(", "url", ",", ...
Issues a POST request against the API, allows for multipart data uploads :param url: a string, the url you are requesting :param params: a dict, the key-value of all the parameters needed in the request :param files: a list, the list of tuples of files :returns: a dict parsed of the JSON response
[ "Issues", "a", "POST", "request", "against", "the", "API", "allows", "for", "multipart", "data", "uploads" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/request.py#L55-L77
train
206,165
tumblr/pytumblr
pytumblr/request.py
TumblrRequest.json_parse
def json_parse(self, response): """ Wraps and abstracts response validation and JSON parsing to make sure the user gets the correct response. :param response: The response returned to us from the request :returns: a dict of the json response """ try: data = response.json() except ValueError: data = {'meta': { 'status': 500, 'msg': 'Server Error'}, 'response': {"error": "Malformed JSON or HTML was returned."}} # We only really care about the response if we succeed # and the error if we fail if 200 <= data['meta']['status'] <= 399: return data['response'] else: return data
python
def json_parse(self, response): """ Wraps and abstracts response validation and JSON parsing to make sure the user gets the correct response. :param response: The response returned to us from the request :returns: a dict of the json response """ try: data = response.json() except ValueError: data = {'meta': { 'status': 500, 'msg': 'Server Error'}, 'response': {"error": "Malformed JSON or HTML was returned."}} # We only really care about the response if we succeed # and the error if we fail if 200 <= data['meta']['status'] <= 399: return data['response'] else: return data
[ "def", "json_parse", "(", "self", ",", "response", ")", ":", "try", ":", "data", "=", "response", ".", "json", "(", ")", "except", "ValueError", ":", "data", "=", "{", "'meta'", ":", "{", "'status'", ":", "500", ",", "'msg'", ":", "'Server Error'", "...
Wraps and abstracts response validation and JSON parsing to make sure the user gets the correct response. :param response: The response returned to us from the request :returns: a dict of the json response
[ "Wraps", "and", "abstracts", "response", "validation", "and", "JSON", "parsing", "to", "make", "sure", "the", "user", "gets", "the", "correct", "response", "." ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/request.py#L79-L98
train
206,166
tumblr/pytumblr
pytumblr/request.py
TumblrRequest.post_multipart
def post_multipart(self, url, params, files): """ Generates and issues a multipart request for data files :param url: a string, the url you are requesting :param params: a dict, a key-value of all the parameters :param files: a dict, matching the form '{name: file descriptor}' :returns: a dict parsed from the JSON response """ resp = requests.post( url, data=params, params=params, files=files, headers=self.headers, allow_redirects=False, auth=self.oauth ) return self.json_parse(resp)
python
def post_multipart(self, url, params, files): """ Generates and issues a multipart request for data files :param url: a string, the url you are requesting :param params: a dict, a key-value of all the parameters :param files: a dict, matching the form '{name: file descriptor}' :returns: a dict parsed from the JSON response """ resp = requests.post( url, data=params, params=params, files=files, headers=self.headers, allow_redirects=False, auth=self.oauth ) return self.json_parse(resp)
[ "def", "post_multipart", "(", "self", ",", "url", ",", "params", ",", "files", ")", ":", "resp", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "params", ",", "params", "=", "params", ",", "files", "=", "files", ",", "headers", "=", "s...
Generates and issues a multipart request for data files :param url: a string, the url you are requesting :param params: a dict, a key-value of all the parameters :param files: a dict, matching the form '{name: file descriptor}' :returns: a dict parsed from the JSON response
[ "Generates", "and", "issues", "a", "multipart", "request", "for", "data", "files" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/request.py#L100-L119
train
206,167
tumblr/pytumblr
pytumblr/__init__.py
TumblrRestClient.avatar
def avatar(self, blogname, size=64): """ Retrieves the url of the blog's avatar :param blogname: a string, the blog you want the avatar for :returns: A dict created from the JSON response """ url = "/v2/blog/{}/avatar/{}".format(blogname, size) return self.send_api_request("get", url)
python
def avatar(self, blogname, size=64): """ Retrieves the url of the blog's avatar :param blogname: a string, the blog you want the avatar for :returns: A dict created from the JSON response """ url = "/v2/blog/{}/avatar/{}".format(blogname, size) return self.send_api_request("get", url)
[ "def", "avatar", "(", "self", ",", "blogname", ",", "size", "=", "64", ")", ":", "url", "=", "\"/v2/blog/{}/avatar/{}\"", ".", "format", "(", "blogname", ",", "size", ")", "return", "self", ".", "send_api_request", "(", "\"get\"", ",", "url", ")" ]
Retrieves the url of the blog's avatar :param blogname: a string, the blog you want the avatar for :returns: A dict created from the JSON response
[ "Retrieves", "the", "url", "of", "the", "blog", "s", "avatar" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L42-L51
train
206,168
tumblr/pytumblr
pytumblr/__init__.py
TumblrRestClient.tagged
def tagged(self, tag, **kwargs): """ Gets a list of posts tagged with the given tag :param tag: a string, the tag you want to look for :param before: a unix timestamp, the timestamp you want to start at to look at posts. :param limit: the number of results you want :param filter: the post format that you want returned: html, text, raw client.tagged("gif", limit=10) :returns: a dict created from the JSON response """ kwargs.update({'tag': tag}) return self.send_api_request("get", '/v2/tagged', kwargs, ['before', 'limit', 'filter', 'tag', 'api_key'], True)
python
def tagged(self, tag, **kwargs): """ Gets a list of posts tagged with the given tag :param tag: a string, the tag you want to look for :param before: a unix timestamp, the timestamp you want to start at to look at posts. :param limit: the number of results you want :param filter: the post format that you want returned: html, text, raw client.tagged("gif", limit=10) :returns: a dict created from the JSON response """ kwargs.update({'tag': tag}) return self.send_api_request("get", '/v2/tagged', kwargs, ['before', 'limit', 'filter', 'tag', 'api_key'], True)
[ "def", "tagged", "(", "self", ",", "tag", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'tag'", ":", "tag", "}", ")", "return", "self", ".", "send_api_request", "(", "\"get\"", ",", "'/v2/tagged'", ",", "kwargs", ",", "[", ...
Gets a list of posts tagged with the given tag :param tag: a string, the tag you want to look for :param before: a unix timestamp, the timestamp you want to start at to look at posts. :param limit: the number of results you want :param filter: the post format that you want returned: html, text, raw client.tagged("gif", limit=10) :returns: a dict created from the JSON response
[ "Gets", "a", "list", "of", "posts", "tagged", "with", "the", "given", "tag" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L96-L111
train
206,169
tumblr/pytumblr
pytumblr/__init__.py
TumblrRestClient.posts
def posts(self, blogname, type=None, **kwargs): """ Gets a list of posts from a particular blog :param blogname: a string, the blogname you want to look up posts for. eg: codingjester.tumblr.com :param id: an int, the id of the post you are looking for on the blog :param tag: a string, the tag you are looking for on posts :param limit: an int, the number of results you want :param offset: an int, the offset of the posts you want to start at. :param before: an int, the timestamp for posts you want before. :param filter: the post format you want returned: HTML, text or raw. :param type: the type of posts you want returned, e.g. video. If omitted returns all post types. :returns: a dict created from the JSON response """ if type is None: url = '/v2/blog/{}/posts'.format(blogname) else: url = '/v2/blog/{}/posts/{}'.format(blogname, type) return self.send_api_request("get", url, kwargs, ['id', 'tag', 'limit', 'offset', 'before', 'reblog_info', 'notes_info', 'filter', 'api_key'], True)
python
def posts(self, blogname, type=None, **kwargs): """ Gets a list of posts from a particular blog :param blogname: a string, the blogname you want to look up posts for. eg: codingjester.tumblr.com :param id: an int, the id of the post you are looking for on the blog :param tag: a string, the tag you are looking for on posts :param limit: an int, the number of results you want :param offset: an int, the offset of the posts you want to start at. :param before: an int, the timestamp for posts you want before. :param filter: the post format you want returned: HTML, text or raw. :param type: the type of posts you want returned, e.g. video. If omitted returns all post types. :returns: a dict created from the JSON response """ if type is None: url = '/v2/blog/{}/posts'.format(blogname) else: url = '/v2/blog/{}/posts/{}'.format(blogname, type) return self.send_api_request("get", url, kwargs, ['id', 'tag', 'limit', 'offset', 'before', 'reblog_info', 'notes_info', 'filter', 'api_key'], True)
[ "def", "posts", "(", "self", ",", "blogname", ",", "type", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "type", "is", "None", ":", "url", "=", "'/v2/blog/{}/posts'", ".", "format", "(", "blogname", ")", "else", ":", "url", "=", "'/v2/blog/{}...
Gets a list of posts from a particular blog :param blogname: a string, the blogname you want to look up posts for. eg: codingjester.tumblr.com :param id: an int, the id of the post you are looking for on the blog :param tag: a string, the tag you are looking for on posts :param limit: an int, the number of results you want :param offset: an int, the offset of the posts you want to start at. :param before: an int, the timestamp for posts you want before. :param filter: the post format you want returned: HTML, text or raw. :param type: the type of posts you want returned, e.g. video. If omitted returns all post types. :returns: a dict created from the JSON response
[ "Gets", "a", "list", "of", "posts", "from", "a", "particular", "blog" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L114-L134
train
206,170
tumblr/pytumblr
pytumblr/__init__.py
TumblrRestClient.blog_info
def blog_info(self, blogname): """ Gets the information of the given blog :param blogname: the name of the blog you want to information on. eg: codingjester.tumblr.com :returns: a dict created from the JSON response of information """ url = "/v2/blog/{}/info".format(blogname) return self.send_api_request("get", url, {}, ['api_key'], True)
python
def blog_info(self, blogname): """ Gets the information of the given blog :param blogname: the name of the blog you want to information on. eg: codingjester.tumblr.com :returns: a dict created from the JSON response of information """ url = "/v2/blog/{}/info".format(blogname) return self.send_api_request("get", url, {}, ['api_key'], True)
[ "def", "blog_info", "(", "self", ",", "blogname", ")", ":", "url", "=", "\"/v2/blog/{}/info\"", ".", "format", "(", "blogname", ")", "return", "self", ".", "send_api_request", "(", "\"get\"", ",", "url", ",", "{", "}", ",", "[", "'api_key'", "]", ",", ...
Gets the information of the given blog :param blogname: the name of the blog you want to information on. eg: codingjester.tumblr.com :returns: a dict created from the JSON response of information
[ "Gets", "the", "information", "of", "the", "given", "blog" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L137-L147
train
206,171
tumblr/pytumblr
pytumblr/__init__.py
TumblrRestClient.blog_following
def blog_following(self, blogname, **kwargs): """ Gets the publicly exposed list of blogs that a blog follows :param blogname: the name of the blog you want to get information on. eg: codingjester.tumblr.com :param limit: an int, the number of blogs you want returned :param offset: an int, the blog to start at, for pagination. # Start at the 20th blog and get 20 more blogs. client.blog_following('pytblr', offset=20, limit=20}) :returns: a dict created from the JSON response """ url = "/v2/blog/{}/following".format(blogname) return self.send_api_request("get", url, kwargs, ['limit', 'offset'])
python
def blog_following(self, blogname, **kwargs): """ Gets the publicly exposed list of blogs that a blog follows :param blogname: the name of the blog you want to get information on. eg: codingjester.tumblr.com :param limit: an int, the number of blogs you want returned :param offset: an int, the blog to start at, for pagination. # Start at the 20th blog and get 20 more blogs. client.blog_following('pytblr', offset=20, limit=20}) :returns: a dict created from the JSON response """ url = "/v2/blog/{}/following".format(blogname) return self.send_api_request("get", url, kwargs, ['limit', 'offset'])
[ "def", "blog_following", "(", "self", ",", "blogname", ",", "*", "*", "kwargs", ")", ":", "url", "=", "\"/v2/blog/{}/following\"", ".", "format", "(", "blogname", ")", "return", "self", ".", "send_api_request", "(", "\"get\"", ",", "url", ",", "kwargs", ",...
Gets the publicly exposed list of blogs that a blog follows :param blogname: the name of the blog you want to get information on. eg: codingjester.tumblr.com :param limit: an int, the number of blogs you want returned :param offset: an int, the blog to start at, for pagination. # Start at the 20th blog and get 20 more blogs. client.blog_following('pytblr', offset=20, limit=20}) :returns: a dict created from the JSON response
[ "Gets", "the", "publicly", "exposed", "list", "of", "blogs", "that", "a", "blog", "follows" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L150-L166
train
206,172
tumblr/pytumblr
pytumblr/__init__.py
TumblrRestClient.like
def like(self, id, reblog_key): """ Like the post of the given blog :param id: an int, the id of the post you want to like :param reblog_key: a string, the reblog key of the post :returns: a dict created from the JSON response """ url = "/v2/user/like" params = {'id': id, 'reblog_key': reblog_key} return self.send_api_request("post", url, params, ['id', 'reblog_key'])
python
def like(self, id, reblog_key): """ Like the post of the given blog :param id: an int, the id of the post you want to like :param reblog_key: a string, the reblog key of the post :returns: a dict created from the JSON response """ url = "/v2/user/like" params = {'id': id, 'reblog_key': reblog_key} return self.send_api_request("post", url, params, ['id', 'reblog_key'])
[ "def", "like", "(", "self", ",", "id", ",", "reblog_key", ")", ":", "url", "=", "\"/v2/user/like\"", "params", "=", "{", "'id'", ":", "id", ",", "'reblog_key'", ":", "reblog_key", "}", "return", "self", ".", "send_api_request", "(", "\"post\"", ",", "url...
Like the post of the given blog :param id: an int, the id of the post you want to like :param reblog_key: a string, the reblog key of the post :returns: a dict created from the JSON response
[ "Like", "the", "post", "of", "the", "given", "blog" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L262-L273
train
206,173
tumblr/pytumblr
pytumblr/__init__.py
TumblrRestClient.unlike
def unlike(self, id, reblog_key): """ Unlike the post of the given blog :param id: an int, the id of the post you want to like :param reblog_key: a string, the reblog key of the post :returns: a dict created from the JSON response """ url = "/v2/user/unlike" params = {'id': id, 'reblog_key': reblog_key} return self.send_api_request("post", url, params, ['id', 'reblog_key'])
python
def unlike(self, id, reblog_key): """ Unlike the post of the given blog :param id: an int, the id of the post you want to like :param reblog_key: a string, the reblog key of the post :returns: a dict created from the JSON response """ url = "/v2/user/unlike" params = {'id': id, 'reblog_key': reblog_key} return self.send_api_request("post", url, params, ['id', 'reblog_key'])
[ "def", "unlike", "(", "self", ",", "id", ",", "reblog_key", ")", ":", "url", "=", "\"/v2/user/unlike\"", "params", "=", "{", "'id'", ":", "id", ",", "'reblog_key'", ":", "reblog_key", "}", "return", "self", ".", "send_api_request", "(", "\"post\"", ",", ...
Unlike the post of the given blog :param id: an int, the id of the post you want to like :param reblog_key: a string, the reblog key of the post :returns: a dict created from the JSON response
[ "Unlike", "the", "post", "of", "the", "given", "blog" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L275-L286
train
206,174
tumblr/pytumblr
pytumblr/__init__.py
TumblrRestClient.create_photo
def create_photo(self, blogname, **kwargs): """ Create a photo post or photoset on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param caption: a string, the caption that you want applied to the photo :param link: a string, the 'click-through' url you want on the photo :param source: a string, the photo source url :param data: a string or a list of the path of photo(s) :returns: a dict created from the JSON response """ kwargs.update({"type": "photo"}) return self._send_post(blogname, kwargs)
python
def create_photo(self, blogname, **kwargs): """ Create a photo post or photoset on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param caption: a string, the caption that you want applied to the photo :param link: a string, the 'click-through' url you want on the photo :param source: a string, the photo source url :param data: a string or a list of the path of photo(s) :returns: a dict created from the JSON response """ kwargs.update({"type": "photo"}) return self._send_post(blogname, kwargs)
[ "def", "create_photo", "(", "self", ",", "blogname", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "\"type\"", ":", "\"photo\"", "}", ")", "return", "self", ".", "_send_post", "(", "blogname", ",", "kwargs", ")" ]
Create a photo post or photoset on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param caption: a string, the caption that you want applied to the photo :param link: a string, the 'click-through' url you want on the photo :param source: a string, the photo source url :param data: a string or a list of the path of photo(s) :returns: a dict created from the JSON response
[ "Create", "a", "photo", "post", "or", "photoset", "on", "a", "blog" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L289-L308
train
206,175
tumblr/pytumblr
pytumblr/__init__.py
TumblrRestClient.create_text
def create_text(self, blogname, **kwargs): """ Create a text post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param title: a string, the optional title of a post :param body: a string, the body of the text post :returns: a dict created from the JSON response """ kwargs.update({"type": "text"}) return self._send_post(blogname, kwargs)
python
def create_text(self, blogname, **kwargs): """ Create a text post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param title: a string, the optional title of a post :param body: a string, the body of the text post :returns: a dict created from the JSON response """ kwargs.update({"type": "text"}) return self._send_post(blogname, kwargs)
[ "def", "create_text", "(", "self", ",", "blogname", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "\"type\"", ":", "\"text\"", "}", ")", "return", "self", ".", "_send_post", "(", "blogname", ",", "kwargs", ")" ]
Create a text post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param title: a string, the optional title of a post :param body: a string, the body of the text post :returns: a dict created from the JSON response
[ "Create", "a", "text", "post", "on", "a", "blog" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L311-L328
train
206,176
tumblr/pytumblr
pytumblr/__init__.py
TumblrRestClient.create_quote
def create_quote(self, blogname, **kwargs): """ Create a quote post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param quote: a string, the full text of the quote :param source: a string, the cited source of the quote :returns: a dict created from the JSON response """ kwargs.update({"type": "quote"}) return self._send_post(blogname, kwargs)
python
def create_quote(self, blogname, **kwargs): """ Create a quote post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param quote: a string, the full text of the quote :param source: a string, the cited source of the quote :returns: a dict created from the JSON response """ kwargs.update({"type": "quote"}) return self._send_post(blogname, kwargs)
[ "def", "create_quote", "(", "self", ",", "blogname", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "\"type\"", ":", "\"quote\"", "}", ")", "return", "self", ".", "_send_post", "(", "blogname", ",", "kwargs", ")" ]
Create a quote post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param quote: a string, the full text of the quote :param source: a string, the cited source of the quote :returns: a dict created from the JSON response
[ "Create", "a", "quote", "post", "on", "a", "blog" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L331-L348
train
206,177
tumblr/pytumblr
pytumblr/__init__.py
TumblrRestClient.create_link
def create_link(self, blogname, **kwargs): """ Create a link post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param title: a string, the title of the link :param url: a string, the url of the link you are posting :param description: a string, the description of the link you are posting :returns: a dict created from the JSON response """ kwargs.update({"type": "link"}) return self._send_post(blogname, kwargs)
python
def create_link(self, blogname, **kwargs): """ Create a link post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param title: a string, the title of the link :param url: a string, the url of the link you are posting :param description: a string, the description of the link you are posting :returns: a dict created from the JSON response """ kwargs.update({"type": "link"}) return self._send_post(blogname, kwargs)
[ "def", "create_link", "(", "self", ",", "blogname", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "\"type\"", ":", "\"link\"", "}", ")", "return", "self", ".", "_send_post", "(", "blogname", ",", "kwargs", ")" ]
Create a link post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param title: a string, the title of the link :param url: a string, the url of the link you are posting :param description: a string, the description of the link you are posting :returns: a dict created from the JSON response
[ "Create", "a", "link", "post", "on", "a", "blog" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L351-L369
train
206,178
tumblr/pytumblr
pytumblr/__init__.py
TumblrRestClient.create_chat
def create_chat(self, blogname, **kwargs): """ Create a chat post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param title: a string, the title of the conversation :param conversation: a string, the conversation you are posting :returns: a dict created from the JSON response """ kwargs.update({"type": "chat"}) return self._send_post(blogname, kwargs)
python
def create_chat(self, blogname, **kwargs): """ Create a chat post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param title: a string, the title of the conversation :param conversation: a string, the conversation you are posting :returns: a dict created from the JSON response """ kwargs.update({"type": "chat"}) return self._send_post(blogname, kwargs)
[ "def", "create_chat", "(", "self", ",", "blogname", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "\"type\"", ":", "\"chat\"", "}", ")", "return", "self", ".", "_send_post", "(", "blogname", ",", "kwargs", ")" ]
Create a chat post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param title: a string, the title of the conversation :param conversation: a string, the conversation you are posting :returns: a dict created from the JSON response
[ "Create", "a", "chat", "post", "on", "a", "blog" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L372-L389
train
206,179
tumblr/pytumblr
pytumblr/__init__.py
TumblrRestClient.reblog
def reblog(self, blogname, **kwargs): """ Creates a reblog on the given blogname :param blogname: a string, the url of the blog you want to reblog to :param id: an int, the post id that you are reblogging :param reblog_key: a string, the reblog key of the post :param comment: a string, a comment added to the reblogged post :returns: a dict created from the JSON response """ url = "/v2/blog/{}/post/reblog".format(blogname) valid_options = ['id', 'reblog_key', 'comment'] + self._post_valid_options(kwargs.get('type', None)) if 'tags' in kwargs and kwargs['tags']: # Take a list of tags and make them acceptable for upload kwargs['tags'] = ",".join(kwargs['tags']) return self.send_api_request('post', url, kwargs, valid_options)
python
def reblog(self, blogname, **kwargs): """ Creates a reblog on the given blogname :param blogname: a string, the url of the blog you want to reblog to :param id: an int, the post id that you are reblogging :param reblog_key: a string, the reblog key of the post :param comment: a string, a comment added to the reblogged post :returns: a dict created from the JSON response """ url = "/v2/blog/{}/post/reblog".format(blogname) valid_options = ['id', 'reblog_key', 'comment'] + self._post_valid_options(kwargs.get('type', None)) if 'tags' in kwargs and kwargs['tags']: # Take a list of tags and make them acceptable for upload kwargs['tags'] = ",".join(kwargs['tags']) return self.send_api_request('post', url, kwargs, valid_options)
[ "def", "reblog", "(", "self", ",", "blogname", ",", "*", "*", "kwargs", ")", ":", "url", "=", "\"/v2/blog/{}/post/reblog\"", ".", "format", "(", "blogname", ")", "valid_options", "=", "[", "'id'", ",", "'reblog_key'", ",", "'comment'", "]", "+", "self", ...
Creates a reblog on the given blogname :param blogname: a string, the url of the blog you want to reblog to :param id: an int, the post id that you are reblogging :param reblog_key: a string, the reblog key of the post :param comment: a string, a comment added to the reblogged post :returns: a dict created from the JSON response
[ "Creates", "a", "reblog", "on", "the", "given", "blogname" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L434-L451
train
206,180
tumblr/pytumblr
pytumblr/__init__.py
TumblrRestClient.delete_post
def delete_post(self, blogname, id): """ Deletes a post with the given id :param blogname: a string, the url of the blog you want to delete from :param id: an int, the post id that you want to delete :returns: a dict created from the JSON response """ url = "/v2/blog/{}/post/delete".format(blogname) return self.send_api_request('post', url, {'id': id}, ['id'])
python
def delete_post(self, blogname, id): """ Deletes a post with the given id :param blogname: a string, the url of the blog you want to delete from :param id: an int, the post id that you want to delete :returns: a dict created from the JSON response """ url = "/v2/blog/{}/post/delete".format(blogname) return self.send_api_request('post', url, {'id': id}, ['id'])
[ "def", "delete_post", "(", "self", ",", "blogname", ",", "id", ")", ":", "url", "=", "\"/v2/blog/{}/post/delete\"", ".", "format", "(", "blogname", ")", "return", "self", ".", "send_api_request", "(", "'post'", ",", "url", ",", "{", "'id'", ":", "id", "}...
Deletes a post with the given id :param blogname: a string, the url of the blog you want to delete from :param id: an int, the post id that you want to delete :returns: a dict created from the JSON response
[ "Deletes", "a", "post", "with", "the", "given", "id" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L454-L464
train
206,181
tumblr/pytumblr
pytumblr/__init__.py
TumblrRestClient._send_post
def _send_post(self, blogname, params): """ Formats parameters and sends the API request off. Validates common and per-post-type parameters and formats your tags for you. :param blogname: a string, the blogname of the blog you are posting to :param params: a dict, the key-value of the parameters for the api request :param valid_options: a list of valid options that the request allows :returns: a dict parsed from the JSON response """ url = "/v2/blog/{}/post".format(blogname) valid_options = self._post_valid_options(params.get('type', None)) if len(params.get("tags", [])) > 0: # Take a list of tags and make them acceptable for upload params['tags'] = ",".join(params['tags']) return self.send_api_request("post", url, params, valid_options)
python
def _send_post(self, blogname, params): """ Formats parameters and sends the API request off. Validates common and per-post-type parameters and formats your tags for you. :param blogname: a string, the blogname of the blog you are posting to :param params: a dict, the key-value of the parameters for the api request :param valid_options: a list of valid options that the request allows :returns: a dict parsed from the JSON response """ url = "/v2/blog/{}/post".format(blogname) valid_options = self._post_valid_options(params.get('type', None)) if len(params.get("tags", [])) > 0: # Take a list of tags and make them acceptable for upload params['tags'] = ",".join(params['tags']) return self.send_api_request("post", url, params, valid_options)
[ "def", "_send_post", "(", "self", ",", "blogname", ",", "params", ")", ":", "url", "=", "\"/v2/blog/{}/post\"", ".", "format", "(", "blogname", ")", "valid_options", "=", "self", ".", "_post_valid_options", "(", "params", ".", "get", "(", "'type'", ",", "N...
Formats parameters and sends the API request off. Validates common and per-post-type parameters and formats your tags for you. :param blogname: a string, the blogname of the blog you are posting to :param params: a dict, the key-value of the parameters for the api request :param valid_options: a list of valid options that the request allows :returns: a dict parsed from the JSON response
[ "Formats", "parameters", "and", "sends", "the", "API", "request", "off", ".", "Validates", "common", "and", "per", "-", "post", "-", "type", "parameters", "and", "formats", "your", "tags", "for", "you", "." ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L514-L532
train
206,182
tumblr/pytumblr
pytumblr/__init__.py
TumblrRestClient.send_api_request
def send_api_request(self, method, url, params={}, valid_parameters=[], needs_api_key=False): """ Sends the url with parameters to the requested url, validating them to make sure that they are what we expect to have passed to us :param method: a string, the request method you want to make :param params: a dict, the parameters used for the API request :param valid_parameters: a list, the list of valid parameters :param needs_api_key: a boolean, whether or not your request needs an api key injected :returns: a dict parsed from the JSON response """ if needs_api_key: params.update({'api_key': self.request.consumer_key}) valid_parameters.append('api_key') files = {} if 'data' in params: if isinstance(params['data'], list): for idx, data in enumerate(params['data']): files['data['+str(idx)+']'] = open(params['data'][idx], 'rb') else: files = {'data': open(params['data'], 'rb')} del params['data'] validate_params(valid_parameters, params) if method == "get": return self.request.get(url, params) else: return self.request.post(url, params, files)
python
def send_api_request(self, method, url, params={}, valid_parameters=[], needs_api_key=False): """ Sends the url with parameters to the requested url, validating them to make sure that they are what we expect to have passed to us :param method: a string, the request method you want to make :param params: a dict, the parameters used for the API request :param valid_parameters: a list, the list of valid parameters :param needs_api_key: a boolean, whether or not your request needs an api key injected :returns: a dict parsed from the JSON response """ if needs_api_key: params.update({'api_key': self.request.consumer_key}) valid_parameters.append('api_key') files = {} if 'data' in params: if isinstance(params['data'], list): for idx, data in enumerate(params['data']): files['data['+str(idx)+']'] = open(params['data'][idx], 'rb') else: files = {'data': open(params['data'], 'rb')} del params['data'] validate_params(valid_parameters, params) if method == "get": return self.request.get(url, params) else: return self.request.post(url, params, files)
[ "def", "send_api_request", "(", "self", ",", "method", ",", "url", ",", "params", "=", "{", "}", ",", "valid_parameters", "=", "[", "]", ",", "needs_api_key", "=", "False", ")", ":", "if", "needs_api_key", ":", "params", ".", "update", "(", "{", "'api_...
Sends the url with parameters to the requested url, validating them to make sure that they are what we expect to have passed to us :param method: a string, the request method you want to make :param params: a dict, the parameters used for the API request :param valid_parameters: a list, the list of valid parameters :param needs_api_key: a boolean, whether or not your request needs an api key injected :returns: a dict parsed from the JSON response
[ "Sends", "the", "url", "with", "parameters", "to", "the", "requested", "url", "validating", "them", "to", "make", "sure", "that", "they", "are", "what", "we", "expect", "to", "have", "passed", "to", "us" ]
4a5cd7c4b8ae78d12811d9fd52620afa1692a415
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L534-L563
train
206,183
klen/pylama
pylama/lint/pylama_mccabe.py
Linter.run
def run(path, code=None, params=None, **meta): """MCCabe code checking. :return list: List of errors. """ tree = compile(code, path, "exec", ast.PyCF_ONLY_AST) McCabeChecker.max_complexity = int(params.get('complexity', 10)) return [ {'lnum': lineno, 'offset': offset, 'text': text, 'type': McCabeChecker._code} for lineno, offset, text, _ in McCabeChecker(tree, path).run() ]
python
def run(path, code=None, params=None, **meta): """MCCabe code checking. :return list: List of errors. """ tree = compile(code, path, "exec", ast.PyCF_ONLY_AST) McCabeChecker.max_complexity = int(params.get('complexity', 10)) return [ {'lnum': lineno, 'offset': offset, 'text': text, 'type': McCabeChecker._code} for lineno, offset, text, _ in McCabeChecker(tree, path).run() ]
[ "def", "run", "(", "path", ",", "code", "=", "None", ",", "params", "=", "None", ",", "*", "*", "meta", ")", ":", "tree", "=", "compile", "(", "code", ",", "path", ",", "\"exec\"", ",", "ast", ".", "PyCF_ONLY_AST", ")", "McCabeChecker", ".", "max_c...
MCCabe code checking. :return list: List of errors.
[ "MCCabe", "code", "checking", "." ]
f436ccc6b55b33381a295ded753e467953cf4379
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/lint/pylama_mccabe.py#L13-L24
train
206,184
klen/pylama
pylama/config.py
split_csp_str
def split_csp_str(val): """ Split comma separated string into unique values, keeping their order. :returns: list of splitted values """ seen = set() values = val if isinstance(val, (list, tuple)) else val.strip().split(',') return [x for x in values if x and not (x in seen or seen.add(x))]
python
def split_csp_str(val): """ Split comma separated string into unique values, keeping their order. :returns: list of splitted values """ seen = set() values = val if isinstance(val, (list, tuple)) else val.strip().split(',') return [x for x in values if x and not (x in seen or seen.add(x))]
[ "def", "split_csp_str", "(", "val", ")", ":", "seen", "=", "set", "(", ")", "values", "=", "val", "if", "isinstance", "(", "val", ",", "(", "list", ",", "tuple", ")", ")", "else", "val", ".", "strip", "(", ")", ".", "split", "(", "','", ")", "r...
Split comma separated string into unique values, keeping their order. :returns: list of splitted values
[ "Split", "comma", "separated", "string", "into", "unique", "values", "keeping", "their", "order", "." ]
f436ccc6b55b33381a295ded753e467953cf4379
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/config.py#L47-L54
train
206,185
klen/pylama
pylama/config.py
parse_linters
def parse_linters(linters): """ Initialize choosen linters. :returns: list of inited linters """ result = list() for name in split_csp_str(linters): linter = LINTERS.get(name) if linter: result.append((name, linter)) else: logging.warning("Linter `%s` not found.", name) return result
python
def parse_linters(linters): """ Initialize choosen linters. :returns: list of inited linters """ result = list() for name in split_csp_str(linters): linter = LINTERS.get(name) if linter: result.append((name, linter)) else: logging.warning("Linter `%s` not found.", name) return result
[ "def", "parse_linters", "(", "linters", ")", ":", "result", "=", "list", "(", ")", "for", "name", "in", "split_csp_str", "(", "linters", ")", ":", "linter", "=", "LINTERS", ".", "get", "(", "name", ")", "if", "linter", ":", "result", ".", "append", "...
Initialize choosen linters. :returns: list of inited linters
[ "Initialize", "choosen", "linters", "." ]
f436ccc6b55b33381a295ded753e467953cf4379
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/config.py#L57-L70
train
206,186
klen/pylama
pylama/config.py
get_default_config_file
def get_default_config_file(rootdir=None): """Search for configuration file.""" if rootdir is None: return DEFAULT_CONFIG_FILE for path in CONFIG_FILES: path = os.path.join(rootdir, path) if os.path.isfile(path) and os.access(path, os.R_OK): return path
python
def get_default_config_file(rootdir=None): """Search for configuration file.""" if rootdir is None: return DEFAULT_CONFIG_FILE for path in CONFIG_FILES: path = os.path.join(rootdir, path) if os.path.isfile(path) and os.access(path, os.R_OK): return path
[ "def", "get_default_config_file", "(", "rootdir", "=", "None", ")", ":", "if", "rootdir", "is", "None", ":", "return", "DEFAULT_CONFIG_FILE", "for", "path", "in", "CONFIG_FILES", ":", "path", "=", "os", ".", "path", ".", "join", "(", "rootdir", ",", "path"...
Search for configuration file.
[ "Search", "for", "configuration", "file", "." ]
f436ccc6b55b33381a295ded753e467953cf4379
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/config.py#L73-L81
train
206,187
klen/pylama
pylama/config.py
parse_options
def parse_options(args=None, config=True, rootdir=CURDIR, **overrides): # noqa """ Parse options from command line and configuration files. :return argparse.Namespace: """ args = args or [] # Parse args from command string options = PARSER.parse_args(args) options.file_params = dict() options.linters_params = dict() # Compile options from ini if config: cfg = get_config(str(options.options), rootdir=rootdir) for opt, val in cfg.default.items(): LOGGER.info('Find option %s (%s)', opt, val) passed_value = getattr(options, opt, _Default()) if isinstance(passed_value, _Default): if opt == 'paths': val = val.split() if opt == 'skip': val = fix_pathname_sep(val) setattr(options, opt, _Default(val)) # Parse file related options for name, opts in cfg.sections.items(): if name == cfg.default_section: continue if name.startswith('pylama'): name = name[7:] if name in LINTERS: options.linters_params[name] = dict(opts) continue mask = re.compile(fnmatch.translate(fix_pathname_sep(name))) options.file_params[mask] = dict(opts) # Override options _override_options(options, **overrides) # Postprocess options for name in options.__dict__: value = getattr(options, name) if isinstance(value, _Default): setattr(options, name, process_value(name, value.value)) if options.concurrent and 'pylint' in options.linters: LOGGER.warning('Can\'t parse code asynchronously with pylint enabled.') options.concurrent = False return options
python
def parse_options(args=None, config=True, rootdir=CURDIR, **overrides): # noqa """ Parse options from command line and configuration files. :return argparse.Namespace: """ args = args or [] # Parse args from command string options = PARSER.parse_args(args) options.file_params = dict() options.linters_params = dict() # Compile options from ini if config: cfg = get_config(str(options.options), rootdir=rootdir) for opt, val in cfg.default.items(): LOGGER.info('Find option %s (%s)', opt, val) passed_value = getattr(options, opt, _Default()) if isinstance(passed_value, _Default): if opt == 'paths': val = val.split() if opt == 'skip': val = fix_pathname_sep(val) setattr(options, opt, _Default(val)) # Parse file related options for name, opts in cfg.sections.items(): if name == cfg.default_section: continue if name.startswith('pylama'): name = name[7:] if name in LINTERS: options.linters_params[name] = dict(opts) continue mask = re.compile(fnmatch.translate(fix_pathname_sep(name))) options.file_params[mask] = dict(opts) # Override options _override_options(options, **overrides) # Postprocess options for name in options.__dict__: value = getattr(options, name) if isinstance(value, _Default): setattr(options, name, process_value(name, value.value)) if options.concurrent and 'pylint' in options.linters: LOGGER.warning('Can\'t parse code asynchronously with pylint enabled.') options.concurrent = False return options
[ "def", "parse_options", "(", "args", "=", "None", ",", "config", "=", "True", ",", "rootdir", "=", "CURDIR", ",", "*", "*", "overrides", ")", ":", "# noqa", "args", "=", "args", "or", "[", "]", "# Parse args from command string", "options", "=", "PARSER", ...
Parse options from command line and configuration files. :return argparse.Namespace:
[ "Parse", "options", "from", "command", "line", "and", "configuration", "files", "." ]
f436ccc6b55b33381a295ded753e467953cf4379
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/config.py#L157-L212
train
206,188
klen/pylama
pylama/config.py
_override_options
def _override_options(options, **overrides): """Override options.""" for opt, val in overrides.items(): passed_value = getattr(options, opt, _Default()) if opt in ('ignore', 'select') and passed_value: value = process_value(opt, passed_value.value) value += process_value(opt, val) setattr(options, opt, value) elif isinstance(passed_value, _Default): setattr(options, opt, process_value(opt, val))
python
def _override_options(options, **overrides): """Override options.""" for opt, val in overrides.items(): passed_value = getattr(options, opt, _Default()) if opt in ('ignore', 'select') and passed_value: value = process_value(opt, passed_value.value) value += process_value(opt, val) setattr(options, opt, value) elif isinstance(passed_value, _Default): setattr(options, opt, process_value(opt, val))
[ "def", "_override_options", "(", "options", ",", "*", "*", "overrides", ")", ":", "for", "opt", ",", "val", "in", "overrides", ".", "items", "(", ")", ":", "passed_value", "=", "getattr", "(", "options", ",", "opt", ",", "_Default", "(", ")", ")", "i...
Override options.
[ "Override", "options", "." ]
f436ccc6b55b33381a295ded753e467953cf4379
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/config.py#L215-L224
train
206,189
klen/pylama
pylama/config.py
process_value
def process_value(name, value): """ Compile option value. """ action = ACTIONS.get(name) if not action: return value if callable(action.type): return action.type(value) if action.const: return bool(int(value)) return value
python
def process_value(name, value): """ Compile option value. """ action = ACTIONS.get(name) if not action: return value if callable(action.type): return action.type(value) if action.const: return bool(int(value)) return value
[ "def", "process_value", "(", "name", ",", "value", ")", ":", "action", "=", "ACTIONS", ".", "get", "(", "name", ")", "if", "not", "action", ":", "return", "value", "if", "callable", "(", "action", ".", "type", ")", ":", "return", "action", ".", "type...
Compile option value.
[ "Compile", "option", "value", "." ]
f436ccc6b55b33381a295ded753e467953cf4379
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/config.py#L227-L239
train
206,190
klen/pylama
pylama/config.py
get_config
def get_config(ini_path=None, rootdir=None): """ Load configuration from INI. :return Namespace: """ config = Namespace() config.default_section = 'pylama' if not ini_path: path = get_default_config_file(rootdir) if path: config.read(path) else: config.read(ini_path) return config
python
def get_config(ini_path=None, rootdir=None): """ Load configuration from INI. :return Namespace: """ config = Namespace() config.default_section = 'pylama' if not ini_path: path = get_default_config_file(rootdir) if path: config.read(path) else: config.read(ini_path) return config
[ "def", "get_config", "(", "ini_path", "=", "None", ",", "rootdir", "=", "None", ")", ":", "config", "=", "Namespace", "(", ")", "config", ".", "default_section", "=", "'pylama'", "if", "not", "ini_path", ":", "path", "=", "get_default_config_file", "(", "r...
Load configuration from INI. :return Namespace:
[ "Load", "configuration", "from", "INI", "." ]
f436ccc6b55b33381a295ded753e467953cf4379
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/config.py#L242-L258
train
206,191
klen/pylama
pylama/config.py
setup_logger
def setup_logger(options): """Do the logger setup with options.""" LOGGER.setLevel(logging.INFO if options.verbose else logging.WARN) if options.report: LOGGER.removeHandler(STREAM) LOGGER.addHandler(logging.FileHandler(options.report, mode='w')) if options.options: LOGGER.info('Try to read configuration from: %r', options.options)
python
def setup_logger(options): """Do the logger setup with options.""" LOGGER.setLevel(logging.INFO if options.verbose else logging.WARN) if options.report: LOGGER.removeHandler(STREAM) LOGGER.addHandler(logging.FileHandler(options.report, mode='w')) if options.options: LOGGER.info('Try to read configuration from: %r', options.options)
[ "def", "setup_logger", "(", "options", ")", ":", "LOGGER", ".", "setLevel", "(", "logging", ".", "INFO", "if", "options", ".", "verbose", "else", "logging", ".", "WARN", ")", "if", "options", ".", "report", ":", "LOGGER", ".", "removeHandler", "(", "STRE...
Do the logger setup with options.
[ "Do", "the", "logger", "setup", "with", "options", "." ]
f436ccc6b55b33381a295ded753e467953cf4379
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/config.py#L261-L269
train
206,192
klen/pylama
pylama/lint/pylama_pyflakes.py
Linter.run
def run(path, code=None, params=None, **meta): """Check code with pyflakes. :return list: List of errors. """ import _ast builtins = params.get("builtins", "") if builtins: builtins = builtins.split(",") tree = compile(code, path, "exec", _ast.PyCF_ONLY_AST) w = checker.Checker(tree, path, builtins=builtins) w.messages = sorted(w.messages, key=lambda m: m.lineno) return [{ 'lnum': m.lineno, 'text': m.message % m.message_args, 'type': m.message[0] } for m in w.messages]
python
def run(path, code=None, params=None, **meta): """Check code with pyflakes. :return list: List of errors. """ import _ast builtins = params.get("builtins", "") if builtins: builtins = builtins.split(",") tree = compile(code, path, "exec", _ast.PyCF_ONLY_AST) w = checker.Checker(tree, path, builtins=builtins) w.messages = sorted(w.messages, key=lambda m: m.lineno) return [{ 'lnum': m.lineno, 'text': m.message % m.message_args, 'type': m.message[0] } for m in w.messages]
[ "def", "run", "(", "path", ",", "code", "=", "None", ",", "params", "=", "None", ",", "*", "*", "meta", ")", ":", "import", "_ast", "builtins", "=", "params", ".", "get", "(", "\"builtins\"", ",", "\"\"", ")", "if", "builtins", ":", "builtins", "="...
Check code with pyflakes. :return list: List of errors.
[ "Check", "code", "with", "pyflakes", "." ]
f436ccc6b55b33381a295ded753e467953cf4379
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/lint/pylama_pyflakes.py#L30-L49
train
206,193
klen/pylama
pylama/main.py
check_path
def check_path(options, rootdir=None, candidates=None, code=None): """Check path. :param rootdir: Root directory (for making relative file paths) :param options: Parsed pylama options (from pylama.config.parse_options) :returns: (list) Errors list """ if not candidates: candidates = [] for path_ in options.paths: path = op.abspath(path_) if op.isdir(path): for root, _, files in walk(path): candidates += [op.relpath(op.join(root, f), CURDIR) for f in files] else: candidates.append(path) if rootdir is None: rootdir = path if op.isdir(path) else op.dirname(path) paths = [] for path in candidates: if not options.force and not any(l.allow(path) for _, l in options.linters): continue if not op.exists(path): continue paths.append(path) if options.concurrent: return check_async(paths, options, rootdir) errors = [] for path in paths: errors += run(path=path, code=code, rootdir=rootdir, options=options) return errors
python
def check_path(options, rootdir=None, candidates=None, code=None): """Check path. :param rootdir: Root directory (for making relative file paths) :param options: Parsed pylama options (from pylama.config.parse_options) :returns: (list) Errors list """ if not candidates: candidates = [] for path_ in options.paths: path = op.abspath(path_) if op.isdir(path): for root, _, files in walk(path): candidates += [op.relpath(op.join(root, f), CURDIR) for f in files] else: candidates.append(path) if rootdir is None: rootdir = path if op.isdir(path) else op.dirname(path) paths = [] for path in candidates: if not options.force and not any(l.allow(path) for _, l in options.linters): continue if not op.exists(path): continue paths.append(path) if options.concurrent: return check_async(paths, options, rootdir) errors = [] for path in paths: errors += run(path=path, code=code, rootdir=rootdir, options=options) return errors
[ "def", "check_path", "(", "options", ",", "rootdir", "=", "None", ",", "candidates", "=", "None", ",", "code", "=", "None", ")", ":", "if", "not", "candidates", ":", "candidates", "=", "[", "]", "for", "path_", "in", "options", ".", "paths", ":", "pa...
Check path. :param rootdir: Root directory (for making relative file paths) :param options: Parsed pylama options (from pylama.config.parse_options) :returns: (list) Errors list
[ "Check", "path", "." ]
f436ccc6b55b33381a295ded753e467953cf4379
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/main.py#L13-L54
train
206,194
klen/pylama
pylama/main.py
shell
def shell(args=None, error=True): """Endpoint for console. Parse a command arguments, configuration files and run a checkers. :return list: list of errors :raise SystemExit: """ if args is None: args = sys.argv[1:] options = parse_options(args) setup_logger(options) LOGGER.info(options) # Install VSC hook if options.hook: from .hook import install_hook for path in options.paths: return install_hook(path) return process_paths(options, error=error)
python
def shell(args=None, error=True): """Endpoint for console. Parse a command arguments, configuration files and run a checkers. :return list: list of errors :raise SystemExit: """ if args is None: args = sys.argv[1:] options = parse_options(args) setup_logger(options) LOGGER.info(options) # Install VSC hook if options.hook: from .hook import install_hook for path in options.paths: return install_hook(path) return process_paths(options, error=error)
[ "def", "shell", "(", "args", "=", "None", ",", "error", "=", "True", ")", ":", "if", "args", "is", "None", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "options", "=", "parse_options", "(", "args", ")", "setup_logger", "(", "options", ...
Endpoint for console. Parse a command arguments, configuration files and run a checkers. :return list: list of errors :raise SystemExit:
[ "Endpoint", "for", "console", "." ]
f436ccc6b55b33381a295ded753e467953cf4379
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/main.py#L57-L79
train
206,195
klen/pylama
pylama/main.py
process_paths
def process_paths(options, candidates=None, error=True): """Process files and log errors.""" errors = check_path(options, rootdir=CURDIR, candidates=candidates) if options.format in ['pycodestyle', 'pep8']: pattern = "%(filename)s:%(lnum)s:%(col)s: %(text)s" elif options.format == 'pylint': pattern = "%(filename)s:%(lnum)s: [%(type)s] %(text)s" else: # 'parsable' pattern = "%(filename)s:%(lnum)s:%(col)s: [%(type)s] %(text)s" for er in errors: if options.abspath: er._info['filename'] = op.abspath(er.filename) LOGGER.warning(pattern, er._info) if error: sys.exit(int(bool(errors))) return errors
python
def process_paths(options, candidates=None, error=True): """Process files and log errors.""" errors = check_path(options, rootdir=CURDIR, candidates=candidates) if options.format in ['pycodestyle', 'pep8']: pattern = "%(filename)s:%(lnum)s:%(col)s: %(text)s" elif options.format == 'pylint': pattern = "%(filename)s:%(lnum)s: [%(type)s] %(text)s" else: # 'parsable' pattern = "%(filename)s:%(lnum)s:%(col)s: [%(type)s] %(text)s" for er in errors: if options.abspath: er._info['filename'] = op.abspath(er.filename) LOGGER.warning(pattern, er._info) if error: sys.exit(int(bool(errors))) return errors
[ "def", "process_paths", "(", "options", ",", "candidates", "=", "None", ",", "error", "=", "True", ")", ":", "errors", "=", "check_path", "(", "options", ",", "rootdir", "=", "CURDIR", ",", "candidates", "=", "candidates", ")", "if", "options", ".", "for...
Process files and log errors.
[ "Process", "files", "and", "log", "errors", "." ]
f436ccc6b55b33381a295ded753e467953cf4379
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/main.py#L82-L101
train
206,196
klen/pylama
pylama/libs/inirama.py
Scanner.reset
def reset(self, source): """ Reset scanner's state. :param source: Source for parsing """ self.tokens = [] self.source = source self.pos = 0
python
def reset(self, source): """ Reset scanner's state. :param source: Source for parsing """ self.tokens = [] self.source = source self.pos = 0
[ "def", "reset", "(", "self", ",", "source", ")", ":", "self", ".", "tokens", "=", "[", "]", "self", ".", "source", "=", "source", "self", ".", "pos", "=", "0" ]
Reset scanner's state. :param source: Source for parsing
[ "Reset", "scanner", "s", "state", "." ]
f436ccc6b55b33381a295ded753e467953cf4379
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/libs/inirama.py#L99-L107
train
206,197
klen/pylama
pylama/libs/inirama.py
Scanner.scan
def scan(self): """ Scan source and grab tokens. """ self.pre_scan() token = None end = len(self.source) while self.pos < end: best_pat = None best_pat_len = 0 # Check patterns for p, regexp in self.patterns: m = regexp.match(self.source, self.pos) if m: best_pat = p best_pat_len = len(m.group(0)) break if best_pat is None: raise SyntaxError( "SyntaxError[@char {0}: {1}]".format( self.pos, "Bad token.")) # Ignore patterns if best_pat in self.ignore: self.pos += best_pat_len continue # Create token token = ( best_pat, self.source[self.pos:self.pos + best_pat_len], self.pos, self.pos + best_pat_len, ) self.pos = token[-1] self.tokens.append(token)
python
def scan(self): """ Scan source and grab tokens. """ self.pre_scan() token = None end = len(self.source) while self.pos < end: best_pat = None best_pat_len = 0 # Check patterns for p, regexp in self.patterns: m = regexp.match(self.source, self.pos) if m: best_pat = p best_pat_len = len(m.group(0)) break if best_pat is None: raise SyntaxError( "SyntaxError[@char {0}: {1}]".format( self.pos, "Bad token.")) # Ignore patterns if best_pat in self.ignore: self.pos += best_pat_len continue # Create token token = ( best_pat, self.source[self.pos:self.pos + best_pat_len], self.pos, self.pos + best_pat_len, ) self.pos = token[-1] self.tokens.append(token)
[ "def", "scan", "(", "self", ")", ":", "self", ".", "pre_scan", "(", ")", "token", "=", "None", "end", "=", "len", "(", "self", ".", "source", ")", "while", "self", ".", "pos", "<", "end", ":", "best_pat", "=", "None", "best_pat_len", "=", "0", "#...
Scan source and grab tokens.
[ "Scan", "source", "and", "grab", "tokens", "." ]
f436ccc6b55b33381a295ded753e467953cf4379
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/libs/inirama.py#L109-L149
train
206,198
klen/pylama
pylama/libs/inirama.py
INIScanner.pre_scan
def pre_scan(self): """ Prepare string for scanning. """ escape_re = re.compile(r'\\\n[\t ]+') self.source = escape_re.sub('', self.source)
python
def pre_scan(self): """ Prepare string for scanning. """ escape_re = re.compile(r'\\\n[\t ]+') self.source = escape_re.sub('', self.source)
[ "def", "pre_scan", "(", "self", ")", ":", "escape_re", "=", "re", ".", "compile", "(", "r'\\\\\\n[\\t ]+'", ")", "self", ".", "source", "=", "escape_re", ".", "sub", "(", "''", ",", "self", ".", "source", ")" ]
Prepare string for scanning.
[ "Prepare", "string", "for", "scanning", "." ]
f436ccc6b55b33381a295ded753e467953cf4379
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/libs/inirama.py#L179-L182
train
206,199