repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
drslump/pyshould
pyshould/dsl.py
any_of
python
def any_of(value, *args): if len(args): value = (value,) + args return ExpectationAny(value)
At least one of the items in value should match
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/dsl.py#L33-L39
null
""" Define the names making up the domain specific language """ from pyshould.expectation import ( Expectation, ExpectationNot, ExpectationAll, ExpectationAny, ExpectationNone, OPERATOR ) from pyshould.dumper import Dumper __author__ = "Ivan -DrSlump- Montes" __email__ = "drslump@pollinimini.net" __licens...
drslump/pyshould
pyshould/dsl.py
all_of
python
def all_of(value, *args): if len(args): value = (value,) + args return ExpectationAll(value)
All the items in value should match
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/dsl.py#L42-L48
null
""" Define the names making up the domain specific language """ from pyshould.expectation import ( Expectation, ExpectationNot, ExpectationAll, ExpectationAny, ExpectationNone, OPERATOR ) from pyshould.dumper import Dumper __author__ = "Ivan -DrSlump- Montes" __email__ = "drslump@pollinimini.net" __licens...
drslump/pyshould
pyshould/dsl.py
none_of
python
def none_of(value, *args): if len(args): value = (value,) + args return ExpectationNone(value)
None of the items in value should match
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/dsl.py#L51-L57
null
""" Define the names making up the domain specific language """ from pyshould.expectation import ( Expectation, ExpectationNot, ExpectationAll, ExpectationAny, ExpectationNone, OPERATOR ) from pyshould.dumper import Dumper __author__ = "Ivan -DrSlump- Montes" __email__ = "drslump@pollinimini.net" __licens...
rmohr/static3
static.py
iter_and_close
python
def iter_and_close(file_like, block_size): while 1: try: block = file_like.read(block_size) if block: yield block else: raise StopIteration except StopIteration: file_like.close() return
Yield file contents by block then close the file.
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L239-L250
null
#!/usr/bin/env python """ Copyright (C) 2012 Roman Mohr <roman@fenkhuber.at> """ """static - A stupidly simple WSGI way to serve static (or mixed) content. (See the docstrings of the various functions and classes.) Copyright (C) 2006-2009 Luke Arno - http://lukearno.com/ This library is free software; you can redis...
rmohr/static3
static.py
cling_wrap
python
def cling_wrap(package_name, dir_name, **kw): resource = Requirement.parse(package_name) return Cling(resource_filename(resource, dir_name), **kw)
Return a Cling that serves from the given package and dir_name. This uses pkg_resources.resource_filename which is not the recommended way, since it extracts the files. I think this works fine unless you have some _very_ serious requirements for static content, in which case you probably shouldn't...
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L253-L264
null
#!/usr/bin/env python """ Copyright (C) 2012 Roman Mohr <roman@fenkhuber.at> """ """static - A stupidly simple WSGI way to serve static (or mixed) content. (See the docstrings of the various functions and classes.) Copyright (C) 2006-2009 Luke Arno - http://lukearno.com/ This library is free software; you can redis...
rmohr/static3
static.py
Cling._is_under_root
python
def _is_under_root(self, full_path): if (path.abspath(full_path) + path.sep)\ .startswith(path.abspath(self.root) + path.sep): return True else: return False
Guard against arbitrary file retrieval.
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L200-L206
null
class Cling(object): """A stupidly simple way to serve static content via WSGI. Serve the file of the same path as PATH_INFO in self.datadir. Look up the Content-type in self.content_types by extension or use 'text/plain' if the extension is not found. Serve up the contents of the file or delega...
rmohr/static3
static.py
Cling._conditions
python
def _conditions(self, full_path, environ): mtime = stat(full_path).st_mtime return str(mtime), rfc822.formatdate(mtime)
Return a tuple of etag, last_modified by mtime from stat.
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L212-L215
null
class Cling(object): """A stupidly simple way to serve static content via WSGI. Serve the file of the same path as PATH_INFO in self.datadir. Look up the Content-type in self.content_types by extension or use 'text/plain' if the extension is not found. Serve up the contents of the file or delega...
rmohr/static3
static.py
Cling._body
python
def _body(self, full_path, environ, file_like): way_to_send = environ.get('wsgi.file_wrapper', iter_and_close) return way_to_send(file_like, self.block_size)
Return an iterator over the body of the response.
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L233-L236
null
class Cling(object): """A stupidly simple way to serve static content via WSGI. Serve the file of the same path as PATH_INFO in self.datadir. Look up the Content-type in self.content_types by extension or use 'text/plain' if the extension is not found. Serve up the contents of the file or delega...
rmohr/static3
static.py
Shock._match_magic
python
def _match_magic(self, full_path): for magic in self.magics: if magic.matches(full_path): return magic
Return the first magic that matches this path or None.
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L296-L300
null
class Shock(Cling): """A stupidly simple way to serve up mixed content. Serves static content just like Cling (it's superclass) except that it process content with the first matching magic from self.magics if any apply. See Cling and classes with "Magic" in their names in this module. If you...
rmohr/static3
static.py
Shock._full_path
python
def _full_path(self, path_info): full_path = self.root + path_info if path.exists(full_path): return full_path else: for magic in self.magics: if path.exists(magic.new_path(full_path)): return magic.new_path(full_path) else:...
Return the full path from which to read.
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L302-L312
null
class Shock(Cling): """A stupidly simple way to serve up mixed content. Serves static content just like Cling (it's superclass) except that it process content with the first matching magic from self.magics if any apply. See Cling and classes with "Magic" in their names in this module. If you...
rmohr/static3
static.py
Shock._guess_type
python
def _guess_type(self, full_path): magic = self._match_magic(full_path) if magic is not None: return (mimetypes.guess_type(magic.old_path(full_path))[0] or 'text/plain') else: return mimetypes.guess_type(full_path)[0] or 'text/plain'
Guess the mime type magically or using the mimetypes module.
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L314-L321
null
class Shock(Cling): """A stupidly simple way to serve up mixed content. Serves static content just like Cling (it's superclass) except that it process content with the first matching magic from self.magics if any apply. See Cling and classes with "Magic" in their names in this module. If you...
rmohr/static3
static.py
Shock._conditions
python
def _conditions(self, full_path, environ): magic = self._match_magic(full_path) if magic is not None: return magic.conditions(full_path, environ) else: mtime = stat(full_path).st_mtime return str(mtime), rfc822.formatdate(mtime)
Return Etag and Last-Modified values defaults to now for both.
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L323-L330
null
class Shock(Cling): """A stupidly simple way to serve up mixed content. Serves static content just like Cling (it's superclass) except that it process content with the first matching magic from self.magics if any apply. See Cling and classes with "Magic" in their names in this module. If you...
rmohr/static3
static.py
Shock._file_like
python
def _file_like(self, full_path): magic = self._match_magic(full_path) if magic is not None: return magic.file_like(full_path, self.encoding) else: return open(full_path, 'rb')
Return the appropriate file object.
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L332-L338
null
class Shock(Cling): """A stupidly simple way to serve up mixed content. Serves static content just like Cling (it's superclass) except that it process content with the first matching magic from self.magics if any apply. See Cling and classes with "Magic" in their names in this module. If you...
rmohr/static3
static.py
Shock._body
python
def _body(self, full_path, environ, file_like): magic = self._match_magic(full_path) if magic is not None: return [_encode(s, self.encoding) for s in magic.body(environ, file_like)] else: way_to_send = envi...
Return an iterator over the body of the response.
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L340-L348
null
class Shock(Cling): """A stupidly simple way to serve up mixed content. Serves static content just like Cling (it's superclass) except that it process content with the first matching magic from self.magics if any apply. See Cling and classes with "Magic" in their names in this module. If you...
rmohr/static3
static.py
BaseMagic.exists
python
def exists(self, full_path): if path.exists(self.new_path(full_path)): return self.new_path(full_path)
Check that self.new_path(full_path) exists.
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L365-L368
[ "def new_path(self, full_path):\n \"\"\"Add the self.extension to the path.\"\"\"\n return full_path + self.extension\n" ]
class BaseMagic(object): """Base class for magic file handling. Really a do nothing if you were to use this directly. In a strait forward case you would just override .extension and body(). (See StringMagic in this module for a simple example of subclassing.) In a more complex case you may need ...
rmohr/static3
static.py
BaseMagic.old_path
python
def old_path(self, full_path): if self.matches(full_path): return full_path[:-len(self.extension)] else: raise MagicError("Path does not match this magic.")
Remove self.extension from path or raise MagicError.
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L374-L379
[ "def matches(self, full_path):\n \"\"\"Check that path ends with self.extension.\"\"\"\n if full_path.endswith(self.extension):\n return full_path\n" ]
class BaseMagic(object): """Base class for magic file handling. Really a do nothing if you were to use this directly. In a strait forward case you would just override .extension and body(). (See StringMagic in this module for a simple example of subclassing.) In a more complex case you may need ...
rmohr/static3
static.py
BaseMagic.conditions
python
def conditions(self, full_path, environ): mtime = int(time.time()) return str(mtime), rfc822.formatdate(mtime)
Return Etag and Last-Modified values (based on mtime).
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L386-L389
null
class BaseMagic(object): """Base class for magic file handling. Really a do nothing if you were to use this directly. In a strait forward case you would just override .extension and body(). (See StringMagic in this module for a simple example of subclassing.) In a more complex case you may need ...
rmohr/static3
static.py
StringMagic.body
python
def body(self, environ, file_like): variables = environ.copy() variables.update(self.variables) template = string.Template(file_like.read()) if self.safe is True: return [template.safe_substitute(variables)] else: return [template.substitute(variables)]
Pass environ and self.variables in to template. self.variables overrides environ so that suprises in environ don't cause unexpected output if you are passing a value in explicitly.
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L414-L426
null
class StringMagic(BaseMagic): """Magic to replace variables in file contents using string.Template. Using this requires Python2.4. """ extension = '.stp' safe = False def __init__(self, **variables): """Keyword arguments populate self.variables.""" self.variables = variables ...
rmohr/static3
static.py
KidMagic.body
python
def body(self, environ, full_path): template = kid.Template(file=full_path, environ=environ, **self.variables) return [template.serialize()]
Pass environ and **self.variables into the template.
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L438-L443
null
class KidMagic(StringMagic): """Like StringMagic only using the Kid templating language. Using this requires Kid: http://kid.lesscode.org/ """ extension = '.kid'
rmohr/static3
static.py
GenshiMagic.body
python
def body(self, environ, full_path): template = MarkupTemplate(full_path.read()) variables = self.variables.copy() variables["environ"] = environ return [template.generate(**variables) .render('html', doctype='html')]
Pass environ and **self.variables into the template.
train
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L455-L462
null
class GenshiMagic(StringMagic): """Like StringMagic only using the Genshi templating language. Using this requires Genshi """ extension = '.genshi'
ifduyue/urlfetch
urlfetch.py
fetch
python
def fetch(*args, **kwargs): data = kwargs.get('data', None) files = kwargs.get('files', {}) if data and isinstance(data, (basestring, dict)) or files: return post(*args, **kwargs) return get(*args, **kwargs)
fetch an URL. :func:`~urlfetch.fetch` is a wrapper of :func:`~urlfetch.request`. It calls :func:`~urlfetch.get` by default. If one of parameter ``data`` or parameter ``files`` is supplied, :func:`~urlfetch.post` is called.
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L528-L540
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ urlfetch ~~~~~~~~~~ An easy to use HTTP client based on httplib. :copyright: (c) 2011-2019 by Yue Du. :license: BSD 2-clause License, see LICENSE for more details. """ __version__ = '1.1.2' __author__ = 'Yue Du <ifduyue@gmail.com>' __url__ = 'https://github.com/ifduy...
ifduyue/urlfetch
urlfetch.py
request
python
def request(url, method="GET", params=None, data=None, headers={}, timeout=None, files={}, randua=False, auth=None, length_limit=None, proxies=None, trust_env=True, max_redirects=0, source_address=None, **kwargs): def make_connection(conn_type, host, port, timeout, source_address...
request an URL :arg string url: URL to be fetched. :arg string method: (optional) HTTP method, one of ``GET``, ``DELETE``, ``HEAD``, ``OPTIONS``, ``PUT``, ``POST``, ``TRACE``, ``PATCH``. ``GET`` is the default. :arg dict/string params: (optional) Dict or stri...
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L558-L763
[ "def parse_url(url):\n \"\"\"Return a dictionary of parsed url\n\n Including scheme, netloc, path, params, query, fragment, uri, username,\n password, host, port and http_host\n \"\"\"\n try:\n url = unicode(url)\n except UnicodeDecodeError:\n pass\n\n if py3k:\n make_utf8 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ urlfetch ~~~~~~~~~~ An easy to use HTTP client based on httplib. :copyright: (c) 2011-2019 by Yue Du. :license: BSD 2-clause License, see LICENSE for more details. """ __version__ = '1.1.2' __author__ = 'Yue Du <ifduyue@gmail.com>' __url__ = 'https://github.com/ifduy...
ifduyue/urlfetch
urlfetch.py
parse_url
python
def parse_url(url): try: url = unicode(url) except UnicodeDecodeError: pass if py3k: make_utf8 = lambda x: x else: make_utf8 = lambda x: isinstance(x, unicode) and x.encode('utf-8') or x if '://' in url: scheme, url = url.split('://', 1) else: sc...
Return a dictionary of parsed url Including scheme, netloc, path, params, query, fragment, uri, username, password, host, port and http_host
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L801-L845
[ "make_utf8 = lambda x: x\n" ]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ urlfetch ~~~~~~~~~~ An easy to use HTTP client based on httplib. :copyright: (c) 2011-2019 by Yue Du. :license: BSD 2-clause License, see LICENSE for more details. """ __version__ = '1.1.2' __author__ = 'Yue Du <ifduyue@gmail.com>' __url__ = 'https://github.com/ifduy...
ifduyue/urlfetch
urlfetch.py
get_proxies_from_environ
python
def get_proxies_from_environ(): proxies = {} http_proxy = os.getenv('http_proxy') or os.getenv('HTTP_PROXY') https_proxy = os.getenv('https_proxy') or os.getenv('HTTPS_PROXY') if http_proxy: proxies['http'] = http_proxy if https_proxy: proxies['https'] = https_proxy return proxie...
Get proxies from os.environ.
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L848-L857
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ urlfetch ~~~~~~~~~~ An easy to use HTTP client based on httplib. :copyright: (c) 2011-2019 by Yue Du. :license: BSD 2-clause License, see LICENSE for more details. """ __version__ = '1.1.2' __author__ = 'Yue Du <ifduyue@gmail.com>' __url__ = 'https://github.com/ifduy...
ifduyue/urlfetch
urlfetch.py
mb_code
python
def mb_code(s, coding=None, errors='replace'): if isinstance(s, unicode): return s if coding is None else s.encode(coding, errors=errors) for c in ('utf-8', 'gb2312', 'gbk', 'gb18030', 'big5'): try: s = s.decode(c) return s if coding is None else s.encode(coding, errors=e...
encoding/decoding helper.
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L860-L870
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ urlfetch ~~~~~~~~~~ An easy to use HTTP client based on httplib. :copyright: (c) 2011-2019 by Yue Du. :license: BSD 2-clause License, see LICENSE for more details. """ __version__ = '1.1.2' __author__ = 'Yue Du <ifduyue@gmail.com>' __url__ = 'https://github.com/ifduy...
ifduyue/urlfetch
urlfetch.py
random_useragent
python
def random_useragent(filename=True): import random default_ua = 'urlfetch/%s' % __version__ if isinstance(filename, basestring): filenames = [filename] else: filenames = [] if filename and UAFILE: filenames.append(UAFILE) for filename in filenames: try: ...
Returns a User-Agent string randomly from file. :arg string filename: (Optional) Path to the file from which a random useragent is generated. By default it's ``True``, a file shipped with this module will be used. :returns: An user-agent string.
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L873-L929
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ urlfetch ~~~~~~~~~~ An easy to use HTTP client based on httplib. :copyright: (c) 2011-2019 by Yue Du. :license: BSD 2-clause License, see LICENSE for more details. """ __version__ = '1.1.2' __author__ = 'Yue Du <ifduyue@gmail.com>' __url__ = 'https://github.com/ifduy...
ifduyue/urlfetch
urlfetch.py
url_concat
python
def url_concat(url, args, keep_existing=True): if not args: return url if keep_existing: if url[-1] not in ('?', '&'): url += '&' if ('?' in url) else '?' return url + urlencode(args, 1) else: url, seq, query = url.partition('?') query = urlparse.parse_qs...
Concatenate url and argument dictionary >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' :arg string url: URL being concat to. :arg dict args: Args being concat. :arg bool keep_existing: (Optional) Whether to keep the args which are ...
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L932-L954
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ urlfetch ~~~~~~~~~~ An easy to use HTTP client based on httplib. :copyright: (c) 2011-2019 by Yue Du. :license: BSD 2-clause License, see LICENSE for more details. """ __version__ = '1.1.2' __author__ = 'Yue Du <ifduyue@gmail.com>' __url__ = 'https://github.com/ifduy...
ifduyue/urlfetch
urlfetch.py
choose_boundary
python
def choose_boundary(): global BOUNDARY_PREFIX if BOUNDARY_PREFIX is None: BOUNDARY_PREFIX = "urlfetch" try: uid = repr(os.getuid()) BOUNDARY_PREFIX += "." + uid except AttributeError: pass try: pid = repr(os.getpid()) BO...
Generate a multipart boundry. :returns: A boundary string
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L957-L976
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ urlfetch ~~~~~~~~~~ An easy to use HTTP client based on httplib. :copyright: (c) 2011-2019 by Yue Du. :license: BSD 2-clause License, see LICENSE for more details. """ __version__ = '1.1.2' __author__ = 'Yue Du <ifduyue@gmail.com>' __url__ = 'https://github.com/ifduy...
ifduyue/urlfetch
urlfetch.py
encode_multipart
python
def encode_multipart(data, files): body = BytesIO() boundary = choose_boundary() part_boundary = b('--%s\r\n' % boundary) writer = codecs.lookup('utf-8')[3] if isinstance(data, dict): for name, values in data.items(): if not isinstance(values, (list, tuple, set)): ...
Encode multipart. :arg dict data: Data to be encoded :arg dict files: Files to be encoded :returns: Encoded binary string :raises: :class:`UrlfetchException`
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L979-L1046
[ "b = lambda s: s.encode('latin-1')\n", "def choose_boundary():\n \"\"\"Generate a multipart boundry.\n\n :returns: A boundary string\n \"\"\"\n global BOUNDARY_PREFIX\n if BOUNDARY_PREFIX is None:\n BOUNDARY_PREFIX = \"urlfetch\"\n try:\n uid = repr(os.getuid())\n ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ urlfetch ~~~~~~~~~~ An easy to use HTTP client based on httplib. :copyright: (c) 2011-2019 by Yue Du. :license: BSD 2-clause License, see LICENSE for more details. """ __version__ = '1.1.2' __author__ = 'Yue Du <ifduyue@gmail.com>' __url__ = 'https://github.com/ifduy...
ifduyue/urlfetch
urlfetch.py
Response.body
python
def body(self): content = [] length = 0 for chunk in self: content.append(chunk) length += len(chunk) if self.length_limit and length > self.length_limit: self.close() raise ContentLimitExceeded("Content length is more than %d "...
Response body. :raises: :class:`ContentLimitExceeded`, :class:`ContentDecodingError`
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L285-L300
[ "b = lambda s: s.encode('latin-1')\n", "def close(self):\n \"\"\"Close the connection.\"\"\"\n self._r.close()\n" ]
class Response(object): """A Response object. >>> import urlfetch >>> response = urlfetch.get("http://docs.python.org/") >>> response.total_time 0.033042049407959 >>> response.status, response.reason, response.version (200, 'OK', 10) >>> type(response.body), len(response.body) (<typ...
ifduyue/urlfetch
urlfetch.py
Response.json
python
def json(self): try: return json.loads(self.text) except Exception as e: raise ContentDecodingError(e)
Load response body as json. :raises: :class:`ContentDecodingError`
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L314-L322
null
class Response(object): """A Response object. >>> import urlfetch >>> response = urlfetch.get("http://docs.python.org/") >>> response.total_time 0.033042049407959 >>> response.status, response.reason, response.version (200, 'OK', 10) >>> type(response.body), len(response.body) (<typ...
ifduyue/urlfetch
urlfetch.py
Response.headers
python
def headers(self): if py3k: return dict((k.lower(), v) for k, v in self.getheaders()) else: return dict(self.getheaders())
Response headers. Response headers is a dict with all keys in lower case. >>> import urlfetch >>> response = urlfetch.get("http://docs.python.org/") >>> response.headers { 'content-length': '8719', 'x-cache': 'MISS from localhost', 'accept-ra...
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L325-L350
null
class Response(object): """A Response object. >>> import urlfetch >>> response = urlfetch.get("http://docs.python.org/") >>> response.total_time 0.033042049407959 >>> response.status, response.reason, response.version (200, 'OK', 10) >>> type(response.body), len(response.body) (<typ...
ifduyue/urlfetch
urlfetch.py
Response.cookies
python
def cookies(self): c = Cookie.SimpleCookie(self.getheader('set-cookie')) return dict((i.key, i.value) for i in c.values())
Cookies in dict
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L353-L356
null
class Response(object): """A Response object. >>> import urlfetch >>> response = urlfetch.get("http://docs.python.org/") >>> response.total_time 0.033042049407959 >>> response.status, response.reason, response.version (200, 'OK', 10) >>> type(response.body), len(response.body) (<typ...
ifduyue/urlfetch
urlfetch.py
Response.cookiestring
python
def cookiestring(self): return '; '.join('%s=%s' % (k, v) for k, v in self.cookies.items())
Cookie string
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L359-L361
null
class Response(object): """A Response object. >>> import urlfetch >>> response = urlfetch.get("http://docs.python.org/") >>> response.total_time 0.033042049407959 >>> response.status, response.reason, response.version (200, 'OK', 10) >>> type(response.body), len(response.body) (<typ...
ifduyue/urlfetch
urlfetch.py
Response.links
python
def links(self): ret = [] linkheader = self.getheader('link') if not linkheader: return ret for i in linkheader.split(','): try: url, params = i.split(';', 1) except ValueError: url, params = i, '' link = {} ...
Links parsed from HTTP Link header
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L364-L384
null
class Response(object): """A Response object. >>> import urlfetch >>> response = urlfetch.get("http://docs.python.org/") >>> response.total_time 0.033042049407959 >>> response.status, response.reason, response.version (200, 'OK', 10) >>> type(response.body), len(response.body) (<typ...
ifduyue/urlfetch
urlfetch.py
Session.cookiestring
python
def cookiestring(self, value): " c = Cookie.SimpleCookie(value) sc = [(i.key, i.value) for i in c.values()] self.cookies = dict(sc)
Cookie string setter
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L452-L456
null
class Session(object): """A session object. :class:`urlfetch.Session` can hold common headers and cookies. Every request issued by a :class:`urlfetch.Session` object will bring u these headers and cookies. :class:`urlfetch.Session` plays a role in handling cookies, just like a cookiejar. ...
ifduyue/urlfetch
urlfetch.py
Session.request
python
def request(self, *args, **kwargs): headers = self.headers.copy() if self.cookiestring: headers['Cookie'] = self.cookiestring headers.update(kwargs.get('headers', {})) kwargs['headers'] = headers r = request(*args, **kwargs) self.cookies.update(r.cookies) ...
Issue a request.
train
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L465-L476
[ "def request(url, method=\"GET\", params=None, data=None, headers={},\n timeout=None, files={}, randua=False, auth=None, length_limit=None,\n proxies=None, trust_env=True, max_redirects=0,\n source_address=None, **kwargs):\n \"\"\"request an URL\n\n :arg string url: URL to be ...
class Session(object): """A session object. :class:`urlfetch.Session` can hold common headers and cookies. Every request issued by a :class:`urlfetch.Session` object will bring u these headers and cookies. :class:`urlfetch.Session` plays a role in handling cookies, just like a cookiejar. ...
mozilla/FoxPuppet
foxpuppet/windows/browser/navbar.py
NavBar.is_tracking_shield_displayed
python
def is_tracking_shield_displayed(self): with self.selenium.context(self.selenium.CONTEXT_CHROME): if self.window.firefox_version >= 63: # Bug 1471713, 1476218 el = self.root.find_element(*self._tracking_protection_shield_locator) return el.get_attribute("active") is ...
Tracking Protection shield. Returns: bool: True or False if the Tracking Shield is displayed.
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/navbar.py#L26-L38
null
class NavBar(Region): """Representation of the navigation bar. Args: window (:py:class:`BaseWindow`): Window object this region appears in. root (:py:class:`~selenium.webdriver.remote.webelement.WebElement`): WebDriver element object that serves as the root for the ...
mozilla/FoxPuppet
foxpuppet/windows/browser/notifications/addons.py
AddOnInstallBlocked.allow
python
def allow(self): with self.selenium.context(self.selenium.CONTEXT_CHROME): self.find_primary_button().click()
Allow the add-on to be installed.
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/notifications/addons.py#L14-L17
[ "def find_primary_button(self):\n \"\"\"Retrieve the primary button.\"\"\"\n if self.window.firefox_version >= 67:\n return self.root.find_element(\n By.CLASS_NAME, \"popup-notification-primary-button\")\n return self.root.find_anonymous_element_by_attribute(\n \"anonid\", \"button...
class AddOnInstallBlocked(BaseNotification): """Add-on install blocked notification."""
mozilla/FoxPuppet
foxpuppet/windows/browser/notifications/addons.py
AddOnInstallConfirmation.addon_name
python
def addon_name(self): with self.selenium.context(self.selenium.CONTEXT_CHROME): el = self.find_description() return el.find_element(By.CSS_SELECTOR, "b").text
Provide access to the add-on name. Returns: str: Add-on name.
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/notifications/addons.py#L24-L33
[ "def find_description(self):\n \"\"\"Retrieve the notification description.\"\"\"\n if self.window.firefox_version >= 67:\n return self.root.find_element(\n By.CLASS_NAME, \"popup-notification-description\")\n return self.root.find_anonymous_element_by_attribute(\n \"class\", \"pop...
class AddOnInstallConfirmation(BaseNotification): """Add-on install confirmation notification.""" @property def cancel(self): """Cancel add-on install.""" with self.selenium.context(self.selenium.CONTEXT_CHROME): self.find_secondary_button().click() def install(self): ...
mozilla/FoxPuppet
foxpuppet/windows/browser/notifications/addons.py
AddOnInstallConfirmation.cancel
python
def cancel(self): with self.selenium.context(self.selenium.CONTEXT_CHROME): self.find_secondary_button().click()
Cancel add-on install.
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/notifications/addons.py#L35-L38
[ "def find_secondary_button(self):\n \"\"\"Retrieve the secondary button.\"\"\"\n if self.window.firefox_version >= 67:\n return self.root.find_element(\n By.CLASS_NAME, \"popup-notification-secondary-button\")\n return self.root.find_anonymous_element_by_attribute(\n \"anonid\", \"...
class AddOnInstallConfirmation(BaseNotification): """Add-on install confirmation notification.""" @property def addon_name(self): """Provide access to the add-on name. Returns: str: Add-on name. """ with self.selenium.context(self.selenium.CONTEXT_CHROME): ...
mozilla/FoxPuppet
foxpuppet/windows/browser/notifications/addons.py
AddOnInstallConfirmation.install
python
def install(self): with self.selenium.context(self.selenium.CONTEXT_CHROME): self.find_primary_button().click()
Confirm add-on install.
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/notifications/addons.py#L40-L43
[ "def find_primary_button(self):\n \"\"\"Retrieve the primary button.\"\"\"\n if self.window.firefox_version >= 67:\n return self.root.find_element(\n By.CLASS_NAME, \"popup-notification-primary-button\")\n return self.root.find_anonymous_element_by_attribute(\n \"anonid\", \"button...
class AddOnInstallConfirmation(BaseNotification): """Add-on install confirmation notification.""" @property def addon_name(self): """Provide access to the add-on name. Returns: str: Add-on name. """ with self.selenium.context(self.selenium.CONTEXT_CHROME): ...
mozilla/FoxPuppet
foxpuppet/windows/browser/notifications/addons.py
AddOnInstallComplete.close
python
def close(self): with self.selenium.context(self.selenium.CONTEXT_CHROME): if self.window.firefox_version > 63: self.find_primary_button().click() self.window.wait_for_notification(None) else: BaseNotification.close(self)
Close the notification.
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/notifications/addons.py#L49-L56
[ "def find_primary_button(self):\n \"\"\"Retrieve the primary button.\"\"\"\n if self.window.firefox_version >= 67:\n return self.root.find_element(\n By.CLASS_NAME, \"popup-notification-primary-button\")\n return self.root.find_anonymous_element_by_attribute(\n \"anonid\", \"button...
class AddOnInstallComplete(BaseNotification): """Add-on install complete notification."""
mozilla/FoxPuppet
foxpuppet/windows/browser/window.py
BrowserWindow.navbar
python
def navbar(self): window = BaseWindow(self.selenium, self.selenium.current_window_handle) with self.selenium.context(self.selenium.CONTEXT_CHROME): el = self.selenium.find_element(*self._nav_bar_locator) return NavBar(window, el)
Provide access to the Navigation Bar. Returns: :py:class:`NavBar`: FoxPuppet NavBar object.
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/window.py#L30-L40
null
class BrowserWindow(BaseWindow): """Representation of a browser window.""" _file_menu_button_locator = (By.ID, "file-menu") _file_menu_private_window_locator = (By.ID, "menu_newPrivateWindow") _file_menu_new_window_button_locator = (By.ID, "menu_newNavigator") _nav_bar_locator = (By.ID, "nav-bar") ...
mozilla/FoxPuppet
foxpuppet/windows/browser/window.py
BrowserWindow.notification
python
def notification(self): with self.selenium.context(self.selenium.CONTEXT_CHROME): try: root = self.selenium.find_element(*self._notification_locator) return BaseNotification.create(self, root) except NoSuchElementException: pass ...
Provide access to the currently displayed notification. Returns: :py:class:`BaseNotification`: FoxPuppet BaseNotification object.
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/window.py#L43-L64
[ "def create(window, root):\n \"\"\"Create a notification object.\n\n Args:\n window (:py:class:`BrowserWindow`): Window object this region\n appears in.\n root\n (:py:class:`~selenium.webdriver.remote.webelement.WebElement`):\n WebDriver element object that serve...
class BrowserWindow(BaseWindow): """Representation of a browser window.""" _file_menu_button_locator = (By.ID, "file-menu") _file_menu_private_window_locator = (By.ID, "menu_newPrivateWindow") _file_menu_new_window_button_locator = (By.ID, "menu_newNavigator") _nav_bar_locator = (By.ID, "nav-bar") ...
mozilla/FoxPuppet
foxpuppet/windows/browser/window.py
BrowserWindow.wait_for_notification
python
def wait_for_notification(self, notification_class=BaseNotification): if notification_class: if notification_class is BaseNotification: message = "No notification was shown." else: message = "{0} was not shown.".format(notification_class.__name__) ...
Wait for the specified notification to be displayed. Args: notification_class (:py:class:`BaseNotification`, optional): The notification class to wait for. If `None` is specified it will wait for any notification to be closed. Defaults to `BaseNotific...
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/window.py#L66-L93
null
class BrowserWindow(BaseWindow): """Representation of a browser window.""" _file_menu_button_locator = (By.ID, "file-menu") _file_menu_private_window_locator = (By.ID, "menu_newPrivateWindow") _file_menu_new_window_button_locator = (By.ID, "menu_newNavigator") _nav_bar_locator = (By.ID, "nav-bar") ...
mozilla/FoxPuppet
foxpuppet/windows/browser/window.py
BrowserWindow.is_private
python
def is_private(self): self.switch_to() with self.selenium.context(self.selenium.CONTEXT_CHROME): return self.selenium.execute_script( """ Components.utils.import("resource://gre/modules/PrivateBrowsingUtils.jsm"); let chromeWindow = arguments[...
Property that checks if the specified window is private or not. Returns: bool: True if this is a Private Browsing window.
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/window.py#L96-L113
[ "def switch_to(self):\n \"\"\"Switch focus for Selenium commands to this window.\"\"\"\n self.selenium.switch_to.window(self.handle)\n" ]
class BrowserWindow(BaseWindow): """Representation of a browser window.""" _file_menu_button_locator = (By.ID, "file-menu") _file_menu_private_window_locator = (By.ID, "menu_newPrivateWindow") _file_menu_new_window_button_locator = (By.ID, "menu_newNavigator") _nav_bar_locator = (By.ID, "nav-bar") ...
mozilla/FoxPuppet
foxpuppet/windows/browser/window.py
BrowserWindow.open_window
python
def open_window(self, private=False): handles_before = self.selenium.window_handles self.switch_to() with self.selenium.context(self.selenium.CONTEXT_CHROME): # Opens private or non-private window self.selenium.find_element(*self._file_menu_button_locator).click() ...
Open a new browser window. Args: private (bool): Optional parameter to open a private browsing window. Defaults to False. Returns: :py:class:`BrowserWindow`: Opened window.
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/window.py#L115-L144
[ "def switch_to(self):\n \"\"\"Switch focus for Selenium commands to this window.\"\"\"\n self.selenium.switch_to.window(self.handle)\n" ]
class BrowserWindow(BaseWindow): """Representation of a browser window.""" _file_menu_button_locator = (By.ID, "file-menu") _file_menu_private_window_locator = (By.ID, "menu_newPrivateWindow") _file_menu_new_window_button_locator = (By.ID, "menu_newNavigator") _nav_bar_locator = (By.ID, "nav-bar") ...
mozilla/FoxPuppet
foxpuppet/windows/browser/notifications/base.py
BaseNotification.create
python
def create(window, root): notifications = {} _id = root.get_property("id") from foxpuppet.windows.browser.notifications import addons notifications.update(addons.NOTIFICATIONS) return notifications.get(_id, BaseNotification)(window, root)
Create a notification object. Args: window (:py:class:`BrowserWindow`): Window object this region appears in. root (:py:class:`~selenium.webdriver.remote.webelement.WebElement`): WebDriver element object that serves as the root for the ...
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/notifications/base.py#L19-L39
null
class BaseNotification(Region): """Abstract base class for any kind of notification.""" __metaclass__ = ABCMeta @staticmethod @property def label(self): """Provide access to the notification label. Returns: str: The notification label """ with self.s...
mozilla/FoxPuppet
foxpuppet/windows/browser/notifications/base.py
BaseNotification.label
python
def label(self): with self.selenium.context(self.selenium.CONTEXT_CHROME): return self.root.get_attribute("label")
Provide access to the notification label. Returns: str: The notification label
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/notifications/base.py#L42-L50
null
class BaseNotification(Region): """Abstract base class for any kind of notification.""" __metaclass__ = ABCMeta @staticmethod def create(window, root): """Create a notification object. Args: window (:py:class:`BrowserWindow`): Window object this region appe...
mozilla/FoxPuppet
foxpuppet/windows/browser/notifications/base.py
BaseNotification.origin
python
def origin(self): with self.selenium.context(self.selenium.CONTEXT_CHROME): return self.root.get_attribute("origin")
Provide access to the notification origin. Returns: str: The notification origin.
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/notifications/base.py#L53-L61
null
class BaseNotification(Region): """Abstract base class for any kind of notification.""" __metaclass__ = ABCMeta @staticmethod def create(window, root): """Create a notification object. Args: window (:py:class:`BrowserWindow`): Window object this region appe...
mozilla/FoxPuppet
foxpuppet/windows/browser/notifications/base.py
BaseNotification.find_primary_button
python
def find_primary_button(self): if self.window.firefox_version >= 67: return self.root.find_element( By.CLASS_NAME, "popup-notification-primary-button") return self.root.find_anonymous_element_by_attribute( "anonid", "button")
Retrieve the primary button.
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/notifications/base.py#L63-L69
null
class BaseNotification(Region): """Abstract base class for any kind of notification.""" __metaclass__ = ABCMeta @staticmethod def create(window, root): """Create a notification object. Args: window (:py:class:`BrowserWindow`): Window object this region appe...
mozilla/FoxPuppet
foxpuppet/windows/browser/notifications/base.py
BaseNotification.close
python
def close(self): with self.selenium.context(self.selenium.CONTEXT_CHROME): self.find_close_button().click() self.window.wait_for_notification(None)
Close the notification.
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/notifications/base.py#L95-L99
[ "def find_close_button(self):\n \"\"\"Retrieve the close button.\"\"\"\n if self.window.firefox_version >= 67:\n return self.root.find_element(\n By.CLASS_NAME, \"popup-notification-closebutton\")\n return self.root.find_anonymous_element_by_attribute(\n \"anonid\", \"closebutton\"...
class BaseNotification(Region): """Abstract base class for any kind of notification.""" __metaclass__ = ABCMeta @staticmethod def create(window, root): """Create a notification object. Args: window (:py:class:`BrowserWindow`): Window object this region appe...
mozilla/FoxPuppet
foxpuppet/windows/manager.py
WindowManager.windows
python
def windows(self): from foxpuppet.windows import BrowserWindow return [ BrowserWindow(self.selenium, handle) for handle in self.selenium.window_handles ]
Return a list of all open windows. Returns: list: List of FoxPuppet BrowserWindow objects.
train
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/manager.py#L26-L38
null
class WindowManager(object): """A window manager that controls the creation of window objects. Args: selenium: (:py:class:`~selenium.webdriver.remote.webdriver.WebDriver`): Firefox WebDriver object. """ def __init__(self, selenium): """Create WindowManager Object. ...
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
chebyshev
python
def chebyshev(point1, point2): return max(abs(point1[0] - point2[0]), abs(point1[1] - point2[1]))
Computes distance between 2D points using chebyshev metric :param point1: 1st point :type point1: list :param point2: 2nd point :type point2: list :returns: Distance between point1 and point2 :rtype: float
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L26-L37
null
#!/usr/bin/python # AUTHOR # Daniel Pulido <dpmcmlxxvi@gmail.com> # COPYRIGHT # Copyright (c) 2015 Daniel Pulido <dpmcmlxxvi@gmail.com> # LICENSE # MIT License (http://opensource.org/licenses/MIT) """ Various patterns to scan pixels on a grid. Rectangular patterns are scanned first along the x-coordinate then t...
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
hilbertrot
python
def hilbertrot(n, x, y, rx, ry): if ry == 0: if rx == 1: x = n - 1 - x y = n - 1 - y return y, x return x, y
Rotates and flips a quadrant appropriately for the Hilbert scan generator. See https://en.wikipedia.org/wiki/Hilbert_curve.
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L52-L61
null
#!/usr/bin/python # AUTHOR # Daniel Pulido <dpmcmlxxvi@gmail.com> # COPYRIGHT # Copyright (c) 2015 Daniel Pulido <dpmcmlxxvi@gmail.com> # LICENSE # MIT License (http://opensource.org/licenses/MIT) """ Various patterns to scan pixels on a grid. Rectangular patterns are scanned first along the x-coordinate then t...
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
circlescan
python
def circlescan(x0, y0, r1, r2): # Validate inputs if r1 < 0: raise ValueError("Initial radius must be non-negative") if r2 < 0: raise ValueError("Final radius must be non-negative") # List of pixels visited in previous diameter previous = [] # Scan distances outward (1) or inward (-1) ...
Scan pixels in a circle pattern around a center point :param x0: Center x-coordinate :type x0: float :param y0: Center y-coordinate :type y0: float :param r1: Initial radius :type r1: float :param r2: Final radius :type r2: float :returns: Coordinate generator :rtype: function
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L392-L466
null
#!/usr/bin/python # AUTHOR # Daniel Pulido <dpmcmlxxvi@gmail.com> # COPYRIGHT # Copyright (c) 2015 Daniel Pulido <dpmcmlxxvi@gmail.com> # LICENSE # MIT License (http://opensource.org/licenses/MIT) """ Various patterns to scan pixels on a grid. Rectangular patterns are scanned first along the x-coordinate then t...
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
gridscan
python
def gridscan(xi, yi, xf, yf, stepx=1, stepy=1): if stepx <= 0: raise ValueError("X-step must be positive") if stepy <= 0: raise ValueError("Y-step must be positive") # Determine direction to move dx = stepx if xf >= xi else -stepx dy = stepy if yf >= yi else -stepy for y in range(yi, yf + dy,...
Scan pixels in a grid pattern along the x-coordinate then y-coordinate :param xi: Initial x-coordinate :type xi: int :param yi: Initial y-coordinate :type yi: int :param xf: Final x-coordinate :type xf: int :param yf: Final y-coordinate :type yf: int :param stepx: Step size in x-coo...
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L468-L496
null
#!/usr/bin/python # AUTHOR # Daniel Pulido <dpmcmlxxvi@gmail.com> # COPYRIGHT # Copyright (c) 2015 Daniel Pulido <dpmcmlxxvi@gmail.com> # LICENSE # MIT License (http://opensource.org/licenses/MIT) """ Various patterns to scan pixels on a grid. Rectangular patterns are scanned first along the x-coordinate then t...
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
hilbertscan
python
def hilbertscan(size, distance): size = 2*(1<<(size-1).bit_length()); if (distance > size**2 - 1): raise StopIteration("Invalid distance!") for d in range(distance): t = d x = 0 y = 0 s = 1 while (s < size): rx = 1 & (t / 2) ry = 1 & (t ^ rx)...
Scan pixels in a Hilbert curve pattern in the first quadrant. Modified algorithm from https://en.wikipedia.org/wiki/Hilbert_curve. :param size: Size of enclosing square :type size: int :param distance: Distance along curve (Must be smaller than size**2 - 1) :type distance: int :returns: Coordi...
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L498-L526
[ "def hilbertrot(n, x, y, rx, ry):\n \"\"\"Rotates and flips a quadrant appropriately for the Hilbert scan\n generator. See https://en.wikipedia.org/wiki/Hilbert_curve.\n \"\"\"\n if ry == 0:\n if rx == 1:\n x = n - 1 - x\n y = n - 1 - y\n return y, x\n return x, y\...
#!/usr/bin/python # AUTHOR # Daniel Pulido <dpmcmlxxvi@gmail.com> # COPYRIGHT # Copyright (c) 2015 Daniel Pulido <dpmcmlxxvi@gmail.com> # LICENSE # MIT License (http://opensource.org/licenses/MIT) """ Various patterns to scan pixels on a grid. Rectangular patterns are scanned first along the x-coordinate then t...
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
ringscan
python
def ringscan(x0, y0, r1, r2, metric=chebyshev): # Validate inputs if r1 < 0: raise ValueError("Initial radius must be non-negative") if r2 < 0: raise ValueError("Final radius must be non-negative") if not hasattr(metric, "__call__"): raise TypeError("Metric not callable") # Define clockwise step d...
Scan pixels in a ring pattern around a center point clockwise :param x0: Center x-coordinate :type x0: int :param y0: Center y-coordinate :type y0: int :param r1: Initial radius :type r1: int :param r2: Final radius :type r2: int :param metric: Distance metric :type metric: func...
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L528-L604
[ "def chebyshev(point1, point2):\n \"\"\"Computes distance between 2D points using chebyshev metric\n\n :param point1: 1st point\n :type point1: list\n :param point2: 2nd point\n :type point2: list\n :returns: Distance between point1 and point2\n :rtype: float\n \"\"\"\n\n return max(abs(p...
#!/usr/bin/python # AUTHOR # Daniel Pulido <dpmcmlxxvi@gmail.com> # COPYRIGHT # Copyright (c) 2015 Daniel Pulido <dpmcmlxxvi@gmail.com> # LICENSE # MIT License (http://opensource.org/licenses/MIT) """ Various patterns to scan pixels on a grid. Rectangular patterns are scanned first along the x-coordinate then t...
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
snakescan
python
def snakescan(xi, yi, xf, yf): # Determine direction to move dx = 1 if xf >= xi else -1 dy = 1 if yf >= yi else -1 # Scan pixels first along x-coordinate then y-coordinate and flip # x-direction when the end of the line is reached x, xa, xb = xi, xi, xf for y in range(yi, yf + dy, dy): ...
Scan pixels in a snake pattern along the x-coordinate then y-coordinate :param xi: Initial x-coordinate :type xi: int :param yi: Initial y-coordinate :type yi: int :param xf: Final x-coordinate :type xf: int :param yf: Final y-coordinate :type yf: int :returns: Coordinate generator ...
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L606-L635
null
#!/usr/bin/python # AUTHOR # Daniel Pulido <dpmcmlxxvi@gmail.com> # COPYRIGHT # Copyright (c) 2015 Daniel Pulido <dpmcmlxxvi@gmail.com> # LICENSE # MIT License (http://opensource.org/licenses/MIT) """ Various patterns to scan pixels on a grid. Rectangular patterns are scanned first along the x-coordinate then t...
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
walkscan
python
def walkscan(x0, y0, xn=0.25, xp=0.25, yn=0.25, yp=0.25): # Validate inputs if xn < 0: raise ValueError("Negative x probabilty must be non-negative") if xp < 0: raise ValueError("Positive x probabilty must be non-negative") if yn < 0: raise ValueError("Negative y probabilty must be non-negative") i...
Scan pixels in a random walk pattern with given step probabilities. The random walk will continue indefinitely unless a skip transformation is used with the 'stop' parameter set or a clip transformation is used with the 'abort' parameter set to True. The probabilities are normalized to sum to 1. :param...
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L637-L691
null
#!/usr/bin/python # AUTHOR # Daniel Pulido <dpmcmlxxvi@gmail.com> # COPYRIGHT # Copyright (c) 2015 Daniel Pulido <dpmcmlxxvi@gmail.com> # LICENSE # MIT License (http://opensource.org/licenses/MIT) """ Various patterns to scan pixels on a grid. Rectangular patterns are scanned first along the x-coordinate then t...
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
clip.next
python
def next(self): while True: x, y = next(self.scan) if self.predicate is not None and not self.predicate(x,y): if self.abort: raise StopIteration("Boundary crossed!") elif (x < self.minx or x > self.maxx or y < self.miny or ...
Next point in iteration
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L108-L121
null
class clip(object): """Clip coordinates that exceed boundary """ def __init__(self, scan, minx=-sys.maxint, maxx=sys.maxint, miny=-sys.maxint, maxy=sys.maxint, predicate=None, abort=False):...
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
reflection.next
python
def next(self): x, y = next(self.scan) xr = -x if self.rx else x yr = -y if self.ry else y return xr, yr
Next point in iteration
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L142-L148
null
class reflection(object): """Reflect coordinates about x and y axes """ def __init__(self, scan, rx=False, ry=False): """ :param scan: Pixel scan generator :type scan: function :param rx: True if x-coordinate should be reflected (default=False) :type rx: bool ...
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
reservoir.next
python
def next(self): if self.count < len(self.reservoir): self.count += 1 return self.reservoir[self.count-1] raise StopIteration("Reservoir exhausted")
Next point in iteration
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L186-L193
null
class reservoir(object): def __init__(self, scan, npoints): """Randomly sample points using the reservoir sampling method. This is only useful if you need exactly 'npoints' sampled. Otherwise use the 'sample' transformation to randomly sample at a given rate. This method requires st...
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
rotation.next
python
def next(self): x, y = next(self.scan) ca, sa = math.cos(self.angle), math.sin(self.angle) xr = ca * x - sa * y yr = sa * x + ca * y return xr, yr
Next point in iteration
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L214-L221
null
class rotation(object): """Rotate coordinates by given angle. If the final transformation axes do not align with the x and y axes then it may yield duplicate coordinates during scanning. """ def __init__(self, scan, angle=0): """ :param scan: Pixel scan generator :type scan:...
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
sample.next
python
def next(self): if self.probability == 1: x, y = next(self.scan) else: while True: x, y = next(self.scan) if random.random() <= self.probability: break return x, y
Next point in iteration
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L241-L250
null
class sample(object): """Randomly sample points at the given probability. """ def __init__(self, scan, probability=1): """ :param scan: Pixel scan generator :type scan: function :param probability: Sampling probability in interval [0,1] (default=1) :type probability: ...
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
scale.next
python
def next(self): x, y = next(self.scan) xr = self.sx * x yr = self.sy * y return xr, yr
Next point in iteration
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L274-L280
null
class scale(object): """Scale coordinates by given factor """ def __init__(self, scan, sx=1, sy=1): """ :param scan: Pixel scan generator :type scan: function :param sx: x-coordinate scale factor (default=1) :type sx: float :param sy: y-coordinate scale facto...
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
skip.next
python
def next(self): while True: x, y = next(self.scan) self.index += 1 if (self.index < self.start): continue if (self.index > self.stop): raise StopIteration("skip stopping") if ((self.index-self.start) % self.step != 0): continue return x, y
Next point in iteration
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L309-L318
null
class skip(object): """Skip points at the given step size """ def __init__(self, scan, start=0, stop=sys.maxint, step=1): """ :param scan: Pixel scan generator :type scan: function :param start: Iteration starting 0-based index (default = 0) :type start: int :...
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
snap.next
python
def next(self): x, y = next(self.scan) xs = int(round(x)) ys = int(round(y)) return xs, ys
Next point in iteration
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L333-L339
null
class snap(object): """Snap x and y coordinates to a grid point """ def __init__(self, scan): """ :param scan: Pixel scan generator :type scan: function """ self.scan = scan def __iter__(self): return self
dpmcmlxxvi/pixelscan
pixelscan/pixelscan.py
translation.next
python
def next(self): x, y = next(self.scan) xr = x + self.tx yr = y + self.ty return xr, yr
Next point in iteration
train
https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L380-L386
null
class translation(object): """Translate coordinates by given offset """ def __init__(self, scan, tx=0, ty=0): """ :param scan: Pixel scan generator :type scan: function :param sx: x-coordinate translation offset (default = 0) :type sx: float :param sy: y-coor...
TylerTemp/docpie
docpie/pie.py
Docpie.docpie
python
def docpie(self, argv=None): token = self._prepare_token(argv) # check first, raise after # so `-hwhatever` can trigger `-h` first self.check_flag_and_handler(token) if token.error is not None: # raise DocpieExit('%s\n\n%s' % (token.error, help_msg)) sel...
match the argv for each usages, return dict. if argv is None, it will use sys.argv instead. if argv is str, it will call argv.split() first. this function will check the options in self.extra and handle it first. Which means it may not try to match any usages because of the checking.
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/pie.py#L128-L168
[ "def _drop_non_appeared(self):\n for key, _ in filter(lambda k_v: k_v[1] == -1, dict(self).items()):\n self.pop(key)\n", "def _add_rest_value(self, rest):\n for each in rest:\n default_values = each.get_sys_default_value(\n self.appeared_only, False)\n logger.debug('get rest ...
class Docpie(dict): # Docpie version # it's not a good idea but it can avoid loop importing _version = '0.4.2' option_name = 'Options:' usage_name = 'Usage:' doc = None case_sensitive = False auto2dashes = True name = None help = True helpstyle = 'python' version = Non...
TylerTemp/docpie
docpie/pie.py
Docpie.clone_exception
python
def clone_exception(error, args): new_error = error.__class__(*args) new_error.__dict__ = error.__dict__ return new_error
return a new cloned error when do: ``` try: do_sth() except BaseException as e: handle(e) def handle(error): # do sth with error raise e # <- won't work! This can generate a new cloned error of the same class P...
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/pie.py#L425-L454
null
class Docpie(dict): # Docpie version # it's not a good idea but it can avoid loop importing _version = '0.4.2' option_name = 'Options:' usage_name = 'Usage:' doc = None case_sensitive = False auto2dashes = True name = None help = True helpstyle = 'python' version = Non...
TylerTemp/docpie
docpie/pie.py
Docpie.help_handler
python
def help_handler(docpie, flag): help_type = docpie.help helpstyle = docpie.helpstyle if helpstyle == 'python': doc = Docpie.help_style_python(docpie.doc) elif helpstyle == 'dedent': doc = Docpie.help_style_dedent(docpie.doc) # elif help_style == 'raw': ...
Default help(`--help`, `-h`) handler. print help string and exit. when help = 'short_brief', flag startswith `--` will print the full `doc`, `-` for "Usage" section and "Option" section only. when help = 'short_brief_notice', flag startswith `--` will print the full `doc`, `-` for "Usag...
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/pie.py#L457-L502
null
class Docpie(dict): # Docpie version # it's not a good idea but it can avoid loop importing _version = '0.4.2' option_name = 'Options:' usage_name = 'Usage:' doc = None case_sensitive = False auto2dashes = True name = None help = True helpstyle = 'python' version = Non...
TylerTemp/docpie
docpie/pie.py
Docpie.to_dict
python
def to_dict(self): # cls, self): config = { 'stdopt': self.stdopt, 'attachopt': self.attachopt, 'attachvalue': self.attachvalue, 'auto2dashes': self.auto2dashes, 'case_sensitive': self.case_sensitive, 'namedoptions': self.namedoptions, ...
Convert Docpie into a JSONlizable dict. Use it in this way: pie = Docpie(__doc__) json.dumps(pie.convert_2_dict()) Note the `extra` info will be lost if you costomize that, because a function is not JSONlizable. You can use `set_config(extra={...})` to set it back.
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/pie.py#L547-L597
null
class Docpie(dict): # Docpie version # it's not a good idea but it can avoid loop importing _version = '0.4.2' option_name = 'Options:' usage_name = 'Usage:' doc = None case_sensitive = False auto2dashes = True name = None help = True helpstyle = 'python' version = Non...
TylerTemp/docpie
docpie/pie.py
Docpie.from_dict
python
def from_dict(cls, dic): if '__version__' not in dic: raise ValueError('Not support old docpie data') data_version = int(dic['__version__'].replace('.', '')) this_version = int(cls._version.replace('.', '')) logger.debug('this: %s, old: %s', this_version, data_version) ...
Convert dict generated by `convert_2_dict` into Docpie instance You can do this: pie = Docpie(__doc__) clone_pie = json.loads(pie.convert_2_docpie( json.dumps(pie.convert_2_dict()) )) Note if you changed `extra`, it will be lost. You can use `set_config(extr...
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/pie.py#L602-L651
null
class Docpie(dict): # Docpie version # it's not a good idea but it can avoid loop importing _version = '0.4.2' option_name = 'Options:' usage_name = 'Usage:' doc = None case_sensitive = False auto2dashes = True name = None help = True helpstyle = 'python' version = Non...
TylerTemp/docpie
docpie/pie.py
Docpie.set_config
python
def set_config(self, **config): reinit = False if 'stdopt' in config: stdopt = config.pop('stdopt') reinit = (stdopt != self.stdopt) self.stdopt = stdopt if 'attachopt' in config: attachopt = config.pop('attachopt') reinit = reinit or (...
Shadow all the current config.
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/pie.py#L655-L714
[ "def _init(self):\n uparser = UsageParser(\n self.usage_name, self.case_sensitive,\n self.stdopt, self.attachopt, self.attachvalue, self.namedoptions)\n oparser = OptionParser(\n self.option_name, self.case_sensitive,\n self.stdopt, self.attachopt, self.attachvalue, self.namedoptio...
class Docpie(dict): # Docpie version # it's not a good idea but it can avoid loop importing _version = '0.4.2' option_name = 'Options:' usage_name = 'Usage:' doc = None case_sensitive = False auto2dashes = True name = None help = True helpstyle = 'python' version = Non...
TylerTemp/docpie
docpie/pie.py
Docpie.find_flag_alias
python
def find_flag_alias(self, flag): for each in self.opt_names: if flag in each: result = set(each) # a copy result.remove(flag) return result return None
Return alias set of a flag; return None if flag is not defined in "Options".
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/pie.py#L749-L758
null
class Docpie(dict): # Docpie version # it's not a good idea but it can avoid loop importing _version = '0.4.2' option_name = 'Options:' usage_name = 'Usage:' doc = None case_sensitive = False auto2dashes = True name = None help = True helpstyle = 'python' version = Non...
TylerTemp/docpie
docpie/pie.py
Docpie.set_auto_handler
python
def set_auto_handler(self, flag, handler): assert flag.startswith('-') and flag not in ('-', '--') alias = self.find_flag_alias(flag) or [] self.extra[flag] = handler for each in alias: self.extra[each] = handler
Set pre-auto-handler for a flag. the handler must accept two argument: first the `pie` which referent to the current `Docpie` instance, second, the `flag` which is the flag found in `argv`. Different from `extra` argument, this will set the alias option you defined in `Option` ...
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/pie.py#L760-L775
[ "def find_flag_alias(self, flag):\n \"\"\"Return alias set of a flag; return None if flag is not defined in\n \"Options\".\n \"\"\"\n for each in self.opt_names:\n if flag in each:\n result = set(each) # a copy\n result.remove(flag)\n return result\n return No...
class Docpie(dict): # Docpie version # it's not a good idea but it can avoid loop importing _version = '0.4.2' option_name = 'Options:' usage_name = 'Usage:' doc = None case_sensitive = False auto2dashes = True name = None help = True helpstyle = 'python' version = Non...
TylerTemp/docpie
docpie/pie.py
Docpie.preview
python
def preview(self, stream=sys.stdout): write = stream.write write(('[Quick preview of Docpie %s]' % self._version).center(80, '=')) write('\n') write(' sections '.center(80, '-')) write('\n') write(self.usage_text) write('\n') option_sections = self.opt...
A quick preview of docpie. Print all the parsed object
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/pie.py#L777-L837
null
class Docpie(dict): # Docpie version # it's not a good idea but it can avoid loop importing _version = '0.4.2' option_name = 'Options:' usage_name = 'Usage:' doc = None case_sensitive = False auto2dashes = True name = None help = True helpstyle = 'python' version = Non...
TylerTemp/docpie
docpie/parser.py
OptionParser.parse_content
python
def parse_content(self, text): """parse section to formal format raw_content: {title: section(with title)}. For `help` access. formal_content: {title: section} but the section has been dedented without title. For parse instance""" raw_content = self.raw_content ...
parse section to formal format raw_content: {title: section(with title)}. For `help` access. formal_content: {title: section} but the section has been dedented without title. For parse instance
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/parser.py#L413-L476
null
class OptionParser(Parser): split_re = re.compile(r'(<.*?>)|\s+') wrap_symbol_re = re.compile(r'([\|\[\]\(\)]|\.\.\.)') line_re = re.compile(r'^(?P<indent> *)' r'(?P<option>[\d\w=_, <>\-\[\]\.]+?)' r'(?P<separater>$| $| {2,})' r'(?P<...
TylerTemp/docpie
docpie/parser.py
OptionParser.parse_names_and_default
python
def parse_names_and_default(self): """parse for `parse_content` {title: [('-a, --all=STH', 'default'), ...]}""" result = {} for title, text in self.formal_content.items(): if not text: result[title] = [] continue logger....
parse for `parse_content` {title: [('-a, --all=STH', 'default'), ...]}
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/parser.py#L478-L521
[ "def parse_line_option_indent(cls, line):\n opt_str, separater, description_str = \\\n cls.cut_first_spaces_outside_bracket(line)\n\n logger.debug('%(line)s -> %(opt_str)r, '\n '%(separater)r, '\n '%(description_str)r' % locals())\n if description_str.strip():\n ...
class OptionParser(Parser): split_re = re.compile(r'(<.*?>)|\s+') wrap_symbol_re = re.compile(r'([\|\[\]\(\)]|\.\.\.)') line_re = re.compile(r'^(?P<indent> *)' r'(?P<option>[\d\w=_, <>\-\[\]\.]+?)' r'(?P<separater>$| $| {2,})' r'(?P<...
TylerTemp/docpie
docpie/parser.py
OptionParser.parse_to_instance
python
def parse_to_instance(self, title_of_name_and_default): """{title: [Option(), ...]}""" result = {} for title, name_and_default in title_of_name_and_default.items(): logger.debug((title, name_and_default)) result[title] = opts = [] for opt_str, default in...
{title: [Option(), ...]}
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/parser.py#L577-L592
[ "def parse_opt_str(self, opt):\n\n repeat = False\n\n # -sth=<goes> ON -> -sth, <goes>, ON\n opt_lis = self.opt_str_to_list(opt)\n logger.debug('%r -> %s' % (opt, opt_lis))\n\n first = opt_lis.pop(0)\n if not first.startswith('-'):\n raise DocpieError('option %s does not start with \"-\"' %...
class OptionParser(Parser): split_re = re.compile(r'(<.*?>)|\s+') wrap_symbol_re = re.compile(r'([\|\[\]\(\)]|\.\.\.)') line_re = re.compile(r'^(?P<indent> *)' r'(?P<option>[\d\w=_, <>\-\[\]\.]+?)' r'(?P<separater>$| $| {2,})' r'(?P<...
TylerTemp/docpie
docpie/parser.py
UsageParser.set_option_name_2_instance
python
def set_option_name_2_instance(self, options): """{title: {'-a': Option(), '--all': Option()}}""" title_opt_2_ins = self.titled_opt_to_ins title_opt_2_ins.clear() for title, opts in options.items(): title_opt_2_ins[title] = opt_2_ins = {} for each in opts: ...
{title: {'-a': Option(), '--all': Option()}}
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/parser.py#L761-L770
null
class UsageParser(Parser): angle_bracket_re = re.compile(r'(<.*?>)') wrap_symbol_re = re.compile( r'(\[[^\]\s]*?options\]|\.\.\.|\||\[|\]|\(|\))' ) split_re = re.compile(r'(\[[^\]\s]*?options\]|\S*<.*?>\S*)|\s+') # will match '-', '--', and # flag ::= "-" [ "-" ] chars "=<" chars ">" ...
TylerTemp/docpie
docpie/parser.py
UsageParser.parse_content
python
def parse_content(self, text): """get Usage section and set to `raw_content`, `formal_content` of no title and empty-line version""" match = re.search( self.usage_re_str.format(self.usage_name), text, flags=(re.DOTALL if self.case_sen...
get Usage section and set to `raw_content`, `formal_content` of no title and empty-line version
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/parser.py#L772-L795
[ "def drop_started_empty_lines(cls, text):\n # drop the empty lines at start\n # different from lstrip\n logger.debug(repr(text))\n m = cls.started_empty_lines.match(text)\n if m is None:\n return text\n return m.groupdict()['rest']\n" ]
class UsageParser(Parser): angle_bracket_re = re.compile(r'(<.*?>)') wrap_symbol_re = re.compile( r'(\[[^\]\s]*?options\]|\.\.\.|\||\[|\]|\(|\))' ) split_re = re.compile(r'(\[[^\]\s]*?options\]|\S*<.*?>\S*)|\s+') # will match '-', '--', and # flag ::= "-" [ "-" ] chars "=<" chars ">" ...
TylerTemp/docpie
docpie/__init__.py
docpie
python
def docpie(doc, argv=None, help=True, version=None, stdopt=True, attachopt=True, attachvalue=True, helpstyle='python', auto2dashes=True, name=None, case_sensitive=False, optionsfirst=False, appearedonly=False, namedoptions=False, extra=None): if case_sensitive...
Parse `argv` based on command-line interface described in `doc`. `docpie` creates your command-line interface based on its description that you pass as `doc`. Such description can contain --options, <positional-argument>, commands, which could be [optional], (required), (mutually | exclusive) or repeat...
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/__init__.py#L34-L133
[ "def docpie(self, argv=None):\n \"\"\"match the argv for each usages, return dict.\n\n if argv is None, it will use sys.argv instead.\n if argv is str, it will call argv.split() first.\n this function will check the options in self.extra and handle it first.\n Which means it may not try to match any ...
""" An easy and Pythonic command-line interface parser. * http://docpie.comes.today * Repository and issue-tracker: https://github.com/TylerTemp/docpie * Licensed under terms of MIT license (see LICENSE) * Copyright (c) 2015-2016 TylerTemp, tylertempdev@gmail.com """ from docpie.pie import Docpie from docpie.erro...
TylerTemp/docpie
docpie/tracemore.py
print_exc_plus
python
def print_exc_plus(stream=sys.stdout): '''print normal traceback information with some local arg values''' # code of this mothod is mainly from <Python Cookbook> write = stream.write # assert the mothod exists flush = stream.flush tp, value, tb = sys.exc_info() while tb.tb_next: tb = ...
print normal traceback information with some local arg values
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/tracemore.py#L22-L56
[ "def u(strs):\n return strs\n" ]
import sys import traceback import logging try: from io import StringIO except ImportError: try: from cStringIO import StringIO except ImportError: from StringIO import StringIO if sys.version_info[0] < 3: def u(strs): return strs.decode('utf-8') else: def u(strs): r...
TylerTemp/docpie
docpie/element.py
Either.fix_argument_only
python
def fix_argument_only(self): ''' fix_argument_only() -> Either or Unit(Argument) `<arg> | ARG | <arg3>` -> `Required(Argument('<arg>', 'ARG', '<arg3>'))` `[<arg>] | [ARG] | [<arg3>]` -> `Optional(Argument('<arg>', 'ARG', '<arg3>'))` `(<arg>) | [ARG]...
fix_argument_only() -> Either or Unit(Argument) `<arg> | ARG | <arg3>` -> `Required(Argument('<arg>', 'ARG', '<arg3>'))` `[<arg>] | [ARG] | [<arg3>]` -> `Optional(Argument('<arg>', 'ARG', '<arg3>'))` `(<arg>) | [ARG]` -> not change, return self `-a | --bette...
train
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/element.py#L1517-L1545
null
class Either(list): error = None def __init__(self, *branch): assert(all(isinstance(x, Unit) for x in branch)) super(Either, self).__init__(branch) self.matched_branch = -1 def fix(self): if not self: return None result = [] for each in self: ...
rosshamish/hexgrid
hexgrid.py
location
python
def location(hexgrid_type, coord): if hexgrid_type == TILE: return str(coord) elif hexgrid_type == NODE: tile_id = nearest_tile_to_node(coord) dirn = tile_node_offset_to_direction(coord - tile_id_to_coord(tile_id)) return '({} {})'.format(tile_id, dirn) elif hexgrid_type == E...
Returns a formatted string representing the coordinate. The format depends on the coordinate type. Tiles look like: 1, 12 Nodes look like: (1 NW), (12 S) Edges look like: (1 NW), (12 SE) :param hexgrid_type: hexgrid.TILE, hexgrid.NODE, hexgrid.EDGE :param coord: integer coordinate in this modu...
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L72-L97
[ "def nearest_tile_to_node(node_coord):\n \"\"\"\n Convenience method wrapping nearest_tile_to_node_using_tiles. Looks at all tiles in legal_tile_ids().\n Returns a tile identifier.\n\n :param node_coord: node coordinate to find an adjacent tile to, int\n :return: tile identifier of an adjacent tile, ...
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...
rosshamish/hexgrid
hexgrid.py
coastal_coords
python
def coastal_coords(): coast = list() for tile_id in coastal_tile_ids(): tile_coord = tile_id_to_coord(tile_id) for edge_coord in coastal_edges(tile_id): dirn = tile_edge_offset_to_direction(edge_coord - tile_coord) if tile_id_in_direction(tile_id, dirn) is None: ...
A coastal coord is a 2-tuple: (tile id, direction). An edge is coastal if it is on the grid's border. :return: list( (tile_id, direction) )
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L128-L144
[ "def tile_id_to_coord(tile_id):\n \"\"\"\n Convert a tile identifier to its corresponding grid coordinate.\n\n :param tile_id: tile identifier, Tile.tile_id\n :return: coordinate of the tile, int\n \"\"\"\n try:\n return _tile_id_to_coord[tile_id]\n except KeyError:\n logging.crit...
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...
rosshamish/hexgrid
hexgrid.py
coastal_edges
python
def coastal_edges(tile_id): edges = list() tile_coord = tile_id_to_coord(tile_id) for edge_coord in edges_touching_tile(tile_id): dirn = tile_edge_offset_to_direction(edge_coord - tile_coord) if tile_id_in_direction(tile_id, dirn) is None: edges.append(edge_coord) return edge...
Returns a list of coastal edge coordinate. An edge is coastal if it is on the grid's border. :return: list(int)
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L147-L160
[ "def tile_id_to_coord(tile_id):\n \"\"\"\n Convert a tile identifier to its corresponding grid coordinate.\n\n :param tile_id: tile identifier, Tile.tile_id\n :return: coordinate of the tile, int\n \"\"\"\n try:\n return _tile_id_to_coord[tile_id]\n except KeyError:\n logging.crit...
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...
rosshamish/hexgrid
hexgrid.py
tile_id_in_direction
python
def tile_id_in_direction(from_tile_id, direction): coord_from = tile_id_to_coord(from_tile_id) for offset, dirn in _tile_tile_offsets.items(): if dirn == direction: coord_to = coord_from + offset if coord_to in legal_tile_coords(): return tile_id_from_coord(coord_...
Variant on direction_to_tile. Returns None if there's no tile there. :param from_tile_id: tile identifier, int :param direction: str :return: tile identifier, int or None
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L163-L177
[ "def tile_id_to_coord(tile_id):\n \"\"\"\n Convert a tile identifier to its corresponding grid coordinate.\n\n :param tile_id: tile identifier, Tile.tile_id\n :return: coordinate of the tile, int\n \"\"\"\n try:\n return _tile_id_to_coord[tile_id]\n except KeyError:\n logging.crit...
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...
rosshamish/hexgrid
hexgrid.py
direction_to_tile
python
def direction_to_tile(from_tile_id, to_tile_id): coord_from = tile_id_to_coord(from_tile_id) coord_to = tile_id_to_coord(to_tile_id) direction = tile_tile_offset_to_direction(coord_to - coord_from) # logging.debug('Tile direction: {}->{} is {}'.format( # from_tile.tile_id, # to_tile.tile...
Convenience method wrapping tile_tile_offset_to_direction. Used to get the direction of the offset between two tiles. The tiles must be adjacent. :param from_tile_id: tile identifier, int :param to_tile_id: tile identifier, int :return: direction from from_tile to to_tile, str
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L180-L197
[ "def tile_id_to_coord(tile_id):\n \"\"\"\n Convert a tile identifier to its corresponding grid coordinate.\n\n :param tile_id: tile identifier, Tile.tile_id\n :return: coordinate of the tile, int\n \"\"\"\n try:\n return _tile_id_to_coord[tile_id]\n except KeyError:\n logging.crit...
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...
rosshamish/hexgrid
hexgrid.py
edge_coord_in_direction
python
def edge_coord_in_direction(tile_id, direction): tile_coord = tile_id_to_coord(tile_id) for edge_coord in edges_touching_tile(tile_id): if tile_edge_offset_to_direction(edge_coord - tile_coord) == direction: return edge_coord raise ValueError('No edge found in direction={} at tile_id={}'...
Returns the edge coordinate in the given direction at the given tile identifier. :param tile_id: tile identifier, int :param direction: direction, str :return: edge coord, int
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L242-L257
[ "def tile_id_to_coord(tile_id):\n \"\"\"\n Convert a tile identifier to its corresponding grid coordinate.\n\n :param tile_id: tile identifier, Tile.tile_id\n :return: coordinate of the tile, int\n \"\"\"\n try:\n return _tile_id_to_coord[tile_id]\n except KeyError:\n logging.crit...
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...
rosshamish/hexgrid
hexgrid.py
node_coord_in_direction
python
def node_coord_in_direction(tile_id, direction): tile_coord = tile_id_to_coord(tile_id) for node_coord in nodes_touching_tile(tile_id): if tile_node_offset_to_direction(node_coord - tile_coord) == direction: return node_coord raise ValueError('No node found in direction={} at tile_id={}'...
Returns the node coordinate in the given direction at the given tile identifier. :param tile_id: tile identifier, int :param direction: direction, str :return: node coord, int
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L260-L275
[ "def tile_node_offset_to_direction(offset):\n \"\"\"\n Get the cardinal direction of a tile-node offset. The tile and node must be adjacent.\n\n :param offset: node_coord - tile_coord, int\n :return: direction of the offset, str\n \"\"\"\n try:\n return _tile_node_offsets[offset]\n excep...
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...
rosshamish/hexgrid
hexgrid.py
tile_id_from_coord
python
def tile_id_from_coord(coord): for i, c in _tile_id_to_coord.items(): if c == coord: return i raise Exception('Tile id lookup failed, coord={} not found in map'.format(hex(coord)))
Convert a tile coordinate to its corresponding tile identifier. :param coord: coordinate of the tile, int :return: tile identifier, Tile.tile_id
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L293-L303
null
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...
rosshamish/hexgrid
hexgrid.py
nearest_tile_to_edge_using_tiles
python
def nearest_tile_to_edge_using_tiles(tile_ids, edge_coord): for tile_id in tile_ids: if edge_coord - tile_id_to_coord(tile_id) in _tile_edge_offsets.keys(): return tile_id logging.critical('Did not find a tile touching edge={}'.format(edge_coord))
Get the first tile found adjacent to the given edge. Returns a tile identifier. :param tile_ids: tiles to look at for adjacency, list(Tile.tile_id) :param edge_coord: edge coordinate to find an adjacent tile to, int :return: tile identifier of an adjacent tile, Tile.tile_id
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L317-L328
[ "def tile_id_to_coord(tile_id):\n \"\"\"\n Convert a tile identifier to its corresponding grid coordinate.\n\n :param tile_id: tile identifier, Tile.tile_id\n :return: coordinate of the tile, int\n \"\"\"\n try:\n return _tile_id_to_coord[tile_id]\n except KeyError:\n logging.crit...
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...
rosshamish/hexgrid
hexgrid.py
nearest_tile_to_node_using_tiles
python
def nearest_tile_to_node_using_tiles(tile_ids, node_coord): for tile_id in tile_ids: if node_coord - tile_id_to_coord(tile_id) in _tile_node_offsets.keys(): return tile_id logging.critical('Did not find a tile touching node={}'.format(node_coord))
Get the first tile found adjacent to the given node. Returns a tile identifier. :param tile_ids: tiles to look at for adjacency, list(Tile.tile_id) :param node_coord: node coordinate to find an adjacent tile to, int :return: tile identifier of an adjacent tile, Tile.tile_id
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L342-L353
[ "def tile_id_to_coord(tile_id):\n \"\"\"\n Convert a tile identifier to its corresponding grid coordinate.\n\n :param tile_id: tile identifier, Tile.tile_id\n :return: coordinate of the tile, int\n \"\"\"\n try:\n return _tile_id_to_coord[tile_id]\n except KeyError:\n logging.crit...
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...
rosshamish/hexgrid
hexgrid.py
edges_touching_tile
python
def edges_touching_tile(tile_id): coord = tile_id_to_coord(tile_id) edges = [] for offset in _tile_edge_offsets.keys(): edges.append(coord + offset) # logging.debug('tile_id={}, edges touching={}'.format(tile_id, edges)) return edges
Get a list of edge coordinates touching the given tile. :param tile_id: tile identifier, Tile.tile_id :return: list of edge coordinates touching the given tile, list(int)
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L356-L368
[ "def tile_id_to_coord(tile_id):\n \"\"\"\n Convert a tile identifier to its corresponding grid coordinate.\n\n :param tile_id: tile identifier, Tile.tile_id\n :return: coordinate of the tile, int\n \"\"\"\n try:\n return _tile_id_to_coord[tile_id]\n except KeyError:\n logging.crit...
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...
rosshamish/hexgrid
hexgrid.py
nodes_touching_tile
python
def nodes_touching_tile(tile_id): coord = tile_id_to_coord(tile_id) nodes = [] for offset in _tile_node_offsets.keys(): nodes.append(coord + offset) # logging.debug('tile_id={}, nodes touching={}'.format(tile_id, nodes)) return nodes
Get a list of node coordinates touching the given tile. :param tile_id: tile identifier, Tile.tile_id :return: list of node coordinates touching the given tile, list(int)
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L371-L383
[ "def tile_id_to_coord(tile_id):\n \"\"\"\n Convert a tile identifier to its corresponding grid coordinate.\n\n :param tile_id: tile identifier, Tile.tile_id\n :return: coordinate of the tile, int\n \"\"\"\n try:\n return _tile_id_to_coord[tile_id]\n except KeyError:\n logging.crit...
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...