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
rbarrois/confutils
confutils/configfile.py
ConfigFile._get_section
python
def _get_section(self, name, create=True): try: return self.sections[name] except KeyError: if not create: raise section = Section(name) self.sections[name] = section return section
Retrieve a section by name. Create it on first access.
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L339-L349
null
class ConfigFile(object): """A (hopefully writable) config file. Attributes: sections (dict(name => Section)): sections of the file blocks (SectionBlock list): blocks from the file header (ConfigLineList): list of lines before the first section current_block (SectionBlock): curr...
rbarrois/confutils
confutils/configfile.py
ConfigFile.get_line
python
def get_line(self, section, line): try: section = self._get_section(section, create=False) except KeyError: return [] return section.find_lines(line)
Retrieve all lines compatible with a given line.
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L358-L364
[ "def _get_section(self, name, create=True):\n \"\"\"Retrieve a section by name. Create it on first access.\"\"\"\n try:\n return self.sections[name]\n except KeyError:\n if not create:\n raise\n\n section = Section(name)\n self.sections[name] = section\n return...
class ConfigFile(object): """A (hopefully writable) config file. Attributes: sections (dict(name => Section)): sections of the file blocks (SectionBlock list): blocks from the file header (ConfigLineList): list of lines before the first section current_block (SectionBlock): curr...
rbarrois/confutils
confutils/configfile.py
ConfigFile.iter_lines
python
def iter_lines(self, section): try: section = self._get_section(section, create=False) except KeyError: return for block in section: for line in block: yield line
Iterate over all lines in a section. This will skip 'header' lines.
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L366-L378
[ "def _get_section(self, name, create=True):\n \"\"\"Retrieve a section by name. Create it on first access.\"\"\"\n try:\n return self.sections[name]\n except KeyError:\n if not create:\n raise\n\n section = Section(name)\n self.sections[name] = section\n return...
class ConfigFile(object): """A (hopefully writable) config file. Attributes: sections (dict(name => Section)): sections of the file blocks (SectionBlock list): blocks from the file header (ConfigLineList): list of lines before the first section current_block (SectionBlock): curr...
rbarrois/confutils
confutils/configfile.py
ConfigFile.enter_block
python
def enter_block(self, name): section = self._get_section(name) block = self.current_block = section.new_block() self.blocks.append(block) return block
Mark 'entering a block'.
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L383-L388
[ "def new_block(self, **kwargs):\n block = SectionBlock(self.name, **kwargs)\n self.blocks.append(block)\n return block\n", "def _get_section(self, name, create=True):\n \"\"\"Retrieve a section by name. Create it on first access.\"\"\"\n try:\n return self.sections[name]\n except KeyError...
class ConfigFile(object): """A (hopefully writable) config file. Attributes: sections (dict(name => Section)): sections of the file blocks (SectionBlock list): blocks from the file header (ConfigLineList): list of lines before the first section current_block (SectionBlock): curr...
rbarrois/confutils
confutils/configfile.py
ConfigFile.insert_line
python
def insert_line(self, line): if self.current_block is not None: self.current_block.append(line) else: self.header.append(line)
Insert a new line
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L390-L395
[ "def append(self, line):\n self.lines.append(line)\n" ]
class ConfigFile(object): """A (hopefully writable) config file. Attributes: sections (dict(name => Section)): sections of the file blocks (SectionBlock list): blocks from the file header (ConfigLineList): list of lines before the first section current_block (SectionBlock): curr...
rbarrois/confutils
confutils/configfile.py
ConfigFile.handle_line
python
def handle_line(self, line): if line.kind == ConfigLine.KIND_HEADER: self.enter_block(line.header) else: self.insert_line(line)
Read one line.
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L397-L402
[ "def enter_block(self, name):\n \"\"\"Mark 'entering a block'.\"\"\"\n section = self._get_section(name)\n block = self.current_block = section.new_block()\n self.blocks.append(block)\n return block\n", "def insert_line(self, line):\n \"\"\"Insert a new line\"\"\"\n if self.current_block is n...
class ConfigFile(object): """A (hopefully writable) config file. Attributes: sections (dict(name => Section)): sections of the file blocks (SectionBlock list): blocks from the file header (ConfigLineList): list of lines before the first section current_block (SectionBlock): curr...
rbarrois/confutils
confutils/configfile.py
ConfigFile.parse
python
def parse(self, fileobj, name_hint='', parser=None): self.current_block = None # Reset current block parser = parser or Parser() for line in parser.parse(fileobj, name_hint=name_hint): self.handle_line(line)
Fill from a file-like object.
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L404-L409
[ "def handle_line(self, line):\n \"\"\"Read one line.\"\"\"\n if line.kind == ConfigLine.KIND_HEADER:\n self.enter_block(line.header)\n else:\n self.insert_line(line)\n" ]
class ConfigFile(object): """A (hopefully writable) config file. Attributes: sections (dict(name => Section)): sections of the file blocks (SectionBlock list): blocks from the file header (ConfigLineList): list of lines before the first section current_block (SectionBlock): curr...
rbarrois/confutils
confutils/configfile.py
ConfigFile.update_line
python
def update_line(self, section, old_line, new_line, once=False): try: s = self._get_section(section, create=False) except KeyError: return 0 return s.update(old_line, new_line, once=once)
Replace all lines matching `old_line` with `new_line`. If ``once`` is set to True, remove only the first instance. Returns: int: the number of updates performed
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L434-L446
[ "def _get_section(self, name, create=True):\n \"\"\"Retrieve a section by name. Create it on first access.\"\"\"\n try:\n return self.sections[name]\n except KeyError:\n if not create:\n raise\n\n section = Section(name)\n self.sections[name] = section\n return...
class ConfigFile(object): """A (hopefully writable) config file. Attributes: sections (dict(name => Section)): sections of the file blocks (SectionBlock list): blocks from the file header (ConfigLineList): list of lines before the first section current_block (SectionBlock): curr...
rbarrois/confutils
confutils/configfile.py
ConfigFile.remove_line
python
def remove_line(self, section, line): try: s = self._get_section(section, create=False) except KeyError: # No such section, skip. return 0 return s.remove(line)
Remove all instances of a line. Returns: int: the number of lines removed
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L448-L460
[ "def _get_section(self, name, create=True):\n \"\"\"Retrieve a section by name. Create it on first access.\"\"\"\n try:\n return self.sections[name]\n except KeyError:\n if not create:\n raise\n\n section = Section(name)\n self.sections[name] = section\n return...
class ConfigFile(object): """A (hopefully writable) config file. Attributes: sections (dict(name => Section)): sections of the file blocks (SectionBlock list): blocks from the file header (ConfigLineList): list of lines before the first section current_block (SectionBlock): curr...
rbarrois/confutils
confutils/configfile.py
ConfigFile.items
python
def items(self, section): for line in self.iter_lines(section): if line.kind == ConfigLine.KIND_DATA: yield line.key, line.value
Retrieve all key/value pairs for a given section.
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L468-L472
[ "def iter_lines(self, section):\n \"\"\"Iterate over all lines in a section.\n\n This will skip 'header' lines.\n \"\"\"\n try:\n section = self._get_section(section, create=False)\n except KeyError:\n return\n\n for block in section:\n for line in block:\n yield li...
class ConfigFile(object): """A (hopefully writable) config file. Attributes: sections (dict(name => Section)): sections of the file blocks (SectionBlock list): blocks from the file header (ConfigLineList): list of lines before the first section current_block (SectionBlock): curr...
rbarrois/confutils
confutils/configfile.py
ConfigFile.get
python
def get(self, section, key): line = self._make_line(key) for line in self.get_line(section, line): yield line.value
Return the 'value' of all lines matching the section/key. Yields: values for matching lines.
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L474-L482
[ "def get_line(self, section, line):\n \"\"\"Retrieve all lines compatible with a given line.\"\"\"\n try:\n section = self._get_section(section, create=False)\n except KeyError:\n return []\n return section.find_lines(line)\n", "def _make_line(self, key, value=None):\n return ConfigLi...
class ConfigFile(object): """A (hopefully writable) config file. Attributes: sections (dict(name => Section)): sections of the file blocks (SectionBlock list): blocks from the file header (ConfigLineList): list of lines before the first section current_block (SectionBlock): curr...
rbarrois/confutils
confutils/configfile.py
ConfigFile.get_one
python
def get_one(self, section, key): lines = iter(self.get(section, key)) try: return next(lines) except StopIteration: raise KeyError("Key %s not found in %s" % (key, section))
Retrieve the first value for a section/key. Raises: KeyError: If no line match the given section/key.
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L484-L494
[ "def get(self, section, key):\n \"\"\"Return the 'value' of all lines matching the section/key.\n\n Yields:\n values for matching lines.\n \"\"\"\n line = self._make_line(key)\n for line in self.get_line(section, line):\n yield line.value\n" ]
class ConfigFile(object): """A (hopefully writable) config file. Attributes: sections (dict(name => Section)): sections of the file blocks (SectionBlock list): blocks from the file header (ConfigLineList): list of lines before the first section current_block (SectionBlock): curr...
rbarrois/confutils
confutils/configfile.py
ConfigFile.add_or_update
python
def add_or_update(self, section, key, value): updates = self.update(section, key, value) if updates == 0: self.add(section, key, value) return updates
Update the key or, if no previous value existed, add it. Returns: int: Number of updated lines.
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L500-L509
[ "def add(self, section, key, value):\n line = self._make_line(key, value)\n return self.add_line(section, line)\n", "def update(self, section, key, new_value, old_value=None, once=False):\n old_line = self._make_line(key, old_value)\n new_line = self._make_line(key, new_value)\n return self.update_...
class ConfigFile(object): """A (hopefully writable) config file. Attributes: sections (dict(name => Section)): sections of the file blocks (SectionBlock list): blocks from the file header (ConfigLineList): list of lines before the first section current_block (SectionBlock): curr...
rbarrois/confutils
confutils/merged_config.py
MergedConfig.get
python
def get(self, key, default=NoDefault): key = normalize_key(key) if default is NoDefault: defaults = [] else: defaults = [default] for options in self.options: try: value = options[key] except KeyError: conti...
Retrieve a value from its key. Retrieval steps are: 1) Normalize the key 2) For each option group: a) Retrieve the value at that key b) If no value exists, continue c) If the value is an instance of 'Default', continue d) Otherwise, return the value ...
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/merged_config.py#L92-L126
[ "def normalize_key(key):\n \"\"\"Normalize a config key.\n\n Returns the same key, with only lower-case characters and no '-'.\n \"\"\"\n return key.lower().replace('-', '_')\n" ]
class MergedConfig(object): """A merged configuration holder. Merges options from a set of dicts.""" def __init__(self, *options, **kwargs): self.options = [] for option in options: self.add_options(option) def add_options(self, options, normalize=True): if normali...
rbarrois/confutils
confutils/configreader.py
ConfigReader.parse_file
python
def parse_file(self, filename, skip_unreadable=False): if not os.access(filename, os.R_OK): if skip_unreadable: return raise ConfigReadingError("Unable to open file %s." % filename) with open(filename, 'rt') as f: return self.parse(f, name_hint=filenam...
Parse a file from its name (instead of fds). If skip_unreadable is False and the file can't be read, will raise a ConfigReadingError.
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configreader.py#L127-L138
[ "def parse(self, f, name_hint=''):\n self.enter_section('core')\n\n for lineno, line in enumerate(f):\n line = line.strip()\n if self.re_section_header.match(line):\n section_name = line[1:-1]\n self.enter_section(section_name)\n elif self.re_blank_line.match(line):\...
class ConfigReader(object): re_section_header = re.compile(r'^\[[\w._-]+\]$') re_blank_line = re.compile(r'^(#.*)?$') re_normal_line = re.compile(r'^([^:=]+)[:=](.*)$') def __init__(self, multi_valued_sections=()): self.sections = {} self.multi_valued_sections = multi_valued_sections ...
20tab/twentytab-tree
tree/menu.py
Menu.as_ul
python
def as_ul(self, current_linkable=False, class_current="active_link", before_1="", after_1="", before_all="", after_all=""): return self.__do_menu("as_ul", current_linkable, class_current, before_1=before_1, after_1=after_1, before_all=before_all, after_all=after_all)
It returns menu as ul
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/menu.py#L68-L74
[ "def __do_menu(self, menu_as, current_linkable=False, class_current=\"\",\n chars=\"\", before_1=\"\", after_1=\"\", before_all=\"\",\n after_all=\"\", render=True):\n nodes = self.root.get_descendants()\n list_nodes = prepare_nodes(list(nodes), self.request)\n\n if not render:\n ...
class Menu(object): """ This class provides some tools to create and render tree structure menu in according to nodes' structure created for your application. It takes some arguments: - request: simply http request - root: the root of menu (it's hidden in menu string) - upy_context: it conta...
20tab/twentytab-tree
tree/menu.py
Menu.as_string
python
def as_string(self, chars, current_linkable=False, class_current="active_link"): return self.__do_menu("as_string", current_linkable, class_current, chars)
It returns menu as string
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/menu.py#L82-L86
[ "def __do_menu(self, menu_as, current_linkable=False, class_current=\"\",\n chars=\"\", before_1=\"\", after_1=\"\", before_all=\"\",\n after_all=\"\", render=True):\n nodes = self.root.get_descendants()\n list_nodes = prepare_nodes(list(nodes), self.request)\n\n if not render:\n ...
class Menu(object): """ This class provides some tools to create and render tree structure menu in according to nodes' structure created for your application. It takes some arguments: - request: simply http request - root: the root of menu (it's hidden in menu string) - upy_context: it conta...
20tab/twentytab-tree
tree/menu.py
Breadcrumb.as_ul
python
def as_ul(self, show_leaf=True, current_linkable=False, class_current="active_link"): return self.__do_menu("as_ul", show_leaf, current_linkable, class_current)
It returns breadcrumb as ul
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/menu.py#L132-L136
[ "def __do_menu(self, menu_as, show_leaf, current_linkable, class_current, chars=\"\", render=True):\n nodes = self.leaf.get_ancestors()[1:]\n list_nodes = list(nodes)\n if show_leaf:\n list_nodes.append(self.leaf)\n\n list_nodes = prepare_nodes(list_nodes, self.request)\n\n if not render:\n ...
class Breadcrumb(object): """ This class provides some tools to create and render tree structure breadcrumb in according to nodes' structure created for your application. It takes some arguments: - request: simply http request - leaf: the the leaf of breadcrumb (it's hidden in menu string) -...
20tab/twentytab-tree
tree/menu.py
Breadcrumb.as_p
python
def as_p(self, show_leaf=True, current_linkable=False, class_current="active_link"): return self.__do_menu("as_p", show_leaf, current_linkable, class_current)
It returns breadcrumb as p
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/menu.py#L138-L142
[ "def __do_menu(self, menu_as, show_leaf, current_linkable, class_current, chars=\"\", render=True):\n nodes = self.leaf.get_ancestors()[1:]\n list_nodes = list(nodes)\n if show_leaf:\n list_nodes.append(self.leaf)\n\n list_nodes = prepare_nodes(list_nodes, self.request)\n\n if not render:\n ...
class Breadcrumb(object): """ This class provides some tools to create and render tree structure breadcrumb in according to nodes' structure created for your application. It takes some arguments: - request: simply http request - leaf: the the leaf of breadcrumb (it's hidden in menu string) -...
20tab/twentytab-tree
tree/menu.py
Breadcrumb.as_string
python
def as_string(self, chars, show_leaf=True, current_linkable=False, class_current="active_link"): return self.__do_menu("as_string", show_leaf, current_linkable, class_current, chars)
It returns breadcrumb as string
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/menu.py#L144-L148
[ "def __do_menu(self, menu_as, show_leaf, current_linkable, class_current, chars=\"\", render=True):\n nodes = self.leaf.get_ancestors()[1:]\n list_nodes = list(nodes)\n if show_leaf:\n list_nodes.append(self.leaf)\n\n list_nodes = prepare_nodes(list_nodes, self.request)\n\n if not render:\n ...
class Breadcrumb(object): """ This class provides some tools to create and render tree structure breadcrumb in according to nodes' structure created for your application. It takes some arguments: - request: simply http request - leaf: the the leaf of breadcrumb (it's hidden in menu string) -...
20tab/twentytab-tree
tree/utility.py
getUrlList
python
def getUrlList(): """ IF YOU WANT REBUILD YOUR STRUCTURE UNCOMMENT THE FOLLOWING LINE """ #Node.rebuild() set_to_return = [] set_url = [] roots = Node.objects.filter(parent__isnull=True) for root in roots: nodes = root.get_descendants() for node in nodes: if...
This function get the Page List from the DB and return the tuple to use in the urls.py, urlpatterns
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/utility.py#L9-L45
null
from django.conf.urls import url from django.conf import settings from django.template import RequestContext from django.template.loader import render_to_string from tree.models import Node from datetime import date class UrlSitemap(object): """ It defines sitemap url's structure to make sitemap.xml file ...
20tab/twentytab-tree
tree/models.py
list_apps
python
def list_apps(): return [(d.split('.')[-1], d.split('.')[-1]) for d in os.listdir( os.getcwd()) if is_app(u"{}/{}".format(os.getcwd(), d))]
It returns a list of application contained in PROJECT_APPS
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L291-L296
null
from django.db import models from django.utils.translation import ugettext_lazy as _ from mptt.models import MPTTModel, TreeForeignKey, TreeManager from django.conf import settings from django.contrib.auth.models import Group from ast import literal_eval import os from twentytab.fields import NullTrueField from . impor...
20tab/twentytab-tree
tree/models.py
Node.slug
python
def slug(self): if self.is_root_node(): return "" if self.slugable and self.parent.parent: if not self.page.regex or (self.page.regex and not self.page.show_regex) or self.is_leaf_node(): return u"{0}/{1}".format(self.parent.slug, self.page.slug) elif ...
It returns node's slug
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L97-L117
null
class Node(MPTTModel): """ This is the class that defines tree's nodes. """ _default_manager = NodeManager() name = models.CharField(max_length=50, help_text=_(u"Identifying name of the associated page."), verbose_name=_(u"Name")) page = models.ForeignKey(u"Page", n...
20tab/twentytab-tree
tree/models.py
Node.slugable
python
def slugable(self): if self.page: if self.is_leaf_node(): return True if not self.is_leaf_node() and not self.page.regex: return True if not self.is_leaf_node() and self.page.regex and not self.page.show_regex: return True ...
A node is slugable in following cases: 1 - Node doesn't have children. 2 - Node has children but its page doesn't have a regex. 3 - Node has children, its page has regex but it doesn't show it. 4 - Node has children, its page shows his regex and node has a default value for regex. ...
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L120-L140
null
class Node(MPTTModel): """ This is the class that defines tree's nodes. """ _default_manager = NodeManager() name = models.CharField(max_length=50, help_text=_(u"Identifying name of the associated page."), verbose_name=_(u"Name")) page = models.ForeignKey(u"Page", n...
20tab/twentytab-tree
tree/models.py
Node.get_pattern
python
def get_pattern(self): if self.is_root_node(): return "" else: parent_pattern = self.parent.get_pattern() if parent_pattern != "": parent_pattern = u"{}".format(parent_pattern) if not self.page and not self.is_leaf_node(): i...
It returns its url pattern
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L142-L165
null
class Node(MPTTModel): """ This is the class that defines tree's nodes. """ _default_manager = NodeManager() name = models.CharField(max_length=50, help_text=_(u"Identifying name of the associated page."), verbose_name=_(u"Name")) page = models.ForeignKey(u"Page", n...
20tab/twentytab-tree
tree/models.py
Node.presentation_type
python
def presentation_type(self): if self.page and self.page.presentation_type: return self.page.presentation_type return ""
It returns page's presentation_type
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L174-L180
null
class Node(MPTTModel): """ This is the class that defines tree's nodes. """ _default_manager = NodeManager() name = models.CharField(max_length=50, help_text=_(u"Identifying name of the associated page."), verbose_name=_(u"Name")) page = models.ForeignKey(u"Page", n...
20tab/twentytab-tree
tree/models.py
Page.view_path
python
def view_path(self): if self.scheme_name is None or self.scheme_name == "": return self.view.view_path else: return self.scheme_name
It returns view's view path
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L238-L245
null
class Page(models.Model): """ This is the class that defines a page of the structure. """ #objects = PageManager() name = models.CharField(max_length=50, unique=True, help_text=_(u"Identifying page's name."), verbose_name=_(u"Name")) slug = models.SlugField(max_lengt...
20tab/twentytab-tree
tree/models.py
Page.get_absolute_url
python
def get_absolute_url(self): try: node = Node.objects.select_related().filter(page=self)[0] return node.get_absolute_url() except Exception, e: raise ValueError(u"Error in {0}.{1}: {2}".format(self.__module__, self.__class__.__name__, e)) return u""
It returns absolute url defined by node related to this page
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L247-L256
null
class Page(models.Model): """ This is the class that defines a page of the structure. """ #objects = PageManager() name = models.CharField(max_length=50, unique=True, help_text=_(u"Identifying page's name."), verbose_name=_(u"Name")) slug = models.SlugField(max_lengt...
20tab/twentytab-tree
tree/models.py
Page.check_static_vars
python
def check_static_vars(self, node): if self.static_vars == "" and hasattr(self, "template"): self.static_vars = { 'upy_context': { 'template_name': u"{}/{}".format(self.template.app_name, self.template.file_name) } } elif hasattr...
This function check if a Page has static vars
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L258-L274
null
class Page(models.Model): """ This is the class that defines a page of the structure. """ #objects = PageManager() name = models.CharField(max_length=50, unique=True, help_text=_(u"Identifying page's name."), verbose_name=_(u"Name")) slug = models.SlugField(max_lengt...
20tab/twentytab-tree
tree/models.py
View.view_path
python
def view_path(self): return u"{0}.{1}.{2}".format(self.app_name, self.module_name, self.func_name)
It returns view_path as string like: 'app_name.module_mane.func_name'
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L373-L377
null
class View(models.Model): """ It defines view object and it's used to write view definition in views.py module """ name = models.CharField(max_length=100, help_text=_(u"Set the view's name."), verbose_name=_(u"Name")) app_name = models.CharField(max_length=100, help_text=_(u"Set the application's na...
20tab/twentytab-tree
tree/views.py
tree_render
python
def tree_render(request, upy_context, vars_dictionary): page = upy_context['PAGE'] return render_to_response(page.template.file_name, vars_dictionary, context_instance=RequestContext(request))
It renders template defined in upy_context's page passed in arguments
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/views.py#L8-L13
null
from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from tree.utility import RobotTXT, Sitemap from django.conf import settings def view_404(request, url=None): """ It returns a 404 http response """ res...
20tab/twentytab-tree
tree/views.py
view_404
python
def view_404(request, url=None): res = render_to_response("404.html", {"PAGE_URL": request.get_full_path()}, context_instance=RequestContext(request)) res.status_code = 404 return res
It returns a 404 http response
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/views.py#L16-L23
null
from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from tree.utility import RobotTXT, Sitemap from django.conf import settings def tree_render(request, upy_context, vars_dictionary): """ It renders template defi...
20tab/twentytab-tree
tree/views.py
view_500
python
def view_500(request, url=None): res = render_to_response("500.html", context_instance=RequestContext(request)) res.status_code = 500 return res
it returns a 500 http response
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/views.py#L26-L32
null
from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from tree.utility import RobotTXT, Sitemap from django.conf import settings def tree_render(request, upy_context, vars_dictionary): """ It renders template defi...
20tab/twentytab-tree
tree/views.py
favicon
python
def favicon(request): favicon = u"{}tree/images/favicon.ico".format(settings.STATIC_URL) try: from seo.models import MetaSite site = MetaSite.objects.get(default=True) return HttpResponseRedirect(site.favicon.url) except: return HttpResponseRedirect(favicon)
It returns favicon's location
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/views.py#L51-L61
null
from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from tree.utility import RobotTXT, Sitemap from django.conf import settings def tree_render(request, upy_context, vars_dictionary): """ It renders template defi...
20tab/twentytab-tree
tree/template_context/context_processors.py
set_meta
python
def set_meta(request): context_extras = {} if not request.is_ajax() and hasattr(request, 'upy_context') and request.upy_context['PAGE']: context_extras['PAGE'] = request.upy_context['PAGE'] context_extras['NODE'] = request.upy_context['NODE'] return context_extras
This context processor returns meta informations contained in cached files. If there aren't cache it calculates dictionary to return
train
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/template_context/context_processors.py#L1-L10
null
inspirehep/plotextractor
plotextractor/extractor.py
get_context
python
def get_context(lines, backwards=False): tex_tag = re.compile(r".*\\(\w+).*") sentence = re.compile(r"(?<=[.?!])[\s]+(?=[A-Z])") context = [] word_list = lines.split() if backwards: word_list.reverse() # For each word we do the following: # 1. Check if we have reached word limit ...
Get context. Given a relevant string from a TeX file, this function will extract text from it as far as it is deemed contextually relevant, either backwards or forwards in the text. The level of relevance allowed is configurable. When it reaches some point in the text that is determined to be out o...
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/extractor.py#L55-L115
null
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2014, 2015 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License,...
inspirehep/plotextractor
plotextractor/extractor.py
extract_context
python
def extract_context(tex_file, extracted_image_data): if os.path.isdir(tex_file) or not os.path.exists(tex_file): return [] lines = "".join(get_lines_from_file(tex_file)) # Generate context for each image and its assoc. labels for data in extracted_image_data: context_list = [] ...
Extract context. Given a .tex file and a label name, this function will extract the text before and after for all the references made to this label in the text. The number of characters to extract before and after is configurable. :param tex_file (list): path to .tex file :param extracted_image_da...
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/extractor.py#L118-L165
null
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2014, 2015 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License,...
inspirehep/plotextractor
plotextractor/extractor.py
extract_captions
python
def extract_captions(tex_file, sdir, image_list, primary=True): if os.path.isdir(tex_file) or not os.path.exists(tex_file): return [] lines = get_lines_from_file(tex_file) # possible figure lead-ins figure_head = u'\\begin{figure' # also matches figure* figure_wrap_head = u'\\begin{wrapfi...
Extract captions. Take the TeX file and the list of images in the tarball (which all, presumably, are used in the TeX file) and figure out which captions in the text are associated with which images :param: lines (list): list of lines of the TeX file :param: tex_file (string): the name of the TeX ...
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/extractor.py#L168-L567
null
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2014, 2015 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License,...
inspirehep/plotextractor
plotextractor/extractor.py
put_it_together
python
def put_it_together(cur_image, caption, context, extracted_image_data, line_index, lines): if type(cur_image) == list: if cur_image[MAIN_CAPTION_OR_IMAGE] == 'ERROR': cur_image[MAIN_CAPTION_OR_IMAGE] = '' for image in cur_image[SUB_CAPTION_OR_IMAGE]: if im...
Put it together. Takes the current image(s) and caption(s) and assembles them into something useful in the extracted_image_data list. :param: cur_image (string || list): the image currently being dealt with, or the list of images, in the case of subimages :param: caption (string || list): the ...
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/extractor.py#L570-L771
[ "def assemble_caption(begin_line, begin_index, end_line, end_index, lines):\n \"\"\"\n Take the caption of a picture and put it all together\n in a nice way. If it spans multiple lines, put it on one line. If it\n contains controlled characters, strip them out. If it has tags we don't\n want to wo...
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2014, 2015 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License,...
inspirehep/plotextractor
plotextractor/extractor.py
intelligently_find_filenames
python
def intelligently_find_filenames(line, TeX=False, ext=False, commas_okay=False): files_included = ['ERROR'] if commas_okay: valid_for_filename = '\\s*[A-Za-z0-9\\-\\=\\+/\\\\_\\.,%#]+' else: valid_for_filename = '\\s*[A-Za-z0-9\\-\\=\\+/\\\\_\\.%#]+' if...
Intelligently find filenames. Find the filename in the line. We don't support all filenames! Just eps and ps for now. :param: line (string): the line we want to get a filename out of :return: filename ([string, ...]): what is probably the name of the file(s)
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/extractor.py#L774-L869
null
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2014, 2015 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License,...
inspirehep/plotextractor
plotextractor/extractor.py
get_lines_from_file
python
def get_lines_from_file(filepath, encoding="UTF-8"): try: fd = codecs.open(filepath, 'r', encoding) lines = fd.readlines() except UnicodeDecodeError: # Fall back to 'ISO-8859-1' fd = codecs.open(filepath, 'r', 'ISO-8859-1') lines = fd.readlines() finally: fd.c...
Return an iterator over lines.
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/extractor.py#L872-L883
null
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2014, 2015 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License,...
inspirehep/plotextractor
plotextractor/output_utils.py
find_open_and_close_braces
python
def find_open_and_close_braces(line_index, start, brace, lines): if brace in ['[', ']']: open_brace = '[' close_brace = ']' elif brace in ['{', '}']: open_brace = '{' close_brace = '}' elif brace in ['(', ')']: open_brace = '(' close_brace = ')' else: ...
Take the line where we want to start and the index where we want to start and find the first instance of matched open and close braces of the same type as brace in file file. :param: line (int): the index of the line we want to start searching at :param: start (int): the index in the line we want to st...
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/output_utils.py#L31-L116
null
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2014, 2015, 2016 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # Li...
inspirehep/plotextractor
plotextractor/output_utils.py
assemble_caption
python
def assemble_caption(begin_line, begin_index, end_line, end_index, lines): # stuff we don't like label_head = '\\label{' # reassemble that sucker if end_line > begin_line: # our caption spanned multiple lines caption = lines[begin_line][begin_index:] for included_line_index in...
Take the caption of a picture and put it all together in a nice way. If it spans multiple lines, put it on one line. If it contains controlled characters, strip them out. If it has tags we don't want to worry about, get rid of them, etc. :param: begin_line (int): the index of the line where the capt...
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/output_utils.py#L119-L168
[ "def find_open_and_close_braces(line_index, start, brace, lines):\n \"\"\"\n Take the line where we want to start and the index where we want to start\n and find the first instance of matched open and close braces of the same\n type as brace in file file.\n\n :param: line (int): the index of the line...
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2014, 2015, 2016 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # Li...
inspirehep/plotextractor
plotextractor/output_utils.py
prepare_image_data
python
def prepare_image_data(extracted_image_data, output_directory, image_mapping): img_list = {} for image, caption, label in extracted_image_data: if not image or image == 'ERROR': continue image_location = get_image_location( image, output...
Prepare and clean image-data from duplicates and other garbage. :param: extracted_image_data ([(string, string, list, list) ...], ...])): the images and their captions + contexts, ordered :param: tex_file (string): the location of the TeX (used for finding the associated images; the TeX is assu...
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/output_utils.py#L171-L211
[ "def get_image_location(image, sdir, image_list, recurred=False):\n \"\"\"Take a raw image name + directory and return the location of image.\n\n :param: image (string): the name of the raw image from the TeX\n :param: sdir (string): the directory where everything was unzipped to\n :param: image_list ([...
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2014, 2015, 2016 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # Li...
inspirehep/plotextractor
plotextractor/output_utils.py
get_image_location
python
def get_image_location(image, sdir, image_list, recurred=False): if isinstance(image, list): # image is a list, not good return None image = image.encode('utf-8', 'ignore') image = image.strip() figure_or_file = '(figure=|file=)' figure_or_file_in_image = re.findall(figure_or_file,...
Take a raw image name + directory and return the location of image. :param: image (string): the name of the raw image from the TeX :param: sdir (string): the directory where everything was unzipped to :param: image_list ([string, string, ...]): the list of images that were extracted from the tarbal...
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/output_utils.py#L214-L315
[ "def get_converted_image_name(image):\n \"\"\"Return the name of the image after it has been converted to png format.\n\n Strips off the old extension.\n\n :param: image (string): The fullpath of the image before conversion\n\n :return: converted_image (string): the fullpath of the image after convert\n...
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2014, 2015, 2016 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # Li...
inspirehep/plotextractor
plotextractor/output_utils.py
get_converted_image_name
python
def get_converted_image_name(image): png_extension = '.png' if image[(0 - len(png_extension)):] == png_extension: # it already ends in png! we're golden return image img_dir = os.path.split(image)[0] image = os.path.split(image)[-1] # cut off the old extension if len(image.sp...
Return the name of the image after it has been converted to png format. Strips off the old extension. :param: image (string): The fullpath of the image before conversion :return: converted_image (string): the fullpath of the image after convert
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/output_utils.py#L318-L344
null
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2014, 2015, 2016 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # Li...
inspirehep/plotextractor
plotextractor/output_utils.py
get_tex_location
python
def get_tex_location(new_tex_name, current_tex_name, recurred=False): tex_location = None current_dir = os.path.split(current_tex_name)[0] some_kind_of_tag = '\\\\\\w+ ' new_tex_name = new_tex_name.strip() if new_tex_name.startswith('input'): new_tex_name = new_tex_name[len('input'):] ...
Takes the name of a TeX file and attempts to match it to an actual file in the tarball. :param: new_tex_name (string): the name of the TeX file to find :param: current_tex_name (string): the location of the TeX file where we found the reference :return: tex_location (string): the location of t...
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/output_utils.py#L347-L412
null
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2014, 2015, 2016 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # Li...
inspirehep/plotextractor
plotextractor/output_utils.py
get_name_from_path
python
def get_name_from_path(full_path, root_path): relative_image_path = os.path.relpath(full_path, root_path) return "_".join(relative_image_path.split('.')[:-1]).replace('/', '_')\ .replace(';', '').replace(':', '')
Create a filename by merging path after root directory.
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/output_utils.py#L415-L419
null
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2014, 2015, 2016 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # Li...
inspirehep/plotextractor
plotextractor/api.py
process_tarball
python
def process_tarball(tarball, output_directory=None, context=False): if not output_directory: # No directory given, so we use the same path as the tarball output_directory = os.path.abspath("{0}_files".format(tarball)) extracted_files_list = untar(tarball, output_directory) image_list, tex_f...
Process one tarball end-to-end. If output directory is given, the tarball will be extracted there. Otherwise, it will extract it in a folder next to the tarball file. The function returns a list of dictionaries: .. code-block:: python [{ 'url': '/path/to/tarball_files/d15-120f3d....
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/api.py#L42-L83
[ "def convert_images(image_list, image_format=\"png\", timeout=20):\n \"\"\"Convert images from list of images to given format, if needed.\n\n Figure out the types of the images that were extracted from\n the tarball and determine how to convert them into PNG.\n\n :param: image_list ([string, string, ......
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2015 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your optio...
inspirehep/plotextractor
plotextractor/api.py
map_images_in_tex
python
def map_images_in_tex(tex_files, image_mapping, output_directory, context=False): extracted_image_data = [] for tex_file in tex_files: # Extract images, captions and labels based on tex file and images partly_extracted_image_data = extract_captions( tex_file, ...
Return caption and context for image references found in TeX sources.
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/api.py#L86-L110
[ "def extract_captions(tex_file, sdir, image_list, primary=True):\n \"\"\"Extract captions.\n\n Take the TeX file and the list of images in the tarball (which all,\n presumably, are used in the TeX file) and figure out which captions\n in the text are associated with which images\n :param: lines (list...
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2015 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your optio...
inspirehep/plotextractor
plotextractor/converter.py
untar
python
def untar(original_tarball, output_directory): if not tarfile.is_tarfile(original_tarball): raise InvalidTarball tarball = tarfile.open(original_tarball) # set mtimes of members to now epochsecs = int(time()) for member in tarball.getmembers(): member.mtime = epochsecs tarball.e...
Untar given tarball file into directory. Here we decide if our file is actually a tarball, then we untar it and return a list of extracted files. :param: tarball (string): the name of the tar file from arXiv :param: output_directory (string): the directory to untar in :return: list of absolute fi...
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/converter.py#L45-L79
null
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2015, 2016 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License,...
inspirehep/plotextractor
plotextractor/converter.py
detect_images_and_tex
python
def detect_images_and_tex( file_list, allowed_image_types=('eps', 'png', 'ps', 'jpg', 'pdf'), timeout=20): tex_file_extension = 'tex' image_list = [] might_be_tex = [] for extracted_file in file_list: # Ignore directories and hidden (metadata) files if os.path.i...
Detect from a list of files which are TeX or images. :param: file_list (list): list of absolute file paths :param: allowed_image_types (list): list of allows image formats :param: timeout (int): the timeout value on shell commands. :return: (image_list, tex_file) (([string, string, ...], string)): ...
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/converter.py#L82-L126
null
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2015, 2016 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License,...
inspirehep/plotextractor
plotextractor/converter.py
convert_images
python
def convert_images(image_list, image_format="png", timeout=20): png_output_contains = 'PNG image' image_mapping = {} for image_file in image_list: if os.path.isdir(image_file): continue if not os.path.exists(image_file): continue cmd_out = check_output(['fil...
Convert images from list of images to given format, if needed. Figure out the types of the images that were extracted from the tarball and determine how to convert them into PNG. :param: image_list ([string, string, ...]): the list of image files extracted from the tarball in step 1 :param: im...
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/converter.py#L129-L171
null
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2015, 2016 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License,...
inspirehep/plotextractor
plotextractor/converter.py
convert_image
python
def convert_image(from_file, to_file, image_format): with Image(filename=from_file) as original: with original.convert(image_format) as converted: converted.save(filename=to_file) return to_file
Convert an image to given format.
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/converter.py#L174-L179
null
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2015, 2016 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License,...
inspirehep/plotextractor
plotextractor/converter.py
rotate_image
python
def rotate_image(filename, line, sdir, image_list): file_loc = get_image_location(filename, sdir, image_list) degrees = re.findall('(angle=[-\\d]+|rotate=[-\\d]+)', line) if len(degrees) < 1: return False degrees = degrees[0].split('=')[-1].strip() if file_loc is None or file_loc == 'ERRO...
Rotate a image. Given a filename and a line, figure out what it is that the author wanted to do wrt changing the rotation of the image and convert the file so that this rotation is reflected in its presentation. :param: filename (string): the name of the file as specified in the TeX :param: line (...
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/converter.py#L182-L221
[ "def get_image_location(image, sdir, image_list, recurred=False):\n \"\"\"Take a raw image name + directory and return the location of image.\n\n :param: image (string): the name of the raw image from the TeX\n :param: sdir (string): the directory where everything was unzipped to\n :param: image_list ([...
# -*- coding: utf-8 -*- # # This file is part of plotextractor. # Copyright (C) 2010, 2011, 2015, 2016 CERN. # # plotextractor is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License,...
klmitch/framer
framer/transport.py
FramerAdaptor.factory
python
def factory(cls, client, *args, **kwargs): # Some basic sanity checks if not six.callable(client): raise exc.FramerException("Protocol factory is not a factory") # Cannot specify both positional and keyword arguments, but # must provide one or the other if not args ...
Generates and returns a callable suitable for passing as the ``protocol_factory`` parameter of the ``create_connection()`` or ``create_server()`` loop methods. This class method performs some sanity checks on the arguments, and is preferred over using a manually constructed ``lambda``. ...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L52-L88
null
class FramerAdaptor(object): """ The Framer transport adaptor class. Instances of this class--initialized with an appropriate ``FramedProtocol`` subclass, as well as send and receive framers--should be returned by the factory passed to the ``create_connection()`` or ``create_server()`` loop met...
klmitch/framer
framer/transport.py
FramerAdaptor._interpret_framer
python
def _interpret_framer(self, args, kwargs): # Cannot specify both positional and keyword arguments, but # must provide one or the other if not args and not kwargs: raise exc.InvalidFramerSpecification( "No framers specified") elif args and kwargs: ...
Interprets positional and keyword arguments related to framers. :param args: A tuple of positional arguments. The first such argument will be interpreted as a framer object, and the second will be interpreted as a framer state. :pa...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L131-L210
null
class FramerAdaptor(object): """ The Framer transport adaptor class. Instances of this class--initialized with an appropriate ``FramedProtocol`` subclass, as well as send and receive framers--should be returned by the factory passed to the ``create_connection()`` or ``create_server()`` loop met...
klmitch/framer
framer/transport.py
FramerAdaptor.connection_made
python
def connection_made(self, transport): # Save the underlying transport self._transport = transport # Call connection_made() on the client protocol, passing # ourself as the transport self._client.connection_made(self)
Called by the underlying transport when a connection is made. :param transport: The transport representing the connection.
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L212-L224
null
class FramerAdaptor(object): """ The Framer transport adaptor class. Instances of this class--initialized with an appropriate ``FramedProtocol`` subclass, as well as send and receive framers--should be returned by the factory passed to the ``create_connection()`` or ``create_server()`` loop met...
klmitch/framer
framer/transport.py
FramerAdaptor.data_received
python
def data_received(self, data): # First, add the data to the receive buffer self._recv_buf += data # Now, pass all frames we can find to the client protocol while self._recv_buf and not self._recv_paused: try: # Extract one frame frame = self....
Called by the underlying transport when data is received. :param data: The data received on the connection.
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L257-L278
null
class FramerAdaptor(object): """ The Framer transport adaptor class. Instances of this class--initialized with an appropriate ``FramedProtocol`` subclass, as well as send and receive framers--should be returned by the factory passed to the ``create_connection()`` or ``create_server()`` loop met...
klmitch/framer
framer/transport.py
FramerAdaptor.get_extra_info
python
def get_extra_info(self, name, default=None): # Handle data we know about if name in self._handlers: return self._handlers[name](self) # Call get_extra_info() on the transport return self._transport.get_extra_info(name, default=default)
Called by the client protocol to return optional transport information. Information requests not recognized by the ``FramerProtocol`` are passed on to the underlying transport. The values of ``name`` recognized directly by ``FramerProtocol`` are: =============== =============...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L307-L342
null
class FramerAdaptor(object): """ The Framer transport adaptor class. Instances of this class--initialized with an appropriate ``FramedProtocol`` subclass, as well as send and receive framers--should be returned by the factory passed to the ``create_connection()`` or ``create_server()`` loop met...
klmitch/framer
framer/transport.py
FramerAdaptor.resume_reading
python
def resume_reading(self): # Clear the read pause status self._recv_paused = False # Call resume_reading() on the transport self._transport.resume_reading() # If there's data in the receive buffer, pass it on to the # client protocol if self._recv_buf: ...
Called by the client protocol to resume the receiving end. The protocol's ``frame_received()`` method will be called once again if some data is available for reading.
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L358-L374
[ "def data_received(self, data):\n \"\"\"\n Called by the underlying transport when data is received.\n\n :param data: The data received on the connection.\n \"\"\"\n\n # First, add the data to the receive buffer\n self._recv_buf += data\n\n # Now, pass all frames we can find to the client proto...
class FramerAdaptor(object): """ The Framer transport adaptor class. Instances of this class--initialized with an appropriate ``FramedProtocol`` subclass, as well as send and receive framers--should be returned by the factory passed to the ``create_connection()`` or ``create_server()`` loop met...
klmitch/framer
framer/transport.py
FramerAdaptor.set_write_buffer_limits
python
def set_write_buffer_limits(self, high=None, low=None): # Call set_write_buffer_limits() on the transport self._transport.set_write_buffer_limits(high=high, low=low)
Called by the client protocol to set the high- and low-water limits for write flow control. These two values control when call the protocol's ``pause_writing()`` and ``resume_writing()`` methods are called. :param high: The high-water limit. Must be a non-negative ...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L413-L433
null
class FramerAdaptor(object): """ The Framer transport adaptor class. Instances of this class--initialized with an appropriate ``FramedProtocol`` subclass, as well as send and receive framers--should be returned by the factory passed to the ``create_connection()`` or ``create_server()`` loop met...
klmitch/framer
framer/transport.py
FramerAdaptor.send_frame
python
def send_frame(self, frame): # Convert the frame to bytes and write them to the connection data = self._send_framer.to_bytes(frame, self._send_state) self._transport.write(data)
Called by the client protocol to send a frame to the remote peer. This method does not block; it buffers the data and arranges for it to be sent out asynchronously. :param frame: The frame to send to the peer. Must be in the format expected by the currently active send ...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L447-L460
null
class FramerAdaptor(object): """ The Framer transport adaptor class. Instances of this class--initialized with an appropriate ``FramedProtocol`` subclass, as well as send and receive framers--should be returned by the factory passed to the ``create_connection()`` or ``create_server()`` loop met...
klmitch/framer
framer/transport.py
FramerAdaptor.push_framer
python
def push_framer(self, *args, **kwargs): # First, interpret the arguments elem = self._interpret_framer(args, kwargs) # Append the element to the framer stack self._framers.append(elem)
Called by the client protocol to temporarily switch to a new send framer, receive framer, or both. Can be called multiple times. Each call to ``push_framer()`` must be paired with a call to ``pop_framer()``, which restores to the previously set framer. When called with positio...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L462-L492
[ "def _interpret_framer(self, args, kwargs):\n \"\"\"\n Interprets positional and keyword arguments related to\n framers.\n\n :param args: A tuple of positional arguments. The first such\n argument will be interpreted as a framer object,\n and the second will be interpret...
class FramerAdaptor(object): """ The Framer transport adaptor class. Instances of this class--initialized with an appropriate ``FramedProtocol`` subclass, as well as send and receive framers--should be returned by the factory passed to the ``create_connection()`` or ``create_server()`` loop met...
klmitch/framer
framer/transport.py
FramerAdaptor.set_framer
python
def set_framer(self, *args, **kwargs): # First, interpret the arguments elem = self._interpret_framer(args, kwargs) # Now, replace the current top of the framer stack self._framers[-1] = elem
Called by the client protocol to replace the current send framer, receive framer, or both. This does not alter the stack maintained by ``push_framer()`` and ``pop_framer()``; if this method is called after ``push_framer()``, then ``pop_framer()`` is called, the framers in force at the t...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L509-L540
[ "def _interpret_framer(self, args, kwargs):\n \"\"\"\n Interprets positional and keyword arguments related to\n framers.\n\n :param args: A tuple of positional arguments. The first such\n argument will be interpreted as a framer object,\n and the second will be interpret...
class FramerAdaptor(object): """ The Framer transport adaptor class. Instances of this class--initialized with an appropriate ``FramedProtocol`` subclass, as well as send and receive framers--should be returned by the factory passed to the ``create_connection()`` or ``create_server()`` loop met...
klmitch/framer
framer/framers.py
IdentityFramer.to_frame
python
def to_frame(self, data, state): # Convert the data to bytes frame = six.binary_type(data) # Clear the buffer del data[:] # Return the frame return frame
Extract a single frame from the data buffer. The consumed data should be removed from the buffer. If no complete frame can be read, must raise a ``NoFrames`` exception. :param data: A ``bytearray`` instance containing the data so far read. :param state: An instanc...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/framers.py#L225-L249
null
class IdentityFramer(Framer): """ The identity framer passes received data straight through. It is the simplest example of a framer. For this framer, frames are ``bytes``. """ def to_bytes(self, frame, state): """ Convert a single frame into bytes that can be transmitted on ...
klmitch/framer
framer/framers.py
ChunkFramer.to_frame
python
def to_frame(self, data, state): # If we've read all the data, let the caller know if state.chunk_remaining <= 0: raise exc.NoFrames() # OK, how much data do we send on? data_len = min(state.chunk_remaining, len(data)) # Extract that data from the buffer fr...
Extract a single frame from the data buffer. The consumed data should be removed from the buffer. If no complete frame can be read, must raise a ``NoFrames`` exception. :param data: A ``bytearray`` instance containing the data so far read. :param state: An instanc...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/framers.py#L302-L334
null
class ChunkFramer(IdentityFramer): """ The chunk framer passes a limited amount of data straight through. It is intended to be used for short-term streaming: initialize it with the amount of data to be received, push it onto the framer stack, then pop the stack when all of the data has been received...
klmitch/framer
framer/framers.py
LineFramer.to_frame
python
def to_frame(self, data, state): # Find the next newline data_len = data.find(b'\n') if data_len < 0: # No line to extract raise exc.NoFrames() # Track how much to exclude frame_len = data_len + 1 # Are we to exclude carriage returns? i...
Extract a single frame from the data buffer. The consumed data should be removed from the buffer. If no complete frame can be read, must raise a ``NoFrames`` exception. :param data: A ``bytearray`` instance containing the data so far read. :param state: An instanc...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/framers.py#L363-L400
null
class LineFramer(Framer): """ The line framer extracts lines as frames. Lines are delimited by newlines or carriage return/newline pairs. The line endings are stripped off. For this framer, frames are ``bytes``. """ def __init__(self, carriage_return=True): """ Initialize...
klmitch/framer
framer/framers.py
LengthEncodedFramer.to_frame
python
def to_frame(self, data, state): # First, determine the length we're looking for length = state.length if length is None: # Try decoding a length from the data buffer length = self.decode_length(data, state) # Now, is there enough data? if len(data) < le...
Extract a single frame from the data buffer. The consumed data should be removed from the buffer. If no complete frame can be read, must raise a ``NoFrames`` exception. :param data: A ``bytearray`` instance containing the data so far read. :param state: An instanc...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/framers.py#L445-L481
[ "def decode_length(self, data, state):\n \"\"\"\n Extract and decode a frame length from the data buffer. The\n consumed data should be removed from the buffer. If the\n length data is incomplete, must raise a ``NoFrames``\n exception.\n\n :param data: A ``bytearray`` instance containing the dat...
class LengthEncodedFramer(Framer): """ Many protocols encode their frames by prefixing the frame with the encoded frame length. This abstract framer is the base class for such framers. Most such framers can be implemented using ``StructFramer``, but other framers with unusual length encodings ...
klmitch/framer
framer/framers.py
LengthEncodedFramer.to_bytes
python
def to_bytes(self, frame, state): # Generate the bytes from the frame frame = six.binary_type(frame) return self.encode_length(frame, state) + frame
Convert a single frame into bytes that can be transmitted on the stream. :param frame: The frame to convert. Should be the same type of object returned by ``to_frame()``. :param state: An instance of ``FramerState``. This object may be used to track...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/framers.py#L483-L499
[ "def encode_length(self, frame, state):\n \"\"\"\n Encode the length of the specified frame into a sequence of\n bytes. The frame will be appended to the byte sequence for\n transmission.\n\n :param frame: The frame to encode the length of. Should be a\n ``bytes`` object.\n :par...
class LengthEncodedFramer(Framer): """ Many protocols encode their frames by prefixing the frame with the encoded frame length. This abstract framer is the base class for such framers. Most such framers can be implemented using ``StructFramer``, but other framers with unusual length encodings ...
klmitch/framer
framer/framers.py
StructFramer.decode_length
python
def decode_length(self, data, state): # Do we have enough data yet? if len(data) < self.fmt.size: raise exc.NoFrames() # Extract the length length = self.fmt.unpack(six.binary_type(data[:self.fmt.size]))[0] del data[:self.fmt.size] # Return the length ...
Extract and decode a frame length from the data buffer. The consumed data should be removed from the buffer. If the length data is incomplete, must raise a ``NoFrames`` exception. :param data: A ``bytearray`` instance containing the data so far read. :para...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/framers.py#L600-L626
null
class StructFramer(LengthEncodedFramer): """ A subclass of ``LengthEncodedFramer`` which encodes the frame length using a format string acceptable to the standard Python ``struct.Struct`` class. For this framer, frames are ``bytes``. """ def __init__(self, fmt): """ Initial...
klmitch/framer
framer/framers.py
StuffingFramer.to_frame
python
def to_frame(self, data, state): # Find the next packet start if not state.frame_start: # Find the begin sequence idx = data.find(self.begin) if idx < 0: # Couldn't find one raise exc.NoFrames() # Excise the begin sequence...
Extract a single frame from the data buffer. The consumed data should be removed from the buffer. If no complete frame can be read, must raise a ``NoFrames`` exception. :param data: A ``bytearray`` instance containing the data so far read. :param state: An instanc...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/framers.py#L700-L743
null
class StuffingFramer(Framer): """ Some protocols encode their frames using synchronization bytes--a sequence of bytes that signal the beginning and end of a frame, allowing for synchronization if a decoding error is encountered. However, the synchronization sequence could occur within the frame,...
klmitch/framer
framer/framers.py
StuffingFramer.to_bytes
python
def to_bytes(self, frame, state): # Generate and return the frame return (self.begin + self.nop.join(six.binary_type(frame).split(self.prefix)) + self.end)
Convert a single frame into bytes that can be transmitted on the stream. :param frame: The frame to convert. Should be the same type of object returned by ``to_frame()``. :param state: An instance of ``FramerState``. This object may be used to track...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/framers.py#L745-L762
null
class StuffingFramer(Framer): """ Some protocols encode their frames using synchronization bytes--a sequence of bytes that signal the beginning and end of a frame, allowing for synchronization if a decoding error is encountered. However, the synchronization sequence could occur within the frame,...
klmitch/framer
framer/framers.py
COBSFramer.to_frame
python
def to_frame(self, data, state): # Find the next null byte data_len = data.find(b'\0') if data_len < 0: # No full frame yet raise exc.NoFrames() # Track how much to exclude frame_len = data_len + 1 # Decode the data frame = six.binary_t...
Extract a single frame from the data buffer. The consumed data should be removed from the buffer. If no complete frame can be read, must raise a ``NoFrames`` exception. :param data: A ``bytearray`` instance containing the data so far read. :param state: An instanc...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/framers.py#L803-L836
null
class COBSFramer(Framer): """ Some protocols encode their frames using synchronization bytes, like ``StuffingFramer``, but the byte stuffing protocol is Consistent Overhead Byte Stuffing, or COBS. This framer implements framing where the end of a frame is delimited by the null character (which ...
klmitch/framer
framer/framers.py
COBSFramer.to_bytes
python
def to_bytes(self, frame, state): # Encode the frame and append the delimiter return six.binary_type(self.variant.encode( six.binary_type(frame))) + b'\0'
Convert a single frame into bytes that can be transmitted on the stream. :param frame: The frame to convert. Should be the same type of object returned by ``to_frame()``. :param state: An instance of ``FramerState``. This object may be used to track...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/framers.py#L838-L854
null
class COBSFramer(Framer): """ Some protocols encode their frames using synchronization bytes, like ``StuffingFramer``, but the byte stuffing protocol is Consistent Overhead Byte Stuffing, or COBS. This framer implements framing where the end of a frame is delimited by the null character (which ...
citruz/beacontools
beacontools/scanner.py
Monitor.run
python
def run(self): self.socket = self.bluez.hci_open_dev(self.bt_device_id) filtr = self.bluez.hci_filter_new() self.bluez.hci_filter_all_events(filtr) self.bluez.hci_filter_set_ptype(filtr, self.bluez.HCI_EVENT_PKT) self.socket.setsockopt(self.bluez.SOL_HCI, self.bluez.HCI_FILTER, ...
Continously scan for BLE advertisements.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/scanner.py#L89-L108
[ "def to_int(string):\n \"\"\"Convert a one element byte string to int for python 2 support.\"\"\"\n if isinstance(string, str):\n return ord(string[0])\n else:\n return string\n", "def set_scan_parameters(self, scan_type=ScanType.ACTIVE, interval_ms=10, window_ms=10,\n ...
class Monitor(threading.Thread): """Continously scan for BLE advertisements.""" def __init__(self, callback, bt_device_id, device_filter, packet_filter): """Construct interface object.""" # do import here so that the package can be used in parsing-only mode (no bluez required) self.blue...
citruz/beacontools
beacontools/scanner.py
Monitor.set_scan_parameters
python
def set_scan_parameters(self, scan_type=ScanType.ACTIVE, interval_ms=10, window_ms=10, address_type=BluetoothAddressType.RANDOM, filter_type=ScanFilter.ALL): " interval_fractions = interval_ms / MS_FRACTION_DIVIDER if interval_fractions < 0x0004 or interval_fractions ...
sets the le scan parameters Args: scan_type: ScanType.(PASSIVE|ACTIVE) interval: ms (as float) between scans (valid range 2.5ms - 10240ms) ..note:: when interval and window are equal, the scan runs continuos window: ms (as float) scan dura...
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/scanner.py#L110-L151
null
class Monitor(threading.Thread): """Continously scan for BLE advertisements.""" def __init__(self, callback, bt_device_id, device_filter, packet_filter): """Construct interface object.""" # do import here so that the package can be used in parsing-only mode (no bluez required) self.blue...
citruz/beacontools
beacontools/scanner.py
Monitor.toggle_scan
python
def toggle_scan(self, enable, filter_duplicates=False): command = struct.pack(">BB", enable, filter_duplicates) self.bluez.hci_send_cmd(self.socket, OGF_LE_CTL, OCF_LE_SET_SCAN_ENABLE, command)
Enables or disables BLE scanning Args: enable: boolean value to enable (True) or disable (False) scanner filter_duplicates: boolean value to enable/disable filter, that omits duplicated packets
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/scanner.py#L153-L161
null
class Monitor(threading.Thread): """Continously scan for BLE advertisements.""" def __init__(self, callback, bt_device_id, device_filter, packet_filter): """Construct interface object.""" # do import here so that the package can be used in parsing-only mode (no bluez required) self.blue...
citruz/beacontools
beacontools/scanner.py
Monitor.process_packet
python
def process_packet(self, pkt): # check if this could be a valid packet before parsing # this reduces the CPU load significantly if not ( \ ((self.mode & ScannerMode.MODE_IBEACON) and (pkt[19:23] == b"\x4c\x00\x02\x15")) or \ ((self.mode & ScannerMode.MODE_EDDYSTONE) and ...
Parse the packet and call callback if one of the filters matches.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/scanner.py#L163-L213
[ "def parse_packet(packet):\n \"\"\"Parse a beacon advertisement packet.\"\"\"\n frame = parse_ltv_packet(packet)\n if frame is None:\n frame = parse_ibeacon_packet(packet)\n return frame\n", "def bt_addr_to_string(addr):\n \"\"\"Convert a binary string to the hex representation.\"\"\"\n a...
class Monitor(threading.Thread): """Continously scan for BLE advertisements.""" def __init__(self, callback, bt_device_id, device_filter, packet_filter): """Construct interface object.""" # do import here so that the package can be used in parsing-only mode (no bluez required) self.blue...
citruz/beacontools
beacontools/scanner.py
Monitor.save_bt_addr
python
def save_bt_addr(self, packet, bt_addr): if isinstance(packet, EddystoneUIDFrame): # remove out old mapping new_mappings = [m for m in self.eddystone_mappings if m[0] != bt_addr] new_mappings.append((bt_addr, packet.properties)) self.eddystone_mappings = new_mappi...
Add to the list of mappings.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/scanner.py#L215-L221
null
class Monitor(threading.Thread): """Continously scan for BLE advertisements.""" def __init__(self, callback, bt_device_id, device_filter, packet_filter): """Construct interface object.""" # do import here so that the package can be used in parsing-only mode (no bluez required) self.blue...
citruz/beacontools
beacontools/scanner.py
Monitor.get_properties
python
def get_properties(self, packet, bt_addr): if is_one_of(packet, [EddystoneTLMFrame, EddystoneURLFrame, \ EddystoneEncryptedTLMFrame, EddystoneEIDFrame]): # here we retrieve the namespace and instance which corresponds to the # eddystone beacon with this bt a...
Get properties of beacon depending on type.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/scanner.py#L223-L231
[ "def is_one_of(obj, types):\n \"\"\"Return true iff obj is an instance of one of the types.\"\"\"\n for type_ in types:\n if isinstance(obj, type_):\n return True\n return False\n", "def properties_from_mapping(self, bt_addr):\n \"\"\"Retrieve properties (namespace, instance) for the...
class Monitor(threading.Thread): """Continously scan for BLE advertisements.""" def __init__(self, callback, bt_device_id, device_filter, packet_filter): """Construct interface object.""" # do import here so that the package can be used in parsing-only mode (no bluez required) self.blue...
citruz/beacontools
beacontools/scanner.py
Monitor.properties_from_mapping
python
def properties_from_mapping(self, bt_addr): for addr, properties in self.eddystone_mappings: if addr == bt_addr: return properties return None
Retrieve properties (namespace, instance) for the specified bt address.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/scanner.py#L233-L238
null
class Monitor(threading.Thread): """Continously scan for BLE advertisements.""" def __init__(self, callback, bt_device_id, device_filter, packet_filter): """Construct interface object.""" # do import here so that the package can be used in parsing-only mode (no bluez required) self.blue...
citruz/beacontools
beacontools/scanner.py
Monitor.terminate
python
def terminate(self): self.toggle_scan(False) self.keep_going = False self.join()
Signal runner to stop and join thread.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/scanner.py#L240-L244
[ "def toggle_scan(self, enable, filter_duplicates=False):\n \"\"\"Enables or disables BLE scanning\n\n Args:\n enable: boolean value to enable (True) or disable (False) scanner\n filter_duplicates: boolean value to enable/disable filter, that\n omits duplicated packets\"\"\"\n comma...
class Monitor(threading.Thread): """Continously scan for BLE advertisements.""" def __init__(self, callback, bt_device_id, device_filter, packet_filter): """Construct interface object.""" # do import here so that the package can be used in parsing-only mode (no bluez required) self.blue...
citruz/beacontools
beacontools/utils.py
data_to_uuid
python
def data_to_uuid(data): string = data_to_hexstring(data) return string[0:8]+'-'+string[8:12]+'-'+string[12:16]+'-'+string[16:20]+'-'+string[20:32]
Convert an array of binary data to the iBeacon uuid format.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/utils.py#L24-L27
[ "def data_to_hexstring(data):\n \"\"\"Convert an array of binary data to the hex representation as a string.\"\"\"\n return hexlify(data_to_binstring(data)).decode('ascii')\n" ]
"""Utilities for byte conversion.""" from binascii import hexlify from re import compile as compile_regex import array import struct from .const import ScannerMode # compiled regex to match lowercase MAC-addresses coming from # bt_addr_to_string RE_MAC_ADDR = compile_regex('(?:[0-9a-f]{2}:){5}(?:[0-9a-f]{2})') def ...
citruz/beacontools
beacontools/utils.py
bt_addr_to_string
python
def bt_addr_to_string(addr): addr_str = array.array('B', addr) addr_str.reverse() hex_str = hexlify(addr_str.tostring()).decode('ascii') # insert ":" seperator between the bytes return ':'.join(a+b for a, b in zip(hex_str[::2], hex_str[1::2]))
Convert a binary string to the hex representation.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/utils.py#L35-L41
null
"""Utilities for byte conversion.""" from binascii import hexlify from re import compile as compile_regex import array import struct from .const import ScannerMode # compiled regex to match lowercase MAC-addresses coming from # bt_addr_to_string RE_MAC_ADDR = compile_regex('(?:[0-9a-f]{2}:){5}(?:[0-9a-f]{2})') def ...
citruz/beacontools
beacontools/utils.py
is_one_of
python
def is_one_of(obj, types): for type_ in types: if isinstance(obj, type_): return True return False
Return true iff obj is an instance of one of the types.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/utils.py#L44-L49
null
"""Utilities for byte conversion.""" from binascii import hexlify from re import compile as compile_regex import array import struct from .const import ScannerMode # compiled regex to match lowercase MAC-addresses coming from # bt_addr_to_string RE_MAC_ADDR = compile_regex('(?:[0-9a-f]{2}:){5}(?:[0-9a-f]{2})') def ...
citruz/beacontools
beacontools/utils.py
is_packet_type
python
def is_packet_type(cls): from .packet_types import EddystoneUIDFrame, EddystoneURLFrame, \ EddystoneEncryptedTLMFrame, EddystoneTLMFrame, \ EddystoneEIDFrame, IBeaconAdvertisement, \ EstimoteTelemetryFrameA, EstimoteTelemetryF...
Check if class is one the packet types.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/utils.py#L52-L60
null
"""Utilities for byte conversion.""" from binascii import hexlify from re import compile as compile_regex import array import struct from .const import ScannerMode # compiled regex to match lowercase MAC-addresses coming from # bt_addr_to_string RE_MAC_ADDR = compile_regex('(?:[0-9a-f]{2}:){5}(?:[0-9a-f]{2})') def ...
citruz/beacontools
beacontools/utils.py
bin_to_int
python
def bin_to_int(string): if isinstance(string, str): return struct.unpack("b", string)[0] else: return struct.unpack("b", bytes([string]))[0]
Convert a one element byte string to signed int for python 2 support.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/utils.py#L71-L76
null
"""Utilities for byte conversion.""" from binascii import hexlify from re import compile as compile_regex import array import struct from .const import ScannerMode # compiled regex to match lowercase MAC-addresses coming from # bt_addr_to_string RE_MAC_ADDR = compile_regex('(?:[0-9a-f]{2}:){5}(?:[0-9a-f]{2})') def ...
citruz/beacontools
beacontools/utils.py
get_mode
python
def get_mode(device_filter): from .device_filters import IBeaconFilter, EddystoneFilter, BtAddrFilter, EstimoteFilter if device_filter is None or len(device_filter) == 0: return ScannerMode.MODE_ALL mode = ScannerMode.MODE_NONE for filtr in device_filter: if isinstance(filtr, IBeaconFil...
Determine which beacons the scanner should look for.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/utils.py#L79-L97
null
"""Utilities for byte conversion.""" from binascii import hexlify from re import compile as compile_regex import array import struct from .const import ScannerMode # compiled regex to match lowercase MAC-addresses coming from # bt_addr_to_string RE_MAC_ADDR = compile_regex('(?:[0-9a-f]{2}:){5}(?:[0-9a-f]{2})') def ...
citruz/beacontools
beacontools/device_filters.py
DeviceFilter.matches
python
def matches(self, filter_props): if filter_props is None: return False found_one = False for key, value in filter_props.items(): if key in self.properties and value != self.properties[key]: return False elif key in self.properties and value ==...
Check if the filter matches the supplied properties.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/device_filters.py#L13-L25
null
class DeviceFilter(object): """Base class for all device filters. Should not be used by itself.""" def __init__(self): """Initialize filter.""" self.properties = {} def __repr__(self): return "{}({})".format( self.__class__.__name__, ", ".join(["=".join((k,...
citruz/beacontools
beacontools/parser.py
parse_packet
python
def parse_packet(packet): frame = parse_ltv_packet(packet) if frame is None: frame = parse_ibeacon_packet(packet) return frame
Parse a beacon advertisement packet.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/parser.py#L14-L19
[ "def parse_ltv_packet(packet):\n \"\"\"Parse a tag-length-value style beacon packet.\"\"\"\n try:\n frame = LTVFrame.parse(packet)\n for ltv in frame:\n if ltv['type'] == SERVICE_DATA_TYPE:\n data = ltv['value']\n\n if data[\"service_identifier\"] == EDDY...
"""Beacon advertisement parser.""" from construct import ConstructError from .structs import LTVFrame, IBeaconAdvertisingPacket from .packet_types import EddystoneUIDFrame, EddystoneURLFrame, EddystoneEncryptedTLMFrame, \ EddystoneTLMFrame, EddystoneEIDFrame, IBeaconAdvertisement, \ ...
citruz/beacontools
beacontools/parser.py
parse_ltv_packet
python
def parse_ltv_packet(packet): try: frame = LTVFrame.parse(packet) for ltv in frame: if ltv['type'] == SERVICE_DATA_TYPE: data = ltv['value'] if data["service_identifier"] == EDDYSTONE_UUID: return parse_eddystone_service_data(data) ...
Parse a tag-length-value style beacon packet.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/parser.py#L21-L38
[ "def parse_eddystone_service_data(data):\n \"\"\"Parse Eddystone service data.\"\"\"\n if data['frame_type'] == EDDYSTONE_UID_FRAME:\n return EddystoneUIDFrame(data['frame'])\n\n elif data['frame_type'] == EDDYSTONE_TLM_FRAME:\n if data['frame']['tlm_version'] == EDDYSTONE_TLM_ENCRYPTED:\n ...
"""Beacon advertisement parser.""" from construct import ConstructError from .structs import LTVFrame, IBeaconAdvertisingPacket from .packet_types import EddystoneUIDFrame, EddystoneURLFrame, EddystoneEncryptedTLMFrame, \ EddystoneTLMFrame, EddystoneEIDFrame, IBeaconAdvertisement, \ ...
citruz/beacontools
beacontools/parser.py
parse_eddystone_service_data
python
def parse_eddystone_service_data(data): if data['frame_type'] == EDDYSTONE_UID_FRAME: return EddystoneUIDFrame(data['frame']) elif data['frame_type'] == EDDYSTONE_TLM_FRAME: if data['frame']['tlm_version'] == EDDYSTONE_TLM_ENCRYPTED: return EddystoneEncryptedTLMFrame(data['frame']['...
Parse Eddystone service data.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/parser.py#L40-L57
null
"""Beacon advertisement parser.""" from construct import ConstructError from .structs import LTVFrame, IBeaconAdvertisingPacket from .packet_types import EddystoneUIDFrame, EddystoneURLFrame, EddystoneEncryptedTLMFrame, \ EddystoneTLMFrame, EddystoneEIDFrame, IBeaconAdvertisement, \ ...
citruz/beacontools
beacontools/parser.py
parse_estimote_service_data
python
def parse_estimote_service_data(data): if data['frame_type'] & 0xF == ESTIMOTE_TELEMETRY_FRAME: protocol_version = (data['frame_type'] & 0xF0) >> 4 if data['frame']['subframe_type'] == ESTIMOTE_TELEMETRY_SUBFRAME_A: return EstimoteTelemetryFrameA(data['frame'], protocol_version) ...
Parse Estimote service data.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/parser.py#L59-L67
null
"""Beacon advertisement parser.""" from construct import ConstructError from .structs import LTVFrame, IBeaconAdvertisingPacket from .packet_types import EddystoneUIDFrame, EddystoneURLFrame, EddystoneEncryptedTLMFrame, \ EddystoneTLMFrame, EddystoneEIDFrame, IBeaconAdvertisement, \ ...
citruz/beacontools
beacontools/packet_types/estimote.py
EstimoteTelemetryFrameA.parse_motion_state
python
def parse_motion_state(val): number = val & 0b00111111 unit = (val & 0b11000000) >> 6 if unit == 1: number *= 60 # minutes elif unit == 2: number *= 60 * 60 # hours elif unit == 3 and number < 32: number *= 60 * 60 * 24 # days elif unit...
Convert motion state byte to seconds.
train
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/packet_types/estimote.py#L46-L59
null
class EstimoteTelemetryFrameA(object): """Estimote telemetry subframe A.""" def __init__(self, data, protocol_version): self._protocol_version = protocol_version self._identifier = data_to_hexstring(data['identifier']) sub = data['sub_frame'] # acceleration: convert to tuple and...
mosdef-hub/foyer
foyer/smarts_graph.py
_find_chordless_cycles
python
def _find_chordless_cycles(bond_graph, max_cycle_size): cycles = [[] for _ in bond_graph.nodes] ''' For all nodes we need to find the cycles that they are included within. ''' for i, node in enumerate(bond_graph.nodes): neighbors = list(bond_graph.neighbors(node)) pairs = list(iter...
Find all chordless cycles (i.e. rings) in the bond graph Traverses the bond graph to determine all cycles (i.e. rings) each atom is contained within. Algorithm has been adapted from: https://stackoverflow.com/questions/4022662/find-all-chordless-cycles-in-an-undirected-graph/4028855#4028855
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/smarts_graph.py#L241-L301
null
from collections import OrderedDict, defaultdict import itertools import sys import networkx as nx from networkx.algorithms import isomorphism from oset import oset as OrderedSet import parmed.periodic_table as pt from foyer.smarts import SMARTS class SMARTSGraph(nx.Graph): """A graph representation of a SMARTS...
mosdef-hub/foyer
foyer/smarts_graph.py
_prepare_atoms
python
def _prepare_atoms(topology, compute_cycles=False): atom1 = next(topology.atoms()) has_whitelists = hasattr(atom1, 'whitelist') has_cycles = hasattr(atom1, 'cycles') compute_cycles = compute_cycles and not has_cycles if compute_cycles or not has_whitelists: for atom in topology.atoms(): ...
Compute cycles and add white-/blacklists to atoms.
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/smarts_graph.py#L304-L326
null
from collections import OrderedDict, defaultdict import itertools import sys import networkx as nx from networkx.algorithms import isomorphism from oset import oset as OrderedSet import parmed.periodic_table as pt from foyer.smarts import SMARTS class SMARTSGraph(nx.Graph): """A graph representation of a SMARTS...
mosdef-hub/foyer
foyer/smarts_graph.py
SMARTSGraph._add_nodes
python
def _add_nodes(self): for n, atom in enumerate(self.ast.select('atom')): self.add_node(n, atom=atom) self._atom_indices[id(atom)] = n
Add all atoms in the SMARTS string as nodes in the graph.
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/smarts_graph.py#L51-L55
null
class SMARTSGraph(nx.Graph): """A graph representation of a SMARTS pattern. Attributes ---------- smarts_string : str parser : foyer.smarts.SMARTS name : str overrides : set Other Parameters ---------- args kwargs """ # Because the first atom in a SMARTS string is a...
mosdef-hub/foyer
foyer/smarts_graph.py
SMARTSGraph._add_edges
python
def _add_edges(self, ast_node, trunk=None): " atom_indices = self._atom_indices for atom in ast_node.tail: if atom.head == 'atom': atom_idx = atom_indices[id(atom)] if atom.is_first_kid and atom.parent().head == 'branch': trunk_idx ...
Add all bonds in the SMARTS string as edges in the graph.
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/smarts_graph.py#L57-L75
null
class SMARTSGraph(nx.Graph): """A graph representation of a SMARTS pattern. Attributes ---------- smarts_string : str parser : foyer.smarts.SMARTS name : str overrides : set Other Parameters ---------- args kwargs """ # Because the first atom in a SMARTS string is a...
mosdef-hub/foyer
foyer/smarts_graph.py
SMARTSGraph._add_label_edges
python
def _add_label_edges(self): labels = self.ast.select('atom_label') if not labels: return # We need each individual label and atoms with multiple ring labels # would yield e.g. the string '12' so split those up. label_digits = defaultdict(list) for label in la...
Add edges between all atoms with the same atom_label in rings.
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/smarts_graph.py#L77-L94
null
class SMARTSGraph(nx.Graph): """A graph representation of a SMARTS pattern. Attributes ---------- smarts_string : str parser : foyer.smarts.SMARTS name : str overrides : set Other Parameters ---------- args kwargs """ # Because the first atom in a SMARTS string is a...