repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
maas/python-libmaas
maas/client/viscera/interfaces.py
get_parent
def get_parent(parent): """Get the parent to send to the handler.""" if isinstance(parent, Interface): return parent.id elif isinstance(parent, int): return parent else: raise TypeError( "parent must be an Interface or int, not %s" % ( type(parent).__n...
python
def get_parent(parent): """Get the parent to send to the handler.""" if isinstance(parent, Interface): return parent.id elif isinstance(parent, int): return parent else: raise TypeError( "parent must be an Interface or int, not %s" % ( type(parent).__n...
[ "def", "get_parent", "(", "parent", ")", ":", "if", "isinstance", "(", "parent", ",", "Interface", ")", ":", "return", "parent", ".", "id", "elif", "isinstance", "(", "parent", ",", "int", ")", ":", "return", "parent", "else", ":", "raise", "TypeError", ...
Get the parent to send to the handler.
[ "Get", "the", "parent", "to", "send", "to", "the", "handler", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/interfaces.py#L45-L54
train
maas/python-libmaas
maas/client/viscera/interfaces.py
Interface.save
async def save(self): """Save this interface.""" if set(self.tags) != set(self._orig_data['tags']): self._changed_data['tags'] = ','.join(self.tags) elif 'tags' in self._changed_data: del self._changed_data['tags'] orig_params = self._orig_data['params'] i...
python
async def save(self): """Save this interface.""" if set(self.tags) != set(self._orig_data['tags']): self._changed_data['tags'] = ','.join(self.tags) elif 'tags' in self._changed_data: del self._changed_data['tags'] orig_params = self._orig_data['params'] i...
[ "async", "def", "save", "(", "self", ")", ":", "if", "set", "(", "self", ".", "tags", ")", "!=", "set", "(", "self", ".", "_orig_data", "[", "'tags'", "]", ")", ":", "self", ".", "_changed_data", "[", "'tags'", "]", "=", "','", ".", "join", "(", ...
Save this interface.
[ "Save", "this", "interface", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/interfaces.py#L127-L152
train
maas/python-libmaas
maas/client/viscera/interfaces.py
Interface.disconnect
async def disconnect(self): """Disconnect this interface.""" self._data = await self._handler.disconnect( system_id=self.node.system_id, id=self.id)
python
async def disconnect(self): """Disconnect this interface.""" self._data = await self._handler.disconnect( system_id=self.node.system_id, id=self.id)
[ "async", "def", "disconnect", "(", "self", ")", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "disconnect", "(", "system_id", "=", "self", ".", "node", ".", "system_id", ",", "id", "=", "self", ".", "id", ")" ]
Disconnect this interface.
[ "Disconnect", "this", "interface", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/interfaces.py#L159-L162
train
maas/python-libmaas
maas/client/viscera/interfaces.py
InterfaceLink.delete
async def delete(self): """Delete this interface link.""" interface = self._data['interface'] data = await interface._handler.unlink_subnet( system_id=interface.node.system_id, id=interface.id, _id=self.id) interface._data['links'] = list(data['links']) interface._ori...
python
async def delete(self): """Delete this interface link.""" interface = self._data['interface'] data = await interface._handler.unlink_subnet( system_id=interface.node.system_id, id=interface.id, _id=self.id) interface._data['links'] = list(data['links']) interface._ori...
[ "async", "def", "delete", "(", "self", ")", ":", "interface", "=", "self", ".", "_data", "[", "'interface'", "]", "data", "=", "await", "interface", ".", "_handler", ".", "unlink_subnet", "(", "system_id", "=", "interface", ".", "node", ".", "system_id", ...
Delete this interface link.
[ "Delete", "this", "interface", "link", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/interfaces.py#L192-L198
train
maas/python-libmaas
maas/client/viscera/interfaces.py
InterfaceLink.set_as_default_gateway
async def set_as_default_gateway(self): """Set this link as the default gateway for the node.""" interface = self._data['interface'] await interface._handler.set_default_gateway( system_id=interface.node.system_id, id=interface.id, link_id=self.id)
python
async def set_as_default_gateway(self): """Set this link as the default gateway for the node.""" interface = self._data['interface'] await interface._handler.set_default_gateway( system_id=interface.node.system_id, id=interface.id, link_id=self.id)
[ "async", "def", "set_as_default_gateway", "(", "self", ")", ":", "interface", "=", "self", ".", "_data", "[", "'interface'", "]", "await", "interface", ".", "_handler", ".", "set_default_gateway", "(", "system_id", "=", "interface", ".", "node", ".", "system_i...
Set this link as the default gateway for the node.
[ "Set", "this", "link", "as", "the", "default", "gateway", "for", "the", "node", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/interfaces.py#L200-L205
train
maas/python-libmaas
maas/client/viscera/interfaces.py
InterfaceLinksType.create
async def create( cls, interface: Interface, mode: LinkMode, subnet: Union[Subnet, int] = None, ip_address: str = None, force: bool = False, default_gateway: bool = False): """ Create a link on `Interface` in MAAS. :param interface: Interface to create the li...
python
async def create( cls, interface: Interface, mode: LinkMode, subnet: Union[Subnet, int] = None, ip_address: str = None, force: bool = False, default_gateway: bool = False): """ Create a link on `Interface` in MAAS. :param interface: Interface to create the li...
[ "async", "def", "create", "(", "cls", ",", "interface", ":", "Interface", ",", "mode", ":", "LinkMode", ",", "subnet", ":", "Union", "[", "Subnet", ",", "int", "]", "=", "None", ",", "ip_address", ":", "str", "=", "None", ",", "force", ":", "bool", ...
Create a link on `Interface` in MAAS. :param interface: Interface to create the link on. :type interface: `Interface` :param mode: Mode of the link. :type mode: `LinkMode` :param subnet: The subnet to create the link on (optional). :type subnet: `Subnet` or `int` ...
[ "Create", "a", "link", "on", "Interface", "in", "MAAS", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/interfaces.py#L211-L291
train
maas/python-libmaas
maas/client/viscera/bcache_cache_sets.py
BcacheCacheSetsType.create
async def create( cls, node: Union[Node, str], cache_device: Union[BlockDevice, Partition]): """ Create a BcacheCacheSet on a Node. :param node: Node to create the interface on. :type node: `Node` or `str` :param cache_device: Block device or partition to...
python
async def create( cls, node: Union[Node, str], cache_device: Union[BlockDevice, Partition]): """ Create a BcacheCacheSet on a Node. :param node: Node to create the interface on. :type node: `Node` or `str` :param cache_device: Block device or partition to...
[ "async", "def", "create", "(", "cls", ",", "node", ":", "Union", "[", "Node", ",", "str", "]", ",", "cache_device", ":", "Union", "[", "BlockDevice", ",", "Partition", "]", ")", ":", "params", "=", "{", "}", "if", "isinstance", "(", "node", ",", "s...
Create a BcacheCacheSet on a Node. :param node: Node to create the interface on. :type node: `Node` or `str` :param cache_device: Block device or partition to create the cache set on. :type cache_device: `BlockDevice` or `Partition`
[ "Create", "a", "BcacheCacheSet", "on", "a", "Node", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/bcache_cache_sets.py#L73-L103
train
maas/python-libmaas
maas/client/flesh/tabular.py
Table.render
def render(self, target, data): """Render the table.""" rows = self.get_rows(target, data) rows = self._filter_rows(rows) renderer = getattr(self, "_render_%s" % target.name, None) if renderer is None: raise ValueError( "Cannot render %r for %s." % (se...
python
def render(self, target, data): """Render the table.""" rows = self.get_rows(target, data) rows = self._filter_rows(rows) renderer = getattr(self, "_render_%s" % target.name, None) if renderer is None: raise ValueError( "Cannot render %r for %s." % (se...
[ "def", "render", "(", "self", ",", "target", ",", "data", ")", ":", "rows", "=", "self", ".", "get_rows", "(", "target", ",", "data", ")", "rows", "=", "self", ".", "_filter_rows", "(", "rows", ")", "renderer", "=", "getattr", "(", "self", ",", "\"...
Render the table.
[ "Render", "the", "table", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/tabular.py#L75-L84
train
maas/python-libmaas
maas/client/viscera/fabrics.py
FabricType.get_default
async def get_default(cls): """ Get the 'default' Fabric for the MAAS. """ data = await cls._handler.read(id=cls._default_fabric_id) return cls(data)
python
async def get_default(cls): """ Get the 'default' Fabric for the MAAS. """ data = await cls._handler.read(id=cls._default_fabric_id) return cls(data)
[ "async", "def", "get_default", "(", "cls", ")", ":", "data", "=", "await", "cls", ".", "_handler", ".", "read", "(", "id", "=", "cls", ".", "_default_fabric_id", ")", "return", "cls", "(", "data", ")" ]
Get the 'default' Fabric for the MAAS.
[ "Get", "the", "default", "Fabric", "for", "the", "MAAS", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/fabrics.py#L60-L65
train
maas/python-libmaas
maas/client/viscera/fabrics.py
Fabric.delete
async def delete(self): """Delete this Fabric.""" if self.id == self._origin.Fabric._default_fabric_id: raise CannotDelete("Default fabric cannot be deleted.") await self._handler.delete(id=self.id)
python
async def delete(self): """Delete this Fabric.""" if self.id == self._origin.Fabric._default_fabric_id: raise CannotDelete("Default fabric cannot be deleted.") await self._handler.delete(id=self.id)
[ "async", "def", "delete", "(", "self", ")", ":", "if", "self", ".", "id", "==", "self", ".", "_origin", ".", "Fabric", ".", "_default_fabric_id", ":", "raise", "CannotDelete", "(", "\"Default fabric cannot be deleted.\"", ")", "await", "self", ".", "_handler",...
Delete this Fabric.
[ "Delete", "this", "Fabric", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/fabrics.py#L82-L86
train
maas/python-libmaas
maas/client/viscera/__init__.py
dir_class
def dir_class(cls): """Return a list of names available on `cls`. Eliminates names that bind to an `ObjectMethod` without a corresponding class method; see `ObjectMethod`. """ # Class attributes (including methods). for name, value in vars_class(cls).items(): if isinstance(value, Object...
python
def dir_class(cls): """Return a list of names available on `cls`. Eliminates names that bind to an `ObjectMethod` without a corresponding class method; see `ObjectMethod`. """ # Class attributes (including methods). for name, value in vars_class(cls).items(): if isinstance(value, Object...
[ "def", "dir_class", "(", "cls", ")", ":", "for", "name", ",", "value", "in", "vars_class", "(", "cls", ")", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "ObjectMethod", ")", ":", "if", "value", ".", "has_classmethod", ":", "yie...
Return a list of names available on `cls`. Eliminates names that bind to an `ObjectMethod` without a corresponding class method; see `ObjectMethod`.
[ "Return", "a", "list", "of", "names", "available", "on", "cls", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L71-L93
train
maas/python-libmaas
maas/client/viscera/__init__.py
dir_instance
def dir_instance(inst): """Return a list of names available on `inst`. Eliminates names that bind to an `ObjectMethod` without a corresponding instance method; see `ObjectMethod`. """ # Skip instance attributes; __slots__ is automatically defined, and # descriptors are used to define attributes...
python
def dir_instance(inst): """Return a list of names available on `inst`. Eliminates names that bind to an `ObjectMethod` without a corresponding instance method; see `ObjectMethod`. """ # Skip instance attributes; __slots__ is automatically defined, and # descriptors are used to define attributes...
[ "def", "dir_instance", "(", "inst", ")", ":", "for", "name", ",", "value", "in", "vars_class", "(", "type", "(", "inst", ")", ")", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "ObjectMethod", ")", ":", "if", "value", ".", "ha...
Return a list of names available on `inst`. Eliminates names that bind to an `ObjectMethod` without a corresponding instance method; see `ObjectMethod`.
[ "Return", "a", "list", "of", "names", "available", "on", "inst", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L96-L114
train
maas/python-libmaas
maas/client/viscera/__init__.py
is_pk_descriptor
def is_pk_descriptor(descriptor, include_alt=False): """Return true if `descriptor` is a primary key.""" if descriptor.pk is True or type(descriptor.pk) is int: return True if include_alt: return descriptor.alt_pk is True or type(descriptor.alt_pk) is int else: return False
python
def is_pk_descriptor(descriptor, include_alt=False): """Return true if `descriptor` is a primary key.""" if descriptor.pk is True or type(descriptor.pk) is int: return True if include_alt: return descriptor.alt_pk is True or type(descriptor.alt_pk) is int else: return False
[ "def", "is_pk_descriptor", "(", "descriptor", ",", "include_alt", "=", "False", ")", ":", "if", "descriptor", ".", "pk", "is", "True", "or", "type", "(", "descriptor", ".", "pk", ")", "is", "int", ":", "return", "True", "if", "include_alt", ":", "return"...
Return true if `descriptor` is a primary key.
[ "Return", "true", "if", "descriptor", "is", "a", "primary", "key", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L183-L190
train
maas/python-libmaas
maas/client/viscera/__init__.py
get_pk_descriptors
def get_pk_descriptors(cls): """Return tuple of tuples with attribute name and descriptor on the `cls` that is defined as the primary keys.""" pk_fields = { name: descriptor for name, descriptor in vars_class(cls).items() if isinstance(descriptor, ObjectField) and is_pk_descriptor(de...
python
def get_pk_descriptors(cls): """Return tuple of tuples with attribute name and descriptor on the `cls` that is defined as the primary keys.""" pk_fields = { name: descriptor for name, descriptor in vars_class(cls).items() if isinstance(descriptor, ObjectField) and is_pk_descriptor(de...
[ "def", "get_pk_descriptors", "(", "cls", ")", ":", "pk_fields", "=", "{", "name", ":", "descriptor", "for", "name", ",", "descriptor", "in", "vars_class", "(", "cls", ")", ".", "items", "(", ")", "if", "isinstance", "(", "descriptor", ",", "ObjectField", ...
Return tuple of tuples with attribute name and descriptor on the `cls` that is defined as the primary keys.
[ "Return", "tuple", "of", "tuples", "with", "attribute", "name", "and", "descriptor", "on", "the", "cls", "that", "is", "defined", "as", "the", "primary", "keys", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L193-L230
train
maas/python-libmaas
maas/client/viscera/__init__.py
ManagedCreate
def ManagedCreate(super_cls): """Dynamically creates a `create` method for a `ObjectSet.Managed` class that calls the `super_cls.create`. The first positional argument that is passed to the `super_cls.create` is the `_manager` that was set using `ObjectSet.Managed`. The created object is added to t...
python
def ManagedCreate(super_cls): """Dynamically creates a `create` method for a `ObjectSet.Managed` class that calls the `super_cls.create`. The first positional argument that is passed to the `super_cls.create` is the `_manager` that was set using `ObjectSet.Managed`. The created object is added to t...
[ "def", "ManagedCreate", "(", "super_cls", ")", ":", "@", "wraps", "(", "super_cls", ".", "create", ")", "async", "def", "_create", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "cls", "=", "type", "(", "self", ")", "manager", "=", "...
Dynamically creates a `create` method for a `ObjectSet.Managed` class that calls the `super_cls.create`. The first positional argument that is passed to the `super_cls.create` is the `_manager` that was set using `ObjectSet.Managed`. The created object is added to the `ObjectSet.Managed` also placed in...
[ "Dynamically", "creates", "a", "create", "method", "for", "a", "ObjectSet", ".", "Managed", "class", "that", "calls", "the", "super_cls", ".", "create", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L488-L518
train
maas/python-libmaas
maas/client/viscera/__init__.py
mapping_of
def mapping_of(cls): """Expects a mapping from some key to data for `cls` instances.""" def mapper(data): if not isinstance(data, Mapping): raise TypeError( "data must be a mapping, not %s" % type(data).__name__) return { key: cls(value) ...
python
def mapping_of(cls): """Expects a mapping from some key to data for `cls` instances.""" def mapper(data): if not isinstance(data, Mapping): raise TypeError( "data must be a mapping, not %s" % type(data).__name__) return { key: cls(value) ...
[ "def", "mapping_of", "(", "cls", ")", ":", "def", "mapper", "(", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "Mapping", ")", ":", "raise", "TypeError", "(", "\"data must be a mapping, not %s\"", "%", "type", "(", "data", ")", ".", "__n...
Expects a mapping from some key to data for `cls` instances.
[ "Expects", "a", "mapping", "from", "some", "key", "to", "data", "for", "cls", "instances", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L1069-L1080
train
maas/python-libmaas
maas/client/viscera/__init__.py
find_objects
def find_objects(modules): """Find subclasses of `Object` and `ObjectSet` in the given modules. :param modules: The full *names* of modules to include. These modules MUST have been imported in advance. """ return { subclass.__name__: subclass for subclass in chain( g...
python
def find_objects(modules): """Find subclasses of `Object` and `ObjectSet` in the given modules. :param modules: The full *names* of modules to include. These modules MUST have been imported in advance. """ return { subclass.__name__: subclass for subclass in chain( g...
[ "def", "find_objects", "(", "modules", ")", ":", "return", "{", "subclass", ".", "__name__", ":", "subclass", "for", "subclass", "in", "chain", "(", "get_all_subclasses", "(", "Object", ")", ",", "get_all_subclasses", "(", "ObjectSet", ")", ",", ")", "if", ...
Find subclasses of `Object` and `ObjectSet` in the given modules. :param modules: The full *names* of modules to include. These modules MUST have been imported in advance.
[ "Find", "subclasses", "of", "Object", "and", "ObjectSet", "in", "the", "given", "modules", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L1089-L1102
train
maas/python-libmaas
maas/client/viscera/__init__.py
ObjectType.bind
def bind(cls, origin, handler, *, name=None): """Bind this object to the given origin and handler. :param origin: An instance of `Origin`. :param handler: An instance of `bones.HandlerAPI`. :return: A subclass of this class. """ name = cls.__name__ if name is None else n...
python
def bind(cls, origin, handler, *, name=None): """Bind this object to the given origin and handler. :param origin: An instance of `Origin`. :param handler: An instance of `bones.HandlerAPI`. :return: A subclass of this class. """ name = cls.__name__ if name is None else n...
[ "def", "bind", "(", "cls", ",", "origin", ",", "handler", ",", "*", ",", "name", "=", "None", ")", ":", "name", "=", "cls", ".", "__name__", "if", "name", "is", "None", "else", "name", "attrs", "=", "{", "\"_origin\"", ":", "origin", ",", "\"_handl...
Bind this object to the given origin and handler. :param origin: An instance of `Origin`. :param handler: An instance of `bones.HandlerAPI`. :return: A subclass of this class.
[ "Bind", "this", "object", "to", "the", "given", "origin", "and", "handler", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L157-L169
train
maas/python-libmaas
maas/client/viscera/__init__.py
Object.refresh
async def refresh(self): """Refresh the object from MAAS.""" cls = type(self) if hasattr(cls, 'read'): descriptors, alt_descriptors = get_pk_descriptors(cls) if len(descriptors) == 1: try: obj = await cls.read(getattr(self, descriptors[...
python
async def refresh(self): """Refresh the object from MAAS.""" cls = type(self) if hasattr(cls, 'read'): descriptors, alt_descriptors = get_pk_descriptors(cls) if len(descriptors) == 1: try: obj = await cls.read(getattr(self, descriptors[...
[ "async", "def", "refresh", "(", "self", ")", ":", "cls", "=", "type", "(", "self", ")", "if", "hasattr", "(", "cls", ",", "'read'", ")", ":", "descriptors", ",", "alt_descriptors", "=", "get_pk_descriptors", "(", "cls", ")", "if", "len", "(", "descript...
Refresh the object from MAAS.
[ "Refresh", "the", "object", "from", "MAAS", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L426-L471
train
maas/python-libmaas
maas/client/viscera/__init__.py
Object.save
async def save(self): """Save the object in MAAS.""" if hasattr(self._handler, "update"): if self._changed_data: update_data = dict(self._changed_data) update_data.update({ key: self._orig_data[key] for key in self._hand...
python
async def save(self): """Save the object in MAAS.""" if hasattr(self._handler, "update"): if self._changed_data: update_data = dict(self._changed_data) update_data.update({ key: self._orig_data[key] for key in self._hand...
[ "async", "def", "save", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "_handler", ",", "\"update\"", ")", ":", "if", "self", ".", "_changed_data", ":", "update_data", "=", "dict", "(", "self", ".", "_changed_data", ")", "update_data", ".", ...
Save the object in MAAS.
[ "Save", "the", "object", "in", "MAAS", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L473-L485
train
maas/python-libmaas
maas/client/viscera/__init__.py
ObjectSet.Managed
def Managed(cls, manager, field, items): """Create a custom `ObjectSet` that is managed by a related `Object.` :param manager: The manager of the `ObjectSet`. This is the `Object` that manages this set of objects. :param field: The field on the `manager` that created this managed ...
python
def Managed(cls, manager, field, items): """Create a custom `ObjectSet` that is managed by a related `Object.` :param manager: The manager of the `ObjectSet`. This is the `Object` that manages this set of objects. :param field: The field on the `manager` that created this managed ...
[ "def", "Managed", "(", "cls", ",", "manager", ",", "field", ",", "items", ")", ":", "attrs", "=", "{", "\"_manager\"", ":", "manager", ",", "\"_manager_field\"", ":", "field", ",", "}", "if", "hasattr", "(", "cls", ",", "\"create\"", ")", ":", "attrs",...
Create a custom `ObjectSet` that is managed by a related `Object.` :param manager: The manager of the `ObjectSet`. This is the `Object` that manages this set of objects. :param field: The field on the `manager` that created this managed `ObjectSet`. :param items: The ite...
[ "Create", "a", "custom", "ObjectSet", "that", "is", "managed", "by", "a", "related", "Object", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L529-L547
train
maas/python-libmaas
maas/client/viscera/__init__.py
ObjectField.Checked
def Checked(cls, name, datum_to_value=None, value_to_datum=None, **other): """Create a custom `ObjectField` that validates values and datums. :param name: The name of the field. This is the name that's used to store the datum in the MAAS-side data dictionary. :param datum_to_value: ...
python
def Checked(cls, name, datum_to_value=None, value_to_datum=None, **other): """Create a custom `ObjectField` that validates values and datums. :param name: The name of the field. This is the name that's used to store the datum in the MAAS-side data dictionary. :param datum_to_value: ...
[ "def", "Checked", "(", "cls", ",", "name", ",", "datum_to_value", "=", "None", ",", "value_to_datum", "=", "None", ",", "**", "other", ")", ":", "attrs", "=", "{", "}", "if", "datum_to_value", "is", "not", "None", ":", "@", "wraps", "(", "datum_to_valu...
Create a custom `ObjectField` that validates values and datums. :param name: The name of the field. This is the name that's used to store the datum in the MAAS-side data dictionary. :param datum_to_value: A callable taking a single ``datum`` argument, passed positionally. This c...
[ "Create", "a", "custom", "ObjectField", "that", "validates", "values", "and", "datums", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L648-L674
train
maas/python-libmaas
maas/client/viscera/__init__.py
ObjectFieldRelated.value_to_datum
def value_to_datum(self, instance, value): """Convert a given Python-side value to a MAAS-side datum. :param instance: The `Object` instance on which this field is currently operating. This method should treat it as read-only, for example to perform validation with regards to ot...
python
def value_to_datum(self, instance, value): """Convert a given Python-side value to a MAAS-side datum. :param instance: The `Object` instance on which this field is currently operating. This method should treat it as read-only, for example to perform validation with regards to ot...
[ "def", "value_to_datum", "(", "self", ",", "instance", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "bound", "=", "getattr", "(", "instance", ".", "_origin", ",", "self", ".", "cls", ")", "if", "type", "(", "value", ")"...
Convert a given Python-side value to a MAAS-side datum. :param instance: The `Object` instance on which this field is currently operating. This method should treat it as read-only, for example to perform validation with regards to other fields. :param datum: The Python-side valu...
[ "Convert", "a", "given", "Python", "-", "side", "value", "to", "a", "MAAS", "-", "side", "datum", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L855-L888
train
maas/python-libmaas
maas/client/viscera/__init__.py
OriginType.fromURL
async def fromURL(cls, url, *, credentials=None, insecure=False): """Return an `Origin` for a given MAAS instance.""" session = await bones.SessionAPI.fromURL( url, credentials=credentials, insecure=insecure) return cls(session)
python
async def fromURL(cls, url, *, credentials=None, insecure=False): """Return an `Origin` for a given MAAS instance.""" session = await bones.SessionAPI.fromURL( url, credentials=credentials, insecure=insecure) return cls(session)
[ "async", "def", "fromURL", "(", "cls", ",", "url", ",", "*", ",", "credentials", "=", "None", ",", "insecure", "=", "False", ")", ":", "session", "=", "await", "bones", ".", "SessionAPI", ".", "fromURL", "(", "url", ",", "credentials", "=", "credential...
Return an `Origin` for a given MAAS instance.
[ "Return", "an", "Origin", "for", "a", "given", "MAAS", "instance", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L1108-L1112
train
maas/python-libmaas
maas/client/viscera/__init__.py
OriginType.fromProfile
def fromProfile(cls, profile): """Return an `Origin` from a given configuration profile. :see: `ProfileStore`. """ session = bones.SessionAPI.fromProfile(profile) return cls(session)
python
def fromProfile(cls, profile): """Return an `Origin` from a given configuration profile. :see: `ProfileStore`. """ session = bones.SessionAPI.fromProfile(profile) return cls(session)
[ "def", "fromProfile", "(", "cls", ",", "profile", ")", ":", "session", "=", "bones", ".", "SessionAPI", ".", "fromProfile", "(", "profile", ")", "return", "cls", "(", "session", ")" ]
Return an `Origin` from a given configuration profile. :see: `ProfileStore`.
[ "Return", "an", "Origin", "from", "a", "given", "configuration", "profile", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L1114-L1120
train
maas/python-libmaas
maas/client/viscera/__init__.py
OriginType.fromProfileName
def fromProfileName(cls, name): """Return an `Origin` from a given configuration profile name. :see: `ProfileStore`. """ session = bones.SessionAPI.fromProfileName(name) return cls(session)
python
def fromProfileName(cls, name): """Return an `Origin` from a given configuration profile name. :see: `ProfileStore`. """ session = bones.SessionAPI.fromProfileName(name) return cls(session)
[ "def", "fromProfileName", "(", "cls", ",", "name", ")", ":", "session", "=", "bones", ".", "SessionAPI", ".", "fromProfileName", "(", "name", ")", "return", "cls", "(", "session", ")" ]
Return an `Origin` from a given configuration profile name. :see: `ProfileStore`.
[ "Return", "an", "Origin", "from", "a", "given", "configuration", "profile", "name", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L1122-L1128
train
maas/python-libmaas
maas/client/viscera/__init__.py
OriginType.login
async def login( cls, url, *, username=None, password=None, insecure=False): """Make an `Origin` by logging-in with a username and password. :return: A tuple of ``profile`` and ``origin``, where the former is an unsaved `Profile` instance, and the latter is an `Origin` instance ...
python
async def login( cls, url, *, username=None, password=None, insecure=False): """Make an `Origin` by logging-in with a username and password. :return: A tuple of ``profile`` and ``origin``, where the former is an unsaved `Profile` instance, and the latter is an `Origin` instance ...
[ "async", "def", "login", "(", "cls", ",", "url", ",", "*", ",", "username", "=", "None", ",", "password", "=", "None", ",", "insecure", "=", "False", ")", ":", "profile", ",", "session", "=", "await", "bones", ".", "SessionAPI", ".", "login", "(", ...
Make an `Origin` by logging-in with a username and password. :return: A tuple of ``profile`` and ``origin``, where the former is an unsaved `Profile` instance, and the latter is an `Origin` instance made using the profile.
[ "Make", "an", "Origin", "by", "logging", "-", "in", "with", "a", "username", "and", "password", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L1130-L1140
train
maas/python-libmaas
maas/client/viscera/__init__.py
OriginType.connect
async def connect( cls, url, *, apikey=None, insecure=False): """Make an `Origin` by connecting with an apikey. :return: A tuple of ``profile`` and ``origin``, where the former is an unsaved `Profile` instance, and the latter is an `Origin` instance made using the pr...
python
async def connect( cls, url, *, apikey=None, insecure=False): """Make an `Origin` by connecting with an apikey. :return: A tuple of ``profile`` and ``origin``, where the former is an unsaved `Profile` instance, and the latter is an `Origin` instance made using the pr...
[ "async", "def", "connect", "(", "cls", ",", "url", ",", "*", ",", "apikey", "=", "None", ",", "insecure", "=", "False", ")", ":", "profile", ",", "session", "=", "await", "bones", ".", "SessionAPI", ".", "connect", "(", "url", "=", "url", ",", "api...
Make an `Origin` by connecting with an apikey. :return: A tuple of ``profile`` and ``origin``, where the former is an unsaved `Profile` instance, and the latter is an `Origin` instance made using the profile.
[ "Make", "an", "Origin", "by", "connecting", "with", "an", "apikey", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L1142-L1152
train
maas/python-libmaas
maas/client/facade.py
facade
def facade(factory): """Declare a method as a facade factory.""" wrapper = FacadeDescriptor(factory.__name__, factory) return update_wrapper(wrapper, factory)
python
def facade(factory): """Declare a method as a facade factory.""" wrapper = FacadeDescriptor(factory.__name__, factory) return update_wrapper(wrapper, factory)
[ "def", "facade", "(", "factory", ")", ":", "wrapper", "=", "FacadeDescriptor", "(", "factory", ".", "__name__", ",", "factory", ")", "return", "update_wrapper", "(", "wrapper", ",", "factory", ")" ]
Declare a method as a facade factory.
[ "Declare", "a", "method", "as", "a", "facade", "factory", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/facade.py#L61-L64
train
maas/python-libmaas
maas/client/viscera/partitions.py
Partition.delete
async def delete(self): """Delete this partition.""" await self._handler.delete( system_id=self.block_device.node.system_id, device_id=self.block_device.id, id=self.id)
python
async def delete(self): """Delete this partition.""" await self._handler.delete( system_id=self.block_device.node.system_id, device_id=self.block_device.id, id=self.id)
[ "async", "def", "delete", "(", "self", ")", ":", "await", "self", ".", "_handler", ".", "delete", "(", "system_id", "=", "self", ".", "block_device", ".", "node", ".", "system_id", ",", "device_id", "=", "self", ".", "block_device", ".", "id", ",", "id...
Delete this partition.
[ "Delete", "this", "partition", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/partitions.py#L78-L82
train
maas/python-libmaas
maas/client/viscera/partitions.py
Partition.unformat
async def unformat(self): """Unformat this partition.""" self._data = await self._handler.unformat( system_id=self.block_device.node.system_id, device_id=self.block_device.id, id=self.id)
python
async def unformat(self): """Unformat this partition.""" self._data = await self._handler.unformat( system_id=self.block_device.node.system_id, device_id=self.block_device.id, id=self.id)
[ "async", "def", "unformat", "(", "self", ")", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "unformat", "(", "system_id", "=", "self", ".", "block_device", ".", "node", ".", "system_id", ",", "device_id", "=", "self", ".", "blo...
Unformat this partition.
[ "Unformat", "this", "partition", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/partitions.py#L91-L95
train
maas/python-libmaas
maas/client/viscera/partitions.py
Partition.mount
async def mount(self, mount_point, *, mount_options=None): """Mount this partition.""" self._data = await self._handler.mount( system_id=self.block_device.node.system_id, device_id=self.block_device.id, id=self.id, mount_point=mount_point, mount_options=mo...
python
async def mount(self, mount_point, *, mount_options=None): """Mount this partition.""" self._data = await self._handler.mount( system_id=self.block_device.node.system_id, device_id=self.block_device.id, id=self.id, mount_point=mount_point, mount_options=mo...
[ "async", "def", "mount", "(", "self", ",", "mount_point", ",", "*", ",", "mount_options", "=", "None", ")", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "mount", "(", "system_id", "=", "self", ".", "block_device", ".", "node",...
Mount this partition.
[ "Mount", "this", "partition", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/partitions.py#L97-L103
train
maas/python-libmaas
maas/client/viscera/partitions.py
Partition.umount
async def umount(self): """Unmount this partition.""" self._data = await self._handler.unmount( system_id=self.block_device.node.system_id, device_id=self.block_device.id, id=self.id)
python
async def umount(self): """Unmount this partition.""" self._data = await self._handler.unmount( system_id=self.block_device.node.system_id, device_id=self.block_device.id, id=self.id)
[ "async", "def", "umount", "(", "self", ")", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "unmount", "(", "system_id", "=", "self", ".", "block_device", ".", "node", ".", "system_id", ",", "device_id", "=", "self", ".", "block_...
Unmount this partition.
[ "Unmount", "this", "partition", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/partitions.py#L105-L109
train
maas/python-libmaas
maas/client/viscera/partitions.py
PartitionsType.read
async def read(cls, node, block_device): """Get list of `Partitions`'s for `node` and `block_device`.""" if isinstance(node, str): system_id = node elif isinstance(node, Node): system_id = node.system_id else: raise TypeError( "node mus...
python
async def read(cls, node, block_device): """Get list of `Partitions`'s for `node` and `block_device`.""" if isinstance(node, str): system_id = node elif isinstance(node, Node): system_id = node.system_id else: raise TypeError( "node mus...
[ "async", "def", "read", "(", "cls", ",", "node", ",", "block_device", ")", ":", "if", "isinstance", "(", "node", ",", "str", ")", ":", "system_id", "=", "node", "elif", "isinstance", "(", "node", ",", "Node", ")", ":", "system_id", "=", "node", ".", ...
Get list of `Partitions`'s for `node` and `block_device`.
[ "Get", "list", "of", "Partitions", "s", "for", "node", "and", "block_device", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/partitions.py#L115-L137
train
maas/python-libmaas
maas/client/viscera/partitions.py
PartitionsType.create
async def create(cls, block_device: BlockDevice, size: int): """ Create a partition on a block device. :param block_device: BlockDevice to create the paritition on. :type block_device: `BlockDevice` :param size: The size of the partition in bytes. :type size: `int` ...
python
async def create(cls, block_device: BlockDevice, size: int): """ Create a partition on a block device. :param block_device: BlockDevice to create the paritition on. :type block_device: `BlockDevice` :param size: The size of the partition in bytes. :type size: `int` ...
[ "async", "def", "create", "(", "cls", ",", "block_device", ":", "BlockDevice", ",", "size", ":", "int", ")", ":", "params", "=", "{", "}", "if", "isinstance", "(", "block_device", ",", "BlockDevice", ")", ":", "params", "[", "'system_id'", "]", "=", "b...
Create a partition on a block device. :param block_device: BlockDevice to create the paritition on. :type block_device: `BlockDevice` :param size: The size of the partition in bytes. :type size: `int`
[ "Create", "a", "partition", "on", "a", "block", "device", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/partitions.py#L139-L160
train
maas/python-libmaas
maas/client/utils/maas_async.py
asynchronous
def asynchronous(func): """Return `func` in a "smart" asynchronous-aware wrapper. If `func` is called within the event-loop — i.e. when it is running — this returns the result of `func` without alteration. However, when called from outside of the event-loop, and the result is awaitable, the result will...
python
def asynchronous(func): """Return `func` in a "smart" asynchronous-aware wrapper. If `func` is called within the event-loop — i.e. when it is running — this returns the result of `func` without alteration. However, when called from outside of the event-loop, and the result is awaitable, the result will...
[ "def", "asynchronous", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "eventloop", "=", "get_event_loop", "(", ")", "result", "=", "func", "(", "*", "args", ",", "**", "kwar...
Return `func` in a "smart" asynchronous-aware wrapper. If `func` is called within the event-loop — i.e. when it is running — this returns the result of `func` without alteration. However, when called from outside of the event-loop, and the result is awaitable, the result will be passed though the curre...
[ "Return", "func", "in", "a", "smart", "asynchronous", "-", "aware", "wrapper", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/maas_async.py#L31-L52
train
maas/python-libmaas
maas/client/utils/maas_async.py
_maybe_wrap
def _maybe_wrap(attribute): """Helper for `Asynchronous`.""" if iscoroutinefunction(attribute): return asynchronous(attribute) if isinstance(attribute, (classmethod, staticmethod)): if iscoroutinefunction(attribute.__func__): return attribute.__class__(asynchronous(attribute.__fu...
python
def _maybe_wrap(attribute): """Helper for `Asynchronous`.""" if iscoroutinefunction(attribute): return asynchronous(attribute) if isinstance(attribute, (classmethod, staticmethod)): if iscoroutinefunction(attribute.__func__): return attribute.__class__(asynchronous(attribute.__fu...
[ "def", "_maybe_wrap", "(", "attribute", ")", ":", "if", "iscoroutinefunction", "(", "attribute", ")", ":", "return", "asynchronous", "(", "attribute", ")", "if", "isinstance", "(", "attribute", ",", "(", "classmethod", ",", "staticmethod", ")", ")", ":", "if...
Helper for `Asynchronous`.
[ "Helper", "for", "Asynchronous", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/maas_async.py#L68-L75
train
maas/python-libmaas
maas/client/viscera/subnets.py
SubnetsType.create
async def create( cls, cidr: str, vlan: Union[Vlan, int] = None, *, name: str = None, description: str = None, gateway_ip: str = None, rdns_mode: RDNSMode = None, dns_servers: Union[Sequence[str], str] = None, managed: bool = None): """ Create ...
python
async def create( cls, cidr: str, vlan: Union[Vlan, int] = None, *, name: str = None, description: str = None, gateway_ip: str = None, rdns_mode: RDNSMode = None, dns_servers: Union[Sequence[str], str] = None, managed: bool = None): """ Create ...
[ "async", "def", "create", "(", "cls", ",", "cidr", ":", "str", ",", "vlan", ":", "Union", "[", "Vlan", ",", "int", "]", "=", "None", ",", "*", ",", "name", ":", "str", "=", "None", ",", "description", ":", "str", "=", "None", ",", "gateway_ip", ...
Create a `Subnet` in MAAS. :param cidr: The cidr of the `Subnet` (required). :type cidr: `str` :param vlan: The VLAN of the `Subnet` (required). :type vlan: `Vlan` :param name: The name of the `Subnet` (optional, will be given a default value if not specified). :...
[ "Create", "a", "Subnet", "in", "MAAS", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/subnets.py#L34-L88
train
maas/python-libmaas
maas/client/viscera/subnets.py
Subnet.save
async def save(self): """Save this subnet.""" if 'vlan' in self._changed_data and self._changed_data['vlan']: # Update uses the ID of the VLAN, not the VLAN object. self._changed_data['vlan'] = self._changed_data['vlan']['id'] if (self._orig_data['vlan'] and ...
python
async def save(self): """Save this subnet.""" if 'vlan' in self._changed_data and self._changed_data['vlan']: # Update uses the ID of the VLAN, not the VLAN object. self._changed_data['vlan'] = self._changed_data['vlan']['id'] if (self._orig_data['vlan'] and ...
[ "async", "def", "save", "(", "self", ")", ":", "if", "'vlan'", "in", "self", ".", "_changed_data", "and", "self", ".", "_changed_data", "[", "'vlan'", "]", ":", "self", ".", "_changed_data", "[", "'vlan'", "]", "=", "self", ".", "_changed_data", "[", "...
Save this subnet.
[ "Save", "this", "subnet", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/subnets.py#L132-L144
train
maas/python-libmaas
maas/client/utils/__init__.py
urlencode
def urlencode(data): """A version of `urllib.urlencode` that isn't insane. This only cares that `data` is an iterable of iterables. Each sub-iterable must be of overall length 2, i.e. a name/value pair. Unicode strings will be encoded to UTF-8. This is what Django expects; see `smart_text` in the ...
python
def urlencode(data): """A version of `urllib.urlencode` that isn't insane. This only cares that `data` is an iterable of iterables. Each sub-iterable must be of overall length 2, i.e. a name/value pair. Unicode strings will be encoded to UTF-8. This is what Django expects; see `smart_text` in the ...
[ "def", "urlencode", "(", "data", ")", ":", "def", "dec", "(", "string", ")", ":", "if", "isinstance", "(", "string", ",", "bytes", ")", ":", "string", "=", "string", ".", "decode", "(", "\"utf-8\"", ")", "return", "quote_plus", "(", "string", ")", "r...
A version of `urllib.urlencode` that isn't insane. This only cares that `data` is an iterable of iterables. Each sub-iterable must be of overall length 2, i.e. a name/value pair. Unicode strings will be encoded to UTF-8. This is what Django expects; see `smart_text` in the Django documentation.
[ "A", "version", "of", "urllib", ".", "urlencode", "that", "isn", "t", "insane", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/__init__.py#L63-L79
train
maas/python-libmaas
maas/client/utils/__init__.py
sign
def sign(uri, headers, credentials): """Sign the URI and headers. A request method of `GET` with no body content is assumed. :param credentials: A tuple of consumer key, token key, and token secret. """ consumer_key, token_key, token_secret = credentials auth = OAuthSigner(token_key, token_sec...
python
def sign(uri, headers, credentials): """Sign the URI and headers. A request method of `GET` with no body content is assumed. :param credentials: A tuple of consumer key, token key, and token secret. """ consumer_key, token_key, token_secret = credentials auth = OAuthSigner(token_key, token_sec...
[ "def", "sign", "(", "uri", ",", "headers", ",", "credentials", ")", ":", "consumer_key", ",", "token_key", ",", "token_secret", "=", "credentials", "auth", "=", "OAuthSigner", "(", "token_key", ",", "token_secret", ",", "consumer_key", ",", "\"\"", ")", "aut...
Sign the URI and headers. A request method of `GET` with no body content is assumed. :param credentials: A tuple of consumer key, token key, and token secret.
[ "Sign", "the", "URI", "and", "headers", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/__init__.py#L166-L175
train
maas/python-libmaas
maas/client/utils/__init__.py
parse_docstring
def parse_docstring(thing): """Parse a Python docstring, or the docstring found on `thing`. :return: a ``(title, body)`` tuple. As per docstring convention, title is the docstring's first paragraph and body is the rest. """ assert not isinstance(thing, bytes) doc = cleandoc(thing) if isinst...
python
def parse_docstring(thing): """Parse a Python docstring, or the docstring found on `thing`. :return: a ``(title, body)`` tuple. As per docstring convention, title is the docstring's first paragraph and body is the rest. """ assert not isinstance(thing, bytes) doc = cleandoc(thing) if isinst...
[ "def", "parse_docstring", "(", "thing", ")", ":", "assert", "not", "isinstance", "(", "thing", ",", "bytes", ")", "doc", "=", "cleandoc", "(", "thing", ")", "if", "isinstance", "(", "thing", ",", "str", ")", "else", "getdoc", "(", "thing", ")", "doc", ...
Parse a Python docstring, or the docstring found on `thing`. :return: a ``(title, body)`` tuple. As per docstring convention, title is the docstring's first paragraph and body is the rest.
[ "Parse", "a", "Python", "docstring", "or", "the", "docstring", "found", "on", "thing", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/__init__.py#L194-L214
train
maas/python-libmaas
maas/client/utils/__init__.py
api_url
def api_url(string): """Ensure that `string` looks like a URL to the API. This ensures that the API version is specified explicitly (i.e. the path ends with /api/{version}). If not, version 2.0 is selected. It also ensures that the path ends with a forward-slash. This is suitable for use as an arg...
python
def api_url(string): """Ensure that `string` looks like a URL to the API. This ensures that the API version is specified explicitly (i.e. the path ends with /api/{version}). If not, version 2.0 is selected. It also ensures that the path ends with a forward-slash. This is suitable for use as an arg...
[ "def", "api_url", "(", "string", ")", ":", "url", "=", "urlparse", "(", "string", ")", "url", "=", "url", ".", "_replace", "(", "path", "=", "ensure_trailing_slash", "(", "url", ".", "path", ")", ")", "if", "re", ".", "search", "(", "\"/api/[0-9.]+/?$\...
Ensure that `string` looks like a URL to the API. This ensures that the API version is specified explicitly (i.e. the path ends with /api/{version}). If not, version 2.0 is selected. It also ensures that the path ends with a forward-slash. This is suitable for use as an argument type with argparse.
[ "Ensure", "that", "string", "looks", "like", "a", "URL", "to", "the", "API", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/__init__.py#L222-L235
train
maas/python-libmaas
maas/client/utils/__init__.py
vars_class
def vars_class(cls): """Return a dict of vars for the given class, including all ancestors. This differs from the usual behaviour of `vars` which returns attributes belonging to the given class and not its ancestors. """ return dict(chain.from_iterable( vars(cls).items() for cls in reversed...
python
def vars_class(cls): """Return a dict of vars for the given class, including all ancestors. This differs from the usual behaviour of `vars` which returns attributes belonging to the given class and not its ancestors. """ return dict(chain.from_iterable( vars(cls).items() for cls in reversed...
[ "def", "vars_class", "(", "cls", ")", ":", "return", "dict", "(", "chain", ".", "from_iterable", "(", "vars", "(", "cls", ")", ".", "items", "(", ")", "for", "cls", "in", "reversed", "(", "cls", ".", "__mro__", ")", ")", ")" ]
Return a dict of vars for the given class, including all ancestors. This differs from the usual behaviour of `vars` which returns attributes belonging to the given class and not its ancestors.
[ "Return", "a", "dict", "of", "vars", "for", "the", "given", "class", "including", "all", "ancestors", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/__init__.py#L245-L252
train
maas/python-libmaas
maas/client/utils/__init__.py
remove_None
def remove_None(params: dict): """Remove all keys in `params` that have the value of `None`.""" return { key: value for key, value in params.items() if value is not None }
python
def remove_None(params: dict): """Remove all keys in `params` that have the value of `None`.""" return { key: value for key, value in params.items() if value is not None }
[ "def", "remove_None", "(", "params", ":", "dict", ")", ":", "return", "{", "key", ":", "value", "for", "key", ",", "value", "in", "params", ".", "items", "(", ")", "if", "value", "is", "not", "None", "}" ]
Remove all keys in `params` that have the value of `None`.
[ "Remove", "all", "keys", "in", "params", "that", "have", "the", "value", "of", "None", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/__init__.py#L325-L331
train
maas/python-libmaas
maas/client/utils/__init__.py
OAuthSigner.sign_request
def sign_request(self, url, method, body, headers): """Sign a request. :param url: The URL to which the request is to be sent. :param headers: The headers in the request. These will be updated with the signature. """ # The use of PLAINTEXT here was copied from MAAS, ...
python
def sign_request(self, url, method, body, headers): """Sign a request. :param url: The URL to which the request is to be sent. :param headers: The headers in the request. These will be updated with the signature. """ # The use of PLAINTEXT here was copied from MAAS, ...
[ "def", "sign_request", "(", "self", ",", "url", ",", "method", ",", "body", ",", "headers", ")", ":", "client", "=", "oauth1", ".", "Client", "(", "self", ".", "consumer_key", ",", "self", ".", "consumer_secret", ",", "self", ".", "token_key", ",", "se...
Sign a request. :param url: The URL to which the request is to be sent. :param headers: The headers in the request. These will be updated with the signature.
[ "Sign", "a", "request", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/__init__.py#L145-L163
train
maas/python-libmaas
maas/client/utils/__init__.py
SpinnerContext.print
def print(self, *args, **kwargs): """Print inside of the spinner context. This must be used when inside of a spinner context to ensure that the line printed doesn't overwrite an already existing spinner line. """ clear_len = max(len(self._prev_msg), len(self.msg)) + 4 se...
python
def print(self, *args, **kwargs): """Print inside of the spinner context. This must be used when inside of a spinner context to ensure that the line printed doesn't overwrite an already existing spinner line. """ clear_len = max(len(self._prev_msg), len(self.msg)) + 4 se...
[ "def", "print", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "clear_len", "=", "max", "(", "len", "(", "self", ".", "_prev_msg", ")", ",", "len", "(", "self", ".", "msg", ")", ")", "+", "4", "self", ".", "spinner", ".", "stream...
Print inside of the spinner context. This must be used when inside of a spinner context to ensure that the line printed doesn't overwrite an already existing spinner line.
[ "Print", "inside", "of", "the", "spinner", "context", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/__init__.py#L342-L350
train
maas/python-libmaas
maas/client/viscera/raids.py
RaidsType.create
async def create( cls, node: Union[Node, str], level: Union[RaidLevel, str], devices: Iterable[Union[BlockDevice, Partition]], *, name: str = None, uuid: str = None, spare_devices: Iterable[Union[BlockDevice, Partition]]): """ Create a RAID on ...
python
async def create( cls, node: Union[Node, str], level: Union[RaidLevel, str], devices: Iterable[Union[BlockDevice, Partition]], *, name: str = None, uuid: str = None, spare_devices: Iterable[Union[BlockDevice, Partition]]): """ Create a RAID on ...
[ "async", "def", "create", "(", "cls", ",", "node", ":", "Union", "[", "Node", ",", "str", "]", ",", "level", ":", "Union", "[", "RaidLevel", ",", "str", "]", ",", "devices", ":", "Iterable", "[", "Union", "[", "BlockDevice", ",", "Partition", "]", ...
Create a RAID on a Node. :param node: Node to create the interface on. :type node: `Node` or `str` :param level: RAID level. :type level: `RaidLevel` :param devices: Mixed list of block devices or partitions to create the RAID from. :type devices: iterable of...
[ "Create", "a", "RAID", "on", "a", "Node", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/raids.py#L88-L166
train
maas/python-libmaas
maas/client/viscera/static_routes.py
StaticRoutesType.create
async def create(cls, destination: Union[int, Subnet], source: Union[int, Subnet], gateway_ip: str, metric: int): """ Create a `StaticRoute` in MAAS. :param name: The name of the `StaticRoute` (optional, will be given a default value if not specified). :type...
python
async def create(cls, destination: Union[int, Subnet], source: Union[int, Subnet], gateway_ip: str, metric: int): """ Create a `StaticRoute` in MAAS. :param name: The name of the `StaticRoute` (optional, will be given a default value if not specified). :type...
[ "async", "def", "create", "(", "cls", ",", "destination", ":", "Union", "[", "int", ",", "Subnet", "]", ",", "source", ":", "Union", "[", "int", ",", "Subnet", "]", ",", "gateway_ip", ":", "str", ",", "metric", ":", "int", ")", ":", "params", "=", ...
Create a `StaticRoute` in MAAS. :param name: The name of the `StaticRoute` (optional, will be given a default value if not specified). :type name: `str` :param description: A description of the `StaticRoute` (optional). :type description: `str` :param class_type: The cla...
[ "Create", "a", "StaticRoute", "in", "MAAS", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/static_routes.py#L27-L54
train
pytest-dev/pytest-runner
ptr.py
CustomizedDist.fetch_build_egg
def fetch_build_egg(self, req): """ Specialized version of Distribution.fetch_build_egg that respects respects allow_hosts and index_url. """ from setuptools.command.easy_install import easy_install dist = Distribution({'script_args': ['easy_install']}) dist.parse_config_files() opts = dist.get_option_dict(...
python
def fetch_build_egg(self, req): """ Specialized version of Distribution.fetch_build_egg that respects respects allow_hosts and index_url. """ from setuptools.command.easy_install import easy_install dist = Distribution({'script_args': ['easy_install']}) dist.parse_config_files() opts = dist.get_option_dict(...
[ "def", "fetch_build_egg", "(", "self", ",", "req", ")", ":", "from", "setuptools", ".", "command", ".", "easy_install", "import", "easy_install", "dist", "=", "Distribution", "(", "{", "'script_args'", ":", "[", "'easy_install'", "]", "}", ")", "dist", ".", ...
Specialized version of Distribution.fetch_build_egg that respects respects allow_hosts and index_url.
[ "Specialized", "version", "of", "Distribution", ".", "fetch_build_egg", "that", "respects", "respects", "allow_hosts", "and", "index_url", "." ]
1bfab3a9b1cc68a3c8a2722fe1a7522ddc61ec2e
https://github.com/pytest-dev/pytest-runner/blob/1bfab3a9b1cc68a3c8a2722fe1a7522ddc61ec2e/ptr.py#L40-L72
train
PokeAPI/pokepy
pokepy/api.py
V2Client._caching
def _caching(self, disk_or_memory, cache_directory=None): """ Decorator that allows caching the outputs of the BaseClient get methods. Cache can be either disk- or memory-based. Disk-based cache is reloaded automatically between runs if the same cache directory is specified. ...
python
def _caching(self, disk_or_memory, cache_directory=None): """ Decorator that allows caching the outputs of the BaseClient get methods. Cache can be either disk- or memory-based. Disk-based cache is reloaded automatically between runs if the same cache directory is specified. ...
[ "def", "_caching", "(", "self", ",", "disk_or_memory", ",", "cache_directory", "=", "None", ")", ":", "if", "disk_or_memory", "not", "in", "(", "'disk'", ",", "'memory'", ")", ":", "raise", "ValueError", "(", "'Accepted values are \"disk\" or \"memory\"'", ")", ...
Decorator that allows caching the outputs of the BaseClient get methods. Cache can be either disk- or memory-based. Disk-based cache is reloaded automatically between runs if the same cache directory is specified. Cache is kept per each unique uid. ex: >> client.get_poke...
[ "Decorator", "that", "allows", "caching", "the", "outputs", "of", "the", "BaseClient", "get", "methods", ".", "Cache", "can", "be", "either", "disk", "-", "or", "memory", "-", "based", ".", "Disk", "-", "based", "cache", "is", "reloaded", "automatically", ...
1154649c4d28414e487080d2601acd4912eeb8a5
https://github.com/PokeAPI/pokepy/blob/1154649c4d28414e487080d2601acd4912eeb8a5/pokepy/api.py#L170-L272
train
PokeAPI/pokepy
pokepy/resources_v2.py
BaseResource.set_subresources
def set_subresources(self, **kwargs): """Same logic as the original except for the first 'if' clause.""" for attribute_name, resource in self._subresource_map.items(): sub_attr = kwargs.get(attribute_name) if sub_attr is None: # Attribute was not found or is null ...
python
def set_subresources(self, **kwargs): """Same logic as the original except for the first 'if' clause.""" for attribute_name, resource in self._subresource_map.items(): sub_attr = kwargs.get(attribute_name) if sub_attr is None: # Attribute was not found or is null ...
[ "def", "set_subresources", "(", "self", ",", "**", "kwargs", ")", ":", "for", "attribute_name", ",", "resource", "in", "self", ".", "_subresource_map", ".", "items", "(", ")", ":", "sub_attr", "=", "kwargs", ".", "get", "(", "attribute_name", ")", "if", ...
Same logic as the original except for the first 'if' clause.
[ "Same", "logic", "as", "the", "original", "except", "for", "the", "first", "if", "clause", "." ]
1154649c4d28414e487080d2601acd4912eeb8a5
https://github.com/PokeAPI/pokepy/blob/1154649c4d28414e487080d2601acd4912eeb8a5/pokepy/resources_v2.py#L19-L32
train
fbradyirl/hikvision
hikvision/api.py
build_url_base
def build_url_base(host, port, is_https): """ Make base of url based on config """ base = "http" if is_https: base += 's' base += "://" base += host if port: base += ":" base += str(port) return base
python
def build_url_base(host, port, is_https): """ Make base of url based on config """ base = "http" if is_https: base += 's' base += "://" base += host if port: base += ":" base += str(port) return base
[ "def", "build_url_base", "(", "host", ",", "port", ",", "is_https", ")", ":", "base", "=", "\"http\"", "if", "is_https", ":", "base", "+=", "'s'", "base", "+=", "\"://\"", "base", "+=", "host", "if", "port", ":", "base", "+=", "\":\"", "base", "+=", ...
Make base of url based on config
[ "Make", "base", "of", "url", "based", "on", "config" ]
3bc3b20b8f7d793cf9dd94777e4b8e82bfd4abc6
https://github.com/fbradyirl/hikvision/blob/3bc3b20b8f7d793cf9dd94777e4b8e82bfd4abc6/hikvision/api.py#L27-L42
train
fbradyirl/hikvision
hikvision/api.py
CreateDevice.is_motion_detection_enabled
def is_motion_detection_enabled(self): """ Get current state of Motion Detection """ response = requests.get(self.motion_url, auth=HTTPBasicAuth( self._username, self._password)) _LOGGING.debug('Response: %s', response.text) if response.status_code != 200: _LOGG...
python
def is_motion_detection_enabled(self): """ Get current state of Motion Detection """ response = requests.get(self.motion_url, auth=HTTPBasicAuth( self._username, self._password)) _LOGGING.debug('Response: %s', response.text) if response.status_code != 200: _LOGG...
[ "def", "is_motion_detection_enabled", "(", "self", ")", ":", "response", "=", "requests", ".", "get", "(", "self", ".", "motion_url", ",", "auth", "=", "HTTPBasicAuth", "(", "self", ".", "_username", ",", "self", ".", "_password", ")", ")", "_LOGGING", "."...
Get current state of Motion Detection
[ "Get", "current", "state", "of", "Motion", "Detection" ]
3bc3b20b8f7d793cf9dd94777e4b8e82bfd4abc6
https://github.com/fbradyirl/hikvision/blob/3bc3b20b8f7d793cf9dd94777e4b8e82bfd4abc6/hikvision/api.py#L165-L225
train
fbradyirl/hikvision
hikvision/api.py
CreateDevice.put_motion_detection_xml
def put_motion_detection_xml(self, xml): """ Put request with xml Motion Detection """ _LOGGING.debug('xml:') _LOGGING.debug("%s", xml) headers = DEFAULT_HEADERS headers['Content-Length'] = len(xml) headers['Host'] = self._host response = requests.put(self.motio...
python
def put_motion_detection_xml(self, xml): """ Put request with xml Motion Detection """ _LOGGING.debug('xml:') _LOGGING.debug("%s", xml) headers = DEFAULT_HEADERS headers['Content-Length'] = len(xml) headers['Host'] = self._host response = requests.put(self.motio...
[ "def", "put_motion_detection_xml", "(", "self", ",", "xml", ")", ":", "_LOGGING", ".", "debug", "(", "'xml:'", ")", "_LOGGING", ".", "debug", "(", "\"%s\"", ",", "xml", ")", "headers", "=", "DEFAULT_HEADERS", "headers", "[", "'Content-Length'", "]", "=", "...
Put request with xml Motion Detection
[ "Put", "request", "with", "xml", "Motion", "Detection" ]
3bc3b20b8f7d793cf9dd94777e4b8e82bfd4abc6
https://github.com/fbradyirl/hikvision/blob/3bc3b20b8f7d793cf9dd94777e4b8e82bfd4abc6/hikvision/api.py#L237-L273
train
marrow/mailer
marrow/mailer/validator.py
DomainValidator._apply_common_rules
def _apply_common_rules(self, part, maxlength): """This method contains the rules that must be applied to both the domain and the local part of the e-mail address. """ part = part.strip() if self.fix: part = part.strip('.') if not part: ...
python
def _apply_common_rules(self, part, maxlength): """This method contains the rules that must be applied to both the domain and the local part of the e-mail address. """ part = part.strip() if self.fix: part = part.strip('.') if not part: ...
[ "def", "_apply_common_rules", "(", "self", ",", "part", ",", "maxlength", ")", ":", "part", "=", "part", ".", "strip", "(", ")", "if", "self", ".", "fix", ":", "part", "=", "part", ".", "strip", "(", "'.'", ")", "if", "not", "part", ":", "return", ...
This method contains the rules that must be applied to both the domain and the local part of the e-mail address.
[ "This", "method", "contains", "the", "rules", "that", "must", "be", "applied", "to", "both", "the", "domain", "and", "the", "local", "part", "of", "the", "e", "-", "mail", "address", "." ]
3995ef98a3f7feb75f1aeb652e6afe40a5c94def
https://github.com/marrow/mailer/blob/3995ef98a3f7feb75f1aeb652e6afe40a5c94def/marrow/mailer/validator.py#L160-L184
train
marrow/mailer
marrow/mailer/message.py
Message.mime
def mime(self): """Produce the final MIME message.""" author = self.author sender = self.sender if not author: raise ValueError("You must specify an author.") if not self.subject: raise ValueError("You must specify a subject.") if len(self.recipients) == 0: raise ValueError("You must specify a...
python
def mime(self): """Produce the final MIME message.""" author = self.author sender = self.sender if not author: raise ValueError("You must specify an author.") if not self.subject: raise ValueError("You must specify a subject.") if len(self.recipients) == 0: raise ValueError("You must specify a...
[ "def", "mime", "(", "self", ")", ":", "author", "=", "self", ".", "author", "sender", "=", "self", ".", "sender", "if", "not", "author", ":", "raise", "ValueError", "(", "\"You must specify an author.\"", ")", "if", "not", "self", ".", "subject", ":", "r...
Produce the final MIME message.
[ "Produce", "the", "final", "MIME", "message", "." ]
3995ef98a3f7feb75f1aeb652e6afe40a5c94def
https://github.com/marrow/mailer/blob/3995ef98a3f7feb75f1aeb652e6afe40a5c94def/marrow/mailer/message.py#L209-L252
train
marrow/mailer
marrow/mailer/message.py
Message.attach
def attach(self, name, data=None, maintype=None, subtype=None, inline=False, filename=None, filename_charset='', filename_language='', encoding=None): """Attach a file to this message. :param name: Path to the file to attach if data is None, or the name of the file if the ``data`` argument is given :pa...
python
def attach(self, name, data=None, maintype=None, subtype=None, inline=False, filename=None, filename_charset='', filename_language='', encoding=None): """Attach a file to this message. :param name: Path to the file to attach if data is None, or the name of the file if the ``data`` argument is given :pa...
[ "def", "attach", "(", "self", ",", "name", ",", "data", "=", "None", ",", "maintype", "=", "None", ",", "subtype", "=", "None", ",", "inline", "=", "False", ",", "filename", "=", "None", ",", "filename_charset", "=", "''", ",", "filename_language", "="...
Attach a file to this message. :param name: Path to the file to attach if data is None, or the name of the file if the ``data`` argument is given :param data: Contents of the file to attach, or None if the data is to be read from the file pointed to by the ``name`` argument :type data: bytes or a fil...
[ "Attach", "a", "file", "to", "this", "message", "." ]
3995ef98a3f7feb75f1aeb652e6afe40a5c94def
https://github.com/marrow/mailer/blob/3995ef98a3f7feb75f1aeb652e6afe40a5c94def/marrow/mailer/message.py#L254-L337
train
marrow/mailer
marrow/mailer/message.py
Message.embed
def embed(self, name, data=None): """Attach an image file and prepare for HTML embedding. This method should only be used to embed images. :param name: Path to the image to embed if data is None, or the name of the file if the ``data`` argument is given :param data: Contents of the image to embed, or No...
python
def embed(self, name, data=None): """Attach an image file and prepare for HTML embedding. This method should only be used to embed images. :param name: Path to the image to embed if data is None, or the name of the file if the ``data`` argument is given :param data: Contents of the image to embed, or No...
[ "def", "embed", "(", "self", ",", "name", ",", "data", "=", "None", ")", ":", "if", "data", "is", "None", ":", "with", "open", "(", "name", ",", "'rb'", ")", "as", "fp", ":", "data", "=", "fp", ".", "read", "(", ")", "name", "=", "os", ".", ...
Attach an image file and prepare for HTML embedding. This method should only be used to embed images. :param name: Path to the image to embed if data is None, or the name of the file if the ``data`` argument is given :param data: Contents of the image to embed, or None if the data is to be read from...
[ "Attach", "an", "image", "file", "and", "prepare", "for", "HTML", "embedding", "." ]
3995ef98a3f7feb75f1aeb652e6afe40a5c94def
https://github.com/marrow/mailer/blob/3995ef98a3f7feb75f1aeb652e6afe40a5c94def/marrow/mailer/message.py#L339-L361
train
marrow/mailer
marrow/mailer/transport/mock.py
MockTransport.deliver
def deliver(self, message): """Concrete message delivery.""" config = self.config success = config.success failure = config.failure exhaustion = config.exhaustion if getattr(message, 'die', False): 1/0 if failure: ...
python
def deliver(self, message): """Concrete message delivery.""" config = self.config success = config.success failure = config.failure exhaustion = config.exhaustion if getattr(message, 'die', False): 1/0 if failure: ...
[ "def", "deliver", "(", "self", ",", "message", ")", ":", "config", "=", "self", ".", "config", "success", "=", "config", ".", "success", "failure", "=", "config", ".", "failure", "exhaustion", "=", "config", ".", "exhaustion", "if", "getattr", "(", "mess...
Concrete message delivery.
[ "Concrete", "message", "delivery", "." ]
3995ef98a3f7feb75f1aeb652e6afe40a5c94def
https://github.com/marrow/mailer/blob/3995ef98a3f7feb75f1aeb652e6afe40a5c94def/marrow/mailer/transport/mock.py#L40-L68
train
marrow/mailer
marrow/mailer/manager/immediate.py
ImmediateManager.startup
def startup(self): """Perform startup actions. This just chains down to the transport layer. """ log.info("Immediate delivery manager starting.") log.debug("Initializing transport queue.") self.transport.startup() log.info("Imme...
python
def startup(self): """Perform startup actions. This just chains down to the transport layer. """ log.info("Immediate delivery manager starting.") log.debug("Initializing transport queue.") self.transport.startup() log.info("Imme...
[ "def", "startup", "(", "self", ")", ":", "log", ".", "info", "(", "\"Immediate delivery manager starting.\"", ")", "log", ".", "debug", "(", "\"Initializing transport queue.\"", ")", "self", ".", "transport", ".", "startup", "(", ")", "log", ".", "info", "(", ...
Perform startup actions. This just chains down to the transport layer.
[ "Perform", "startup", "actions", ".", "This", "just", "chains", "down", "to", "the", "transport", "layer", "." ]
3995ef98a3f7feb75f1aeb652e6afe40a5c94def
https://github.com/marrow/mailer/blob/3995ef98a3f7feb75f1aeb652e6afe40a5c94def/marrow/mailer/manager/immediate.py#L24-L35
train
marrow/mailer
marrow/mailer/address.py
AddressList.string_addresses
def string_addresses(self, encoding=None): """Return a list of string representations of the addresses suitable for usage in an SMTP transaction.""" if not encoding: encoding = self.encoding # We need the punycode goodness. return [Address(i.address).encode(encoding).decode(encoding) for i in self]
python
def string_addresses(self, encoding=None): """Return a list of string representations of the addresses suitable for usage in an SMTP transaction.""" if not encoding: encoding = self.encoding # We need the punycode goodness. return [Address(i.address).encode(encoding).decode(encoding) for i in self]
[ "def", "string_addresses", "(", "self", ",", "encoding", "=", "None", ")", ":", "if", "not", "encoding", ":", "encoding", "=", "self", ".", "encoding", "return", "[", "Address", "(", "i", ".", "address", ")", ".", "encode", "(", "encoding", ")", ".", ...
Return a list of string representations of the addresses suitable for usage in an SMTP transaction.
[ "Return", "a", "list", "of", "string", "representations", "of", "the", "addresses", "suitable", "for", "usage", "in", "an", "SMTP", "transaction", "." ]
3995ef98a3f7feb75f1aeb652e6afe40a5c94def
https://github.com/marrow/mailer/blob/3995ef98a3f7feb75f1aeb652e6afe40a5c94def/marrow/mailer/address.py#L193-L201
train
learningequality/ricecooker
ricecooker/sushi_bar_client.py
ReconnectingWebSocket.run
def run(self): """ If the connection drops, then run_forever will terminate and a reconnection attempt will be made. """ while True: self.connect_lock.acquire() if self.stopped(): return self.__connect() self.connect...
python
def run(self): """ If the connection drops, then run_forever will terminate and a reconnection attempt will be made. """ while True: self.connect_lock.acquire() if self.stopped(): return self.__connect() self.connect...
[ "def", "run", "(", "self", ")", ":", "while", "True", ":", "self", ".", "connect_lock", ".", "acquire", "(", ")", "if", "self", ".", "stopped", "(", ")", ":", "return", "self", ".", "__connect", "(", ")", "self", ".", "connect_lock", ".", "release", ...
If the connection drops, then run_forever will terminate and a reconnection attempt will be made.
[ "If", "the", "connection", "drops", "then", "run_forever", "will", "terminate", "and", "a", "reconnection", "attempt", "will", "be", "made", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/sushi_bar_client.py#L38-L49
train
learningequality/ricecooker
ricecooker/sushi_bar_client.py
ReconnectingWebSocket.send
def send(self, data): """ This method keeps trying to send a message relying on the run method to reopen the websocket in case it was closed. """ while not self.stopped(): try: self.ws.send(data) return except websocket.WebS...
python
def send(self, data): """ This method keeps trying to send a message relying on the run method to reopen the websocket in case it was closed. """ while not self.stopped(): try: self.ws.send(data) return except websocket.WebS...
[ "def", "send", "(", "self", ",", "data", ")", ":", "while", "not", "self", ".", "stopped", "(", ")", ":", "try", ":", "self", ".", "ws", ".", "send", "(", "data", ")", "return", "except", "websocket", ".", "WebSocketConnectionClosedException", ":", "ti...
This method keeps trying to send a message relying on the run method to reopen the websocket in case it was closed.
[ "This", "method", "keeps", "trying", "to", "send", "a", "message", "relying", "on", "the", "run", "method", "to", "reopen", "the", "websocket", "in", "case", "it", "was", "closed", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/sushi_bar_client.py#L54-L65
train
learningequality/ricecooker
ricecooker/sushi_bar_client.py
SushiBarClient.__create_channel_run
def __create_channel_run(self, channel, username, token): """Sends a post request to create the channel run.""" data = { 'channel_id': channel.get_node_id().hex, 'chef_name': self.__get_chef_name(), 'ricecooker_version': __version__, 'started_by_user': use...
python
def __create_channel_run(self, channel, username, token): """Sends a post request to create the channel run.""" data = { 'channel_id': channel.get_node_id().hex, 'chef_name': self.__get_chef_name(), 'ricecooker_version': __version__, 'started_by_user': use...
[ "def", "__create_channel_run", "(", "self", ",", "channel", ",", "username", ",", "token", ")", ":", "data", "=", "{", "'channel_id'", ":", "channel", ".", "get_node_id", "(", ")", ".", "hex", ",", "'chef_name'", ":", "self", ".", "__get_chef_name", "(", ...
Sends a post request to create the channel run.
[ "Sends", "a", "post", "request", "to", "create", "the", "channel", "run", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/sushi_bar_client.py#L140-L159
train
learningequality/ricecooker
ricecooker/sushi_bar_client.py
LocalControlSocket.run
def run(self): """ This override threading.Thread to open socket and wait for messages. """ while True: self.open_lock.acquire() if self.stopped(): return self.__open() self.open_lock.release()
python
def run(self): """ This override threading.Thread to open socket and wait for messages. """ while True: self.open_lock.acquire() if self.stopped(): return self.__open() self.open_lock.release()
[ "def", "run", "(", "self", ")", ":", "while", "True", ":", "self", ".", "open_lock", ".", "acquire", "(", ")", "if", "self", ".", "stopped", "(", ")", ":", "return", "self", ".", "__open", "(", ")", "self", ".", "open_lock", ".", "release", "(", ...
This override threading.Thread to open socket and wait for messages.
[ "This", "override", "threading", ".", "Thread", "to", "open", "socket", "and", "wait", "for", "messages", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/sushi_bar_client.py#L387-L396
train
learningequality/ricecooker
ricecooker/utils/linecook.py
filter_filenames
def filter_filenames(filenames): """ Skip files with extentions in `FILE_EXCLUDE_EXTENTIONS` and filenames that contain `FILE_SKIP_PATTENRS`. """ filenames_cleaned = [] for filename in filenames: keep = True for pattern in FILE_EXCLUDE_EXTENTIONS: if filename.endswith...
python
def filter_filenames(filenames): """ Skip files with extentions in `FILE_EXCLUDE_EXTENTIONS` and filenames that contain `FILE_SKIP_PATTENRS`. """ filenames_cleaned = [] for filename in filenames: keep = True for pattern in FILE_EXCLUDE_EXTENTIONS: if filename.endswith...
[ "def", "filter_filenames", "(", "filenames", ")", ":", "filenames_cleaned", "=", "[", "]", "for", "filename", "in", "filenames", ":", "keep", "=", "True", "for", "pattern", "in", "FILE_EXCLUDE_EXTENTIONS", ":", "if", "filename", ".", "endswith", "(", "pattern"...
Skip files with extentions in `FILE_EXCLUDE_EXTENTIONS` and filenames that contain `FILE_SKIP_PATTENRS`.
[ "Skip", "files", "with", "extentions", "in", "FILE_EXCLUDE_EXTENTIONS", "and", "filenames", "that", "contain", "FILE_SKIP_PATTENRS", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/linecook.py#L83-L99
train
learningequality/ricecooker
ricecooker/utils/linecook.py
filter_thumbnail_files
def filter_thumbnail_files(chan_path, filenames, metadata_provider): """ We don't want to create `ContentNode` from thumbnail files. """ thumbnail_files_to_skip = metadata_provider.get_thumbnail_paths() filenames_cleaned = [] for filename in filenames: keep = True chan_filepath =...
python
def filter_thumbnail_files(chan_path, filenames, metadata_provider): """ We don't want to create `ContentNode` from thumbnail files. """ thumbnail_files_to_skip = metadata_provider.get_thumbnail_paths() filenames_cleaned = [] for filename in filenames: keep = True chan_filepath =...
[ "def", "filter_thumbnail_files", "(", "chan_path", ",", "filenames", ",", "metadata_provider", ")", ":", "thumbnail_files_to_skip", "=", "metadata_provider", ".", "get_thumbnail_paths", "(", ")", "filenames_cleaned", "=", "[", "]", "for", "filename", "in", "filenames"...
We don't want to create `ContentNode` from thumbnail files.
[ "We", "don", "t", "want", "to", "create", "ContentNode", "from", "thumbnail", "files", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/linecook.py#L101-L115
train
learningequality/ricecooker
ricecooker/utils/linecook.py
keep_folder
def keep_folder(raw_path): """ Keep only folders that don't contain patterns in `DIR_EXCLUDE_PATTERNS`. """ keep = True for pattern in DIR_EXCLUDE_PATTERNS: if pattern in raw_path: LOGGER.debug('rejecting', raw_path) keep = False return keep
python
def keep_folder(raw_path): """ Keep only folders that don't contain patterns in `DIR_EXCLUDE_PATTERNS`. """ keep = True for pattern in DIR_EXCLUDE_PATTERNS: if pattern in raw_path: LOGGER.debug('rejecting', raw_path) keep = False return keep
[ "def", "keep_folder", "(", "raw_path", ")", ":", "keep", "=", "True", "for", "pattern", "in", "DIR_EXCLUDE_PATTERNS", ":", "if", "pattern", "in", "raw_path", ":", "LOGGER", ".", "debug", "(", "'rejecting'", ",", "raw_path", ")", "keep", "=", "False", "retu...
Keep only folders that don't contain patterns in `DIR_EXCLUDE_PATTERNS`.
[ "Keep", "only", "folders", "that", "don", "t", "contain", "patterns", "in", "DIR_EXCLUDE_PATTERNS", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/linecook.py#L117-L126
train
learningequality/ricecooker
ricecooker/utils/linecook.py
process_folder
def process_folder(channel, rel_path, filenames, metadata_provider): """ Create `ContentNode`s from each file in this folder and the node to `channel` under the path `rel_path`. """ LOGGER.debug('IN process_folder ' + str(rel_path) + ' ' + str(filenames)) if not keep_folder(rel_path): ...
python
def process_folder(channel, rel_path, filenames, metadata_provider): """ Create `ContentNode`s from each file in this folder and the node to `channel` under the path `rel_path`. """ LOGGER.debug('IN process_folder ' + str(rel_path) + ' ' + str(filenames)) if not keep_folder(rel_path): ...
[ "def", "process_folder", "(", "channel", ",", "rel_path", ",", "filenames", ",", "metadata_provider", ")", ":", "LOGGER", ".", "debug", "(", "'IN process_folder '", "+", "str", "(", "rel_path", ")", "+", "' '", "+", "str", "(", "filenames", ")", ")", "...
Create `ContentNode`s from each file in this folder and the node to `channel` under the path `rel_path`.
[ "Create", "ContentNode", "s", "from", "each", "file", "in", "this", "folder", "and", "the", "node", "to", "channel", "under", "the", "path", "rel_path", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/linecook.py#L128-L186
train
learningequality/ricecooker
ricecooker/utils/linecook.py
build_ricecooker_json_tree
def build_ricecooker_json_tree(args, options, metadata_provider, json_tree_path): """ Download all categories, subpages, modules, and resources from open.edu. """ LOGGER.info('Starting to build the ricecooker_json_tree') channeldir = args['channeldir'] if channeldir.endswith(os.path.sep): ...
python
def build_ricecooker_json_tree(args, options, metadata_provider, json_tree_path): """ Download all categories, subpages, modules, and resources from open.edu. """ LOGGER.info('Starting to build the ricecooker_json_tree') channeldir = args['channeldir'] if channeldir.endswith(os.path.sep): ...
[ "def", "build_ricecooker_json_tree", "(", "args", ",", "options", ",", "metadata_provider", ",", "json_tree_path", ")", ":", "LOGGER", ".", "info", "(", "'Starting to build the ricecooker_json_tree'", ")", "channeldir", "=", "args", "[", "'channeldir'", "]", "if", "...
Download all categories, subpages, modules, and resources from open.edu.
[ "Download", "all", "categories", "subpages", "modules", "and", "resources", "from", "open", ".", "edu", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/linecook.py#L189-L245
train
learningequality/ricecooker
examples/tutorial_chef.py
TutorialChef.construct_channel
def construct_channel(self, *args, **kwargs): """ This method is reponsible for creating a `ChannelNode` object from the info in `channel_info` and populating it with TopicNode and ContentNode children. """ # Create channel ################################################...
python
def construct_channel(self, *args, **kwargs): """ This method is reponsible for creating a `ChannelNode` object from the info in `channel_info` and populating it with TopicNode and ContentNode children. """ # Create channel ################################################...
[ "def", "construct_channel", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "channel", "=", "self", ".", "get_channel", "(", "*", "args", ",", "**", "kwargs", ")", "exampletopic", "=", "TopicNode", "(", "source_id", "=", "\"topic-1\"", ",",...
This method is reponsible for creating a `ChannelNode` object from the info in `channel_info` and populating it with TopicNode and ContentNode children.
[ "This", "method", "is", "reponsible", "for", "creating", "a", "ChannelNode", "object", "from", "the", "info", "in", "channel_info", "and", "populating", "it", "with", "TopicNode", "and", "ContentNode", "children", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/examples/tutorial_chef.py#L29-L88
train
learningequality/ricecooker
ricecooker/utils/jsontrees.py
read_tree_from_json
def read_tree_from_json(srcpath): """ Load ricecooker json tree data from json file at `srcpath`. """ with open(srcpath) as infile: json_tree = json.load(infile) if json_tree is None: raise ValueError('Could not find ricecooker json tree') return json_tree
python
def read_tree_from_json(srcpath): """ Load ricecooker json tree data from json file at `srcpath`. """ with open(srcpath) as infile: json_tree = json.load(infile) if json_tree is None: raise ValueError('Could not find ricecooker json tree') return json_tree
[ "def", "read_tree_from_json", "(", "srcpath", ")", ":", "with", "open", "(", "srcpath", ")", "as", "infile", ":", "json_tree", "=", "json", ".", "load", "(", "infile", ")", "if", "json_tree", "is", "None", ":", "raise", "ValueError", "(", "'Could not find ...
Load ricecooker json tree data from json file at `srcpath`.
[ "Load", "ricecooker", "json", "tree", "data", "from", "json", "file", "at", "srcpath", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/jsontrees.py#L48-L56
train
learningequality/ricecooker
ricecooker/utils/jsontrees.py
get_channel_node_from_json
def get_channel_node_from_json(json_tree): """ Build `ChannelNode` from json data provided in `json_tree`. """ channel = ChannelNode( title=json_tree['title'], description=json_tree['description'], source_domain=json_tree['source_domain'], source_id=json_tree['source_id']...
python
def get_channel_node_from_json(json_tree): """ Build `ChannelNode` from json data provided in `json_tree`. """ channel = ChannelNode( title=json_tree['title'], description=json_tree['description'], source_domain=json_tree['source_domain'], source_id=json_tree['source_id']...
[ "def", "get_channel_node_from_json", "(", "json_tree", ")", ":", "channel", "=", "ChannelNode", "(", "title", "=", "json_tree", "[", "'title'", "]", ",", "description", "=", "json_tree", "[", "'description'", "]", ",", "source_domain", "=", "json_tree", "[", "...
Build `ChannelNode` from json data provided in `json_tree`.
[ "Build", "ChannelNode", "from", "json", "data", "provided", "in", "json_tree", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/jsontrees.py#L72-L84
train
learningequality/ricecooker
ricecooker/chefs.py
BaseChef.get_channel
def get_channel(self, **kwargs): """ Call chef script's get_channel method in compatibility mode ...or... Create a `ChannelNode` from the Chef's `channel_info` class attribute. Args: kwargs (dict): additional keyword arguments that `uploadchannel` received Re...
python
def get_channel(self, **kwargs): """ Call chef script's get_channel method in compatibility mode ...or... Create a `ChannelNode` from the Chef's `channel_info` class attribute. Args: kwargs (dict): additional keyword arguments that `uploadchannel` received Re...
[ "def", "get_channel", "(", "self", ",", "**", "kwargs", ")", ":", "if", "self", ".", "compatibility_mode", ":", "if", "hasattr", "(", "self", ".", "chef_module", ",", "'get_channel'", ")", ":", "config", ".", "LOGGER", ".", "info", "(", "\"Calling get_chan...
Call chef script's get_channel method in compatibility mode ...or... Create a `ChannelNode` from the Chef's `channel_info` class attribute. Args: kwargs (dict): additional keyword arguments that `uploadchannel` received Returns: channel created from get_channel method or Non...
[ "Call", "chef", "script", "s", "get_channel", "method", "in", "compatibility", "mode", "...", "or", "...", "Create", "a", "ChannelNode", "from", "the", "Chef", "s", "channel_info", "class", "attribute", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/chefs.py#L156-L196
train
learningequality/ricecooker
ricecooker/chefs.py
JsonTreeChef.construct_channel
def construct_channel(self, **kwargs): """ Build the channel tree by adding TopicNodes and ContentNode children. """ channel = self.get_channel(**kwargs) json_tree_path = self.get_json_tree_path(**kwargs) json_tree = read_tree_from_json(json_tree_path) build_tree_...
python
def construct_channel(self, **kwargs): """ Build the channel tree by adding TopicNodes and ContentNode children. """ channel = self.get_channel(**kwargs) json_tree_path = self.get_json_tree_path(**kwargs) json_tree = read_tree_from_json(json_tree_path) build_tree_...
[ "def", "construct_channel", "(", "self", ",", "**", "kwargs", ")", ":", "channel", "=", "self", ".", "get_channel", "(", "**", "kwargs", ")", "json_tree_path", "=", "self", ".", "get_json_tree_path", "(", "**", "kwargs", ")", "json_tree", "=", "read_tree_fro...
Build the channel tree by adding TopicNodes and ContentNode children.
[ "Build", "the", "channel", "tree", "by", "adding", "TopicNodes", "and", "ContentNode", "children", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/chefs.py#L371-L380
train
learningequality/ricecooker
ricecooker/chefs.py
LineCook.pre_run
def pre_run(self, args, options): """ This function is called before `run` in order to build the json tree. """ if 'generate' in args and args['generate']: self.metadata_provider = CsvMetadataProvider(args['channeldir'], cha...
python
def pre_run(self, args, options): """ This function is called before `run` in order to build the json tree. """ if 'generate' in args and args['generate']: self.metadata_provider = CsvMetadataProvider(args['channeldir'], cha...
[ "def", "pre_run", "(", "self", ",", "args", ",", "options", ")", ":", "if", "'generate'", "in", "args", "and", "args", "[", "'generate'", "]", ":", "self", ".", "metadata_provider", "=", "CsvMetadataProvider", "(", "args", "[", "'channeldir'", "]", ",", ...
This function is called before `run` in order to build the json tree.
[ "This", "function", "is", "called", "before", "run", "in", "order", "to", "build", "the", "json", "tree", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/chefs.py#L443-L477
train
learningequality/ricecooker
ricecooker/utils/html.py
calculate_relative_url
def calculate_relative_url(url, filename=None, baseurl=None, subpath=None): """ Calculate the relative path for a URL relative to a base URL, possibly also injecting in a subpath prefix. """ # ensure the provided subpath is a list if isinstance(subpath, str): subpath = subpath.strip("/").sp...
python
def calculate_relative_url(url, filename=None, baseurl=None, subpath=None): """ Calculate the relative path for a URL relative to a base URL, possibly also injecting in a subpath prefix. """ # ensure the provided subpath is a list if isinstance(subpath, str): subpath = subpath.strip("/").sp...
[ "def", "calculate_relative_url", "(", "url", ",", "filename", "=", "None", ",", "baseurl", "=", "None", ",", "subpath", "=", "None", ")", ":", "if", "isinstance", "(", "subpath", ",", "str", ")", ":", "subpath", "=", "subpath", ".", "strip", "(", "\"/\...
Calculate the relative path for a URL relative to a base URL, possibly also injecting in a subpath prefix.
[ "Calculate", "the", "relative", "path", "for", "a", "URL", "relative", "to", "a", "base", "URL", "possibly", "also", "injecting", "in", "a", "subpath", "prefix", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/html.py#L54-L78
train
learningequality/ricecooker
ricecooker/utils/html.py
download_file
def download_file(url, destpath, filename=None, baseurl=None, subpath=None, middleware_callbacks=None, middleware_kwargs=None, request_fn=sess.get): """ Download a file from a URL, into a destination folder, with optional use of relative paths and middleware processors. - If `filename` is set, that will be...
python
def download_file(url, destpath, filename=None, baseurl=None, subpath=None, middleware_callbacks=None, middleware_kwargs=None, request_fn=sess.get): """ Download a file from a URL, into a destination folder, with optional use of relative paths and middleware processors. - If `filename` is set, that will be...
[ "def", "download_file", "(", "url", ",", "destpath", ",", "filename", "=", "None", ",", "baseurl", "=", "None", ",", "subpath", "=", "None", ",", "middleware_callbacks", "=", "None", ",", "middleware_kwargs", "=", "None", ",", "request_fn", "=", "sess", "....
Download a file from a URL, into a destination folder, with optional use of relative paths and middleware processors. - If `filename` is set, that will be used as the name of the file when it's written to the destpath. - If `baseurl` is specified, the file will be put into subdirectory of destpath per the url'...
[ "Download", "a", "file", "from", "a", "URL", "into", "a", "destination", "folder", "with", "optional", "use", "of", "relative", "paths", "and", "middleware", "processors", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/html.py#L81-L129
train
learningequality/ricecooker
ricecooker/classes/files.py
File.set_language
def set_language(self, language): """ Set self.language to internal lang. repr. code from str or Language object. """ if isinstance(language, str): language_obj = languages.getlang(language) if language_obj: self.language = language_obj.code else: ...
python
def set_language(self, language): """ Set self.language to internal lang. repr. code from str or Language object. """ if isinstance(language, str): language_obj = languages.getlang(language) if language_obj: self.language = language_obj.code else: ...
[ "def", "set_language", "(", "self", ",", "language", ")", ":", "if", "isinstance", "(", "language", ",", "str", ")", ":", "language_obj", "=", "languages", ".", "getlang", "(", "language", ")", "if", "language_obj", ":", "self", ".", "language", "=", "la...
Set self.language to internal lang. repr. code from str or Language object.
[ "Set", "self", ".", "language", "to", "internal", "lang", ".", "repr", ".", "code", "from", "str", "or", "Language", "object", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/classes/files.py#L258-L267
train
learningequality/ricecooker
ricecooker/classes/nodes.py
Node.get_thumbnail_preset
def get_thumbnail_preset(self): """ Returns the format preset corresponding to this Node's type, or None if the node doesn't have a format preset. """ if isinstance(self, ChannelNode): return format_presets.CHANNEL_THUMBNAIL elif isinstance(self, TopicNode): ...
python
def get_thumbnail_preset(self): """ Returns the format preset corresponding to this Node's type, or None if the node doesn't have a format preset. """ if isinstance(self, ChannelNode): return format_presets.CHANNEL_THUMBNAIL elif isinstance(self, TopicNode): ...
[ "def", "get_thumbnail_preset", "(", "self", ")", ":", "if", "isinstance", "(", "self", ",", "ChannelNode", ")", ":", "return", "format_presets", ".", "CHANNEL_THUMBNAIL", "elif", "isinstance", "(", "self", ",", "TopicNode", ")", ":", "return", "format_presets", ...
Returns the format preset corresponding to this Node's type, or None if the node doesn't have a format preset.
[ "Returns", "the", "format", "preset", "corresponding", "to", "this", "Node", "s", "type", "or", "None", "if", "the", "node", "doesn", "t", "have", "a", "format", "preset", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/classes/nodes.py#L113-L132
train
learningequality/ricecooker
ricecooker/utils/pdf.py
PDFParser.open
def open(self, update=False): """ Opens pdf file to read from. """ filename = os.path.basename(self.source_path) folder, _ext = os.path.splitext(filename) self.path = os.path.sep.join([self.directory, folder, filename]) if not os.path.exists(os.path.dirname(self.p...
python
def open(self, update=False): """ Opens pdf file to read from. """ filename = os.path.basename(self.source_path) folder, _ext = os.path.splitext(filename) self.path = os.path.sep.join([self.directory, folder, filename]) if not os.path.exists(os.path.dirname(self.p...
[ "def", "open", "(", "self", ",", "update", "=", "False", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "self", ".", "source_path", ")", "folder", ",", "_ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "sel...
Opens pdf file to read from.
[ "Opens", "pdf", "file", "to", "read", "from", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/pdf.py#L46-L62
train
learningequality/ricecooker
ricecooker/utils/pdf.py
PDFParser.get_toc
def get_toc(self, subchapters=False): """ Returns table-of-contents information extracted from the PDF doc. When `subchapters=False`, the output is a list of this form .. code-block:: python [ {'title': 'First chapter', 'page_start': 0, 'page_end': 10}, ...
python
def get_toc(self, subchapters=False): """ Returns table-of-contents information extracted from the PDF doc. When `subchapters=False`, the output is a list of this form .. code-block:: python [ {'title': 'First chapter', 'page_start': 0, 'page_end': 10}, ...
[ "def", "get_toc", "(", "self", ",", "subchapters", "=", "False", ")", ":", "self", ".", "check_path", "(", ")", "chapters", "=", "[", "]", "index", "=", "0", "for", "dest", "in", "self", ".", "pdf", ".", "getOutlines", "(", ")", ":", "if", "isinsta...
Returns table-of-contents information extracted from the PDF doc. When `subchapters=False`, the output is a list of this form .. code-block:: python [ {'title': 'First chapter', 'page_start': 0, 'page_end': 10}, {'title': 'Second chapter', 'page_start': 10...
[ "Returns", "table", "-", "of", "-", "contents", "information", "extracted", "from", "the", "PDF", "doc", ".", "When", "subchapters", "=", "False", "the", "output", "is", "a", "list", "of", "this", "form" ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/pdf.py#L75-L136
train
learningequality/ricecooker
ricecooker/utils/metadata_provider.py
get_metadata_file_path
def get_metadata_file_path(channeldir, filename): """ Return the path to the metadata file named `filename` that is a sibling of `channeldir`. """ channelparentdir, channeldirname = os.path.split(channeldir) return os.path.join(channelparentdir, filename)
python
def get_metadata_file_path(channeldir, filename): """ Return the path to the metadata file named `filename` that is a sibling of `channeldir`. """ channelparentdir, channeldirname = os.path.split(channeldir) return os.path.join(channelparentdir, filename)
[ "def", "get_metadata_file_path", "(", "channeldir", ",", "filename", ")", ":", "channelparentdir", ",", "channeldirname", "=", "os", ".", "path", ".", "split", "(", "channeldir", ")", "return", "os", ".", "path", ".", "join", "(", "channelparentdir", ",", "f...
Return the path to the metadata file named `filename` that is a sibling of `channeldir`.
[ "Return", "the", "path", "to", "the", "metadata", "file", "named", "filename", "that", "is", "a", "sibling", "of", "channeldir", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L144-L149
train
learningequality/ricecooker
ricecooker/utils/metadata_provider.py
_read_csv_lines
def _read_csv_lines(path): """ Opens CSV file `path` and returns list of rows. Pass output of this function to `csv.DictReader` for reading data. """ csv_file = open(path, 'r') csv_lines_raw = csv_file.readlines() csv_lines_clean = [line for line in csv_lines_raw if len(line.strip()) > 0] ...
python
def _read_csv_lines(path): """ Opens CSV file `path` and returns list of rows. Pass output of this function to `csv.DictReader` for reading data. """ csv_file = open(path, 'r') csv_lines_raw = csv_file.readlines() csv_lines_clean = [line for line in csv_lines_raw if len(line.strip()) > 0] ...
[ "def", "_read_csv_lines", "(", "path", ")", ":", "csv_file", "=", "open", "(", "path", ",", "'r'", ")", "csv_lines_raw", "=", "csv_file", ".", "readlines", "(", ")", "csv_lines_clean", "=", "[", "line", "for", "line", "in", "csv_lines_raw", "if", "len", ...
Opens CSV file `path` and returns list of rows. Pass output of this function to `csv.DictReader` for reading data.
[ "Opens", "CSV", "file", "path", "and", "returns", "list", "of", "rows", ".", "Pass", "output", "of", "this", "function", "to", "csv", ".", "DictReader", "for", "reading", "data", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L875-L883
train
learningequality/ricecooker
ricecooker/utils/metadata_provider.py
_clean_dict
def _clean_dict(row): """ Transform empty strings values of dict `row` to None. """ row_cleaned = {} for key, val in row.items(): if val is None or val == '': row_cleaned[key] = None else: row_cleaned[key] = val return row_cleaned
python
def _clean_dict(row): """ Transform empty strings values of dict `row` to None. """ row_cleaned = {} for key, val in row.items(): if val is None or val == '': row_cleaned[key] = None else: row_cleaned[key] = val return row_cleaned
[ "def", "_clean_dict", "(", "row", ")", ":", "row_cleaned", "=", "{", "}", "for", "key", ",", "val", "in", "row", ".", "items", "(", ")", ":", "if", "val", "is", "None", "or", "val", "==", "''", ":", "row_cleaned", "[", "key", "]", "=", "None", ...
Transform empty strings values of dict `row` to None.
[ "Transform", "empty", "strings", "values", "of", "dict", "row", "to", "None", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L886-L896
train
learningequality/ricecooker
ricecooker/utils/metadata_provider.py
CsvMetadataProvider.get
def get(self, path_tuple): """ Returns metadata dict for path in `path_tuple`. """ if path_tuple in self.contentcache: metadata = self.contentcache[path_tuple] else: # TODO: make chef robust to missing metadata # LOGGER.error( LOGGE...
python
def get(self, path_tuple): """ Returns metadata dict for path in `path_tuple`. """ if path_tuple in self.contentcache: metadata = self.contentcache[path_tuple] else: # TODO: make chef robust to missing metadata # LOGGER.error( LOGGE...
[ "def", "get", "(", "self", ",", "path_tuple", ")", ":", "if", "path_tuple", "in", "self", ".", "contentcache", ":", "metadata", "=", "self", ".", "contentcache", "[", "path_tuple", "]", "else", ":", "LOGGER", ".", "warning", "(", "'No metadata found for path...
Returns metadata dict for path in `path_tuple`.
[ "Returns", "metadata", "dict", "for", "path", "in", "path_tuple", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L239-L253
train
learningequality/ricecooker
ricecooker/utils/metadata_provider.py
CsvMetadataProvider.get_channel_info
def get_channel_info(self): """ Returns the first data row from Channel.csv """ csv_filename = get_metadata_file_path(channeldir=self.channeldir, filename=self.channelinfo) csv_lines = _read_csv_lines(csv_filename) dict_reader = csv.DictReader(csv_lines) channel_c...
python
def get_channel_info(self): """ Returns the first data row from Channel.csv """ csv_filename = get_metadata_file_path(channeldir=self.channeldir, filename=self.channelinfo) csv_lines = _read_csv_lines(csv_filename) dict_reader = csv.DictReader(csv_lines) channel_c...
[ "def", "get_channel_info", "(", "self", ")", ":", "csv_filename", "=", "get_metadata_file_path", "(", "channeldir", "=", "self", ".", "channeldir", ",", "filename", "=", "self", ".", "channelinfo", ")", "csv_lines", "=", "_read_csv_lines", "(", "csv_filename", "...
Returns the first data row from Channel.csv
[ "Returns", "the", "first", "data", "row", "from", "Channel", ".", "csv" ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L255-L268
train
learningequality/ricecooker
ricecooker/utils/metadata_provider.py
CsvMetadataProvider.get_thumbnail_paths
def get_thumbnail_paths(self): """ Helper function used to avoid processing thumbnail files during `os.walk`. """ thumbnail_path_tuples = [] # channel thumbnail channel_info = self.get_channel_info() chthumbnail_path = channel_info.get('thumbnail_chan_path', None)...
python
def get_thumbnail_paths(self): """ Helper function used to avoid processing thumbnail files during `os.walk`. """ thumbnail_path_tuples = [] # channel thumbnail channel_info = self.get_channel_info() chthumbnail_path = channel_info.get('thumbnail_chan_path', None)...
[ "def", "get_thumbnail_paths", "(", "self", ")", ":", "thumbnail_path_tuples", "=", "[", "]", "channel_info", "=", "self", ".", "get_channel_info", "(", ")", "chthumbnail_path", "=", "channel_info", ".", "get", "(", "'thumbnail_chan_path'", ",", "None", ")", "if"...
Helper function used to avoid processing thumbnail files during `os.walk`.
[ "Helper", "function", "used", "to", "avoid", "processing", "thumbnail", "files", "during", "os", ".", "walk", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L270-L287
train
learningequality/ricecooker
ricecooker/utils/metadata_provider.py
CsvMetadataProvider._map_exercise_row_to_dict
def _map_exercise_row_to_dict(self, row): """ Convert dictionary keys from raw CSV Exercise format to ricecooker keys. """ row_cleaned = _clean_dict(row) license_id = row_cleaned[CONTENT_LICENSE_ID_KEY] if license_id: license_dict = dict( licen...
python
def _map_exercise_row_to_dict(self, row): """ Convert dictionary keys from raw CSV Exercise format to ricecooker keys. """ row_cleaned = _clean_dict(row) license_id = row_cleaned[CONTENT_LICENSE_ID_KEY] if license_id: license_dict = dict( licen...
[ "def", "_map_exercise_row_to_dict", "(", "self", ",", "row", ")", ":", "row_cleaned", "=", "_clean_dict", "(", "row", ")", "license_id", "=", "row_cleaned", "[", "CONTENT_LICENSE_ID_KEY", "]", "if", "license_id", ":", "license_dict", "=", "dict", "(", "license_i...
Convert dictionary keys from raw CSV Exercise format to ricecooker keys.
[ "Convert", "dictionary", "keys", "from", "raw", "CSV", "Exercise", "format", "to", "ricecooker", "keys", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L359-L404
train
learningequality/ricecooker
ricecooker/utils/metadata_provider.py
CsvMetadataProvider._map_exercise_question_row_to_dict
def _map_exercise_question_row_to_dict(self, row): """ Convert dictionary keys from raw CSV Exercise Question format to ricecooker keys. """ row_cleaned = _clean_dict(row) # Parse answers all_answers = [] ansA = row_cleaned[EXERCISE_QUESTIONS_OPTION_A_KEY] ...
python
def _map_exercise_question_row_to_dict(self, row): """ Convert dictionary keys from raw CSV Exercise Question format to ricecooker keys. """ row_cleaned = _clean_dict(row) # Parse answers all_answers = [] ansA = row_cleaned[EXERCISE_QUESTIONS_OPTION_A_KEY] ...
[ "def", "_map_exercise_question_row_to_dict", "(", "self", ",", "row", ")", ":", "row_cleaned", "=", "_clean_dict", "(", "row", ")", "all_answers", "=", "[", "]", "ansA", "=", "row_cleaned", "[", "EXERCISE_QUESTIONS_OPTION_A_KEY", "]", "all_answers", ".", "append",...
Convert dictionary keys from raw CSV Exercise Question format to ricecooker keys.
[ "Convert", "dictionary", "keys", "from", "raw", "CSV", "Exercise", "Question", "format", "to", "ricecooker", "keys", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L406-L500
train
learningequality/ricecooker
ricecooker/utils/metadata_provider.py
CsvMetadataProvider.validate_headers
def validate_headers(self): """ Check if CSV metadata files have the right format. """ super().validate() self.validate_header(self.channeldir, self.channelinfo, CHANNEL_INFO_HEADER) self.validate_header(self.channeldir, self.contentinfo, CONTENT_INFO_HEADER) if s...
python
def validate_headers(self): """ Check if CSV metadata files have the right format. """ super().validate() self.validate_header(self.channeldir, self.channelinfo, CHANNEL_INFO_HEADER) self.validate_header(self.channeldir, self.contentinfo, CONTENT_INFO_HEADER) if s...
[ "def", "validate_headers", "(", "self", ")", ":", "super", "(", ")", ".", "validate", "(", ")", "self", ".", "validate_header", "(", "self", ".", "channeldir", ",", "self", ".", "channelinfo", ",", "CHANNEL_INFO_HEADER", ")", "self", ".", "validate_header", ...
Check if CSV metadata files have the right format.
[ "Check", "if", "CSV", "metadata", "files", "have", "the", "right", "format", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L509-L518
train
learningequality/ricecooker
ricecooker/utils/metadata_provider.py
CsvMetadataProvider.validate_header
def validate_header(self, channeldir, filename, expected_header): """ Check if CSV metadata file `filename` have the expected header format. """ expected = set(expected_header) csv_filename = get_metadata_file_path(channeldir, filename) csv_lines = _read_csv_lines(csv_fil...
python
def validate_header(self, channeldir, filename, expected_header): """ Check if CSV metadata file `filename` have the expected header format. """ expected = set(expected_header) csv_filename = get_metadata_file_path(channeldir, filename) csv_lines = _read_csv_lines(csv_fil...
[ "def", "validate_header", "(", "self", ",", "channeldir", ",", "filename", ",", "expected_header", ")", ":", "expected", "=", "set", "(", "expected_header", ")", "csv_filename", "=", "get_metadata_file_path", "(", "channeldir", ",", "filename", ")", "csv_lines", ...
Check if CSV metadata file `filename` have the expected header format.
[ "Check", "if", "CSV", "metadata", "file", "filename", "have", "the", "expected", "header", "format", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L520-L531
train
learningequality/ricecooker
ricecooker/utils/metadata_provider.py
CsvMetadataProvider.generate_contentinfo_from_channeldir
def generate_contentinfo_from_channeldir(self, args, options): """ Create rows in Content.csv for each folder and file in `self.channeldir`. """ LOGGER.info('Generating Content.csv rows folders and file in channeldir') file_path = get_metadata_file_path(self.channeldir, self.cont...
python
def generate_contentinfo_from_channeldir(self, args, options): """ Create rows in Content.csv for each folder and file in `self.channeldir`. """ LOGGER.info('Generating Content.csv rows folders and file in channeldir') file_path = get_metadata_file_path(self.channeldir, self.cont...
[ "def", "generate_contentinfo_from_channeldir", "(", "self", ",", "args", ",", "options", ")", ":", "LOGGER", ".", "info", "(", "'Generating Content.csv rows folders and file in channeldir'", ")", "file_path", "=", "get_metadata_file_path", "(", "self", ".", "channeldir", ...
Create rows in Content.csv for each folder and file in `self.channeldir`.
[ "Create", "rows", "in", "Content", ".", "csv", "for", "each", "folder", "and", "file", "in", "self", ".", "channeldir", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L777-L797
train
learningequality/ricecooker
ricecooker/utils/metadata_provider.py
CsvMetadataProvider.generate_contentinfo_from_folder
def generate_contentinfo_from_folder(self, csvwriter, rel_path, filenames): """ Create a topic node row in Content.csv for the folder at `rel_path` and add content node rows for all the files in the `rel_path` folder. """ LOGGER.debug('IN process_folder ' + str(rel_path) + ' ...
python
def generate_contentinfo_from_folder(self, csvwriter, rel_path, filenames): """ Create a topic node row in Content.csv for the folder at `rel_path` and add content node rows for all the files in the `rel_path` folder. """ LOGGER.debug('IN process_folder ' + str(rel_path) + ' ...
[ "def", "generate_contentinfo_from_folder", "(", "self", ",", "csvwriter", ",", "rel_path", ",", "filenames", ")", ":", "LOGGER", ".", "debug", "(", "'IN process_folder '", "+", "str", "(", "rel_path", ")", "+", "' '", "+", "str", "(", "filenames", ")", "...
Create a topic node row in Content.csv for the folder at `rel_path` and add content node rows for all the files in the `rel_path` folder.
[ "Create", "a", "topic", "node", "row", "in", "Content", ".", "csv", "for", "the", "folder", "at", "rel_path", "and", "add", "content", "node", "rows", "for", "all", "the", "files", "in", "the", "rel_path", "folder", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L799-L819
train
learningequality/ricecooker
ricecooker/utils/metadata_provider.py
CsvMetadataProvider.channeldir_node_to_row
def channeldir_node_to_row(self, path_tuple): """ Return a dict with keys corresponding to Content.csv columns. """ row = dict() for key in CONTENT_INFO_HEADER: row[key] = None row[CONTENT_PATH_KEY] = "/".join(path_tuple) # use / in .csv on Windows and UNIX ...
python
def channeldir_node_to_row(self, path_tuple): """ Return a dict with keys corresponding to Content.csv columns. """ row = dict() for key in CONTENT_INFO_HEADER: row[key] = None row[CONTENT_PATH_KEY] = "/".join(path_tuple) # use / in .csv on Windows and UNIX ...
[ "def", "channeldir_node_to_row", "(", "self", ",", "path_tuple", ")", ":", "row", "=", "dict", "(", ")", "for", "key", "in", "CONTENT_INFO_HEADER", ":", "row", "[", "key", "]", "=", "None", "row", "[", "CONTENT_PATH_KEY", "]", "=", "\"/\"", ".", "join", ...
Return a dict with keys corresponding to Content.csv columns.
[ "Return", "a", "dict", "with", "keys", "corresponding", "to", "Content", ".", "csv", "columns", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L822-L836
train
learningequality/ricecooker
ricecooker/utils/metadata_provider.py
CsvMetadataProvider.generate_templates
def generate_templates(self, exercise_questions=False): """ Create empty .csv files with the right headers and place them in the Will place files as siblings of directory `channeldir`. """ self.generate_template(channeldir=self.channeldir, filename=...
python
def generate_templates(self, exercise_questions=False): """ Create empty .csv files with the right headers and place them in the Will place files as siblings of directory `channeldir`. """ self.generate_template(channeldir=self.channeldir, filename=...
[ "def", "generate_templates", "(", "self", ",", "exercise_questions", "=", "False", ")", ":", "self", ".", "generate_template", "(", "channeldir", "=", "self", ".", "channeldir", ",", "filename", "=", "self", ".", "channelinfo", ",", "header", "=", "CHANNEL_INF...
Create empty .csv files with the right headers and place them in the Will place files as siblings of directory `channeldir`.
[ "Create", "empty", ".", "csv", "files", "with", "the", "right", "headers", "and", "place", "them", "in", "the", "Will", "place", "files", "as", "siblings", "of", "directory", "channeldir", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L844-L861
train
learningequality/ricecooker
ricecooker/utils/metadata_provider.py
CsvMetadataProvider.generate_template
def generate_template(self, channeldir, filename, header): """ Create empty template .csv file called `filename` as siblings of the directory `channeldir` with header fields specified in `header`. """ file_path = get_metadata_file_path(channeldir, filename) if not os.path...
python
def generate_template(self, channeldir, filename, header): """ Create empty template .csv file called `filename` as siblings of the directory `channeldir` with header fields specified in `header`. """ file_path = get_metadata_file_path(channeldir, filename) if not os.path...
[ "def", "generate_template", "(", "self", ",", "channeldir", ",", "filename", ",", "header", ")", ":", "file_path", "=", "get_metadata_file_path", "(", "channeldir", ",", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "file_path", ")", ...
Create empty template .csv file called `filename` as siblings of the directory `channeldir` with header fields specified in `header`.
[ "Create", "empty", "template", ".", "csv", "file", "called", "filename", "as", "siblings", "of", "the", "directory", "channeldir", "with", "header", "fields", "specified", "in", "header", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L863-L872
train
learningequality/ricecooker
ricecooker/commands.py
authenticate_user
def authenticate_user(token): """ Add the content curation Authorizatino `token` header to `config.SESSION`. """ config.SESSION.headers.update({"Authorization": "Token {0}".format(token)}) try: response = config.SESSION.post(config.authentication_url()) response.raise_for_status() ...
python
def authenticate_user(token): """ Add the content curation Authorizatino `token` header to `config.SESSION`. """ config.SESSION.headers.update({"Authorization": "Token {0}".format(token)}) try: response = config.SESSION.post(config.authentication_url()) response.raise_for_status() ...
[ "def", "authenticate_user", "(", "token", ")", ":", "config", ".", "SESSION", ".", "headers", ".", "update", "(", "{", "\"Authorization\"", ":", "\"Token {0}\"", ".", "format", "(", "token", ")", "}", ")", "try", ":", "response", "=", "config", ".", "SES...
Add the content curation Authorizatino `token` header to `config.SESSION`.
[ "Add", "the", "content", "curation", "Authorizatino", "token", "header", "to", "config", ".", "SESSION", "." ]
2f0385282500cb77ef2894646c6f9ce11bd7a853
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/commands.py#L184-L197
train
SBRG/ssbio
ssbio/protein/structure/properties/residues.py
residue_distances
def residue_distances(res_1_num, res_1_chain, res_2_num, res_2_chain, model): """Distance between the last atom of 2 residues""" res1 = model[res_1_chain][res_1_num].child_list[-1] res2 = model[res_2_chain][res_2_num].child_list[-1] distance = res1 - res2 return distance
python
def residue_distances(res_1_num, res_1_chain, res_2_num, res_2_chain, model): """Distance between the last atom of 2 residues""" res1 = model[res_1_chain][res_1_num].child_list[-1] res2 = model[res_2_chain][res_2_num].child_list[-1] distance = res1 - res2 return distance
[ "def", "residue_distances", "(", "res_1_num", ",", "res_1_chain", ",", "res_2_num", ",", "res_2_chain", ",", "model", ")", ":", "res1", "=", "model", "[", "res_1_chain", "]", "[", "res_1_num", "]", ".", "child_list", "[", "-", "1", "]", "res2", "=", "mod...
Distance between the last atom of 2 residues
[ "Distance", "between", "the", "last", "atom", "of", "2", "residues" ]
e9449e64ffc1a1f5ad07e5849aa12a650095f8a2
https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/properties/residues.py#L82-L89
train