repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
pudo/jsonmapping
jsonmapping/statements.py
StatementsVisitor.get_subject
python
def get_subject(self, data): if not isinstance(data, Mapping): return None if data.get(self.subject): return data.get(self.subject) return uuid.uuid4().urn
Try to get a unique ID from the object. By default, this will be the 'id' field of any given object, or a field specified by the 'rdfSubject' property. If no other option is available, a UUID will be generated.
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/statements.py#L22-L31
null
class StatementsVisitor(SchemaVisitor): """ This class has utility functions for transforming JSON schema defined objects into a series of RDF-like statements (i.e. subject, predicate, object, context) quads. It can be used independently of any specific storage backend, including RDF. """ @property...
pudo/jsonmapping
jsonmapping/statements.py
StatementsVisitor.reverse
python
def reverse(self): name = self.schema.get('rdfReverse') if name is not None: return name if self.parent is not None and self.parent.is_array: return self.parent.reverse
Reverse links make sense for object to object links where we later may want to also query the reverse of the relationship, e.g. when obj1 is a child of obj2, we want to infer that obj2 is a parent of obj1.
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/statements.py#L38-L46
null
class StatementsVisitor(SchemaVisitor): """ This class has utility functions for transforming JSON schema defined objects into a series of RDF-like statements (i.e. subject, predicate, object, context) quads. It can be used independently of any specific storage backend, including RDF. """ @property...
pudo/jsonmapping
jsonmapping/statements.py
StatementsVisitor.triplify
python
def triplify(self, data, parent=None): if data is None: return if self.is_object: for res in self._triplify_object(data, parent): yield res elif self.is_array: for item in data: for res in self.items.triplify(item, parent): ...
Recursively generate statements from the data supplied.
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/statements.py#L53-L71
[ "def _triplify_object(self, data, parent):\n \"\"\" Create bi-directional statements for object relationships. \"\"\"\n subject = self.get_subject(data)\n if self.path:\n yield (subject, TYPE_SCHEMA, self.path, TYPE_SCHEMA)\n\n if parent is not None:\n yield (parent, self.predicate, subjec...
class StatementsVisitor(SchemaVisitor): """ This class has utility functions for transforming JSON schema defined objects into a series of RDF-like statements (i.e. subject, predicate, object, context) quads. It can be used independently of any specific storage backend, including RDF. """ @property...
pudo/jsonmapping
jsonmapping/statements.py
StatementsVisitor._triplify_object
python
def _triplify_object(self, data, parent): subject = self.get_subject(data) if self.path: yield (subject, TYPE_SCHEMA, self.path, TYPE_SCHEMA) if parent is not None: yield (parent, self.predicate, subject, TYPE_LINK) if self.reverse is not None: ...
Create bi-directional statements for object relationships.
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/statements.py#L73-L86
[ "def get_subject(self, data):\n \"\"\" Try to get a unique ID from the object. By default, this will be\n the 'id' field of any given object, or a field specified by the\n 'rdfSubject' property. If no other option is available, a UUID will be\n generated. \"\"\"\n if not isinstance(data, Mapping):\n ...
class StatementsVisitor(SchemaVisitor): """ This class has utility functions for transforming JSON schema defined objects into a series of RDF-like statements (i.e. subject, predicate, object, context) quads. It can be used independently of any specific storage backend, including RDF. """ @property...
pudo/jsonmapping
jsonmapping/statements.py
StatementsVisitor.objectify
python
def objectify(self, load, node, depth=2, path=None): if path is None: path = set() if self.is_object: if depth < 1: return return self._objectify_object(load, node, depth, path) elif self.is_array: if depth < 1: ret...
Given a node ID, return an object the information available about this node. This accepts a loader function as it's first argument, which is expected to return all tuples of (predicate, object, source) for the given subject.
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/statements.py#L89-L106
[ "def _objectify_object(self, load, node, depth, path):\n # Support inline objects which don't count towards the depth.\n next_depth = depth\n if not self.schema.get('inline'):\n next_depth = depth - 1\n\n sub_path = path.union([node])\n obj = {\n self.subject: node,\n '$schema': ...
class StatementsVisitor(SchemaVisitor): """ This class has utility functions for transforming JSON schema defined objects into a series of RDF-like statements (i.e. subject, predicate, object, context) quads. It can be used independently of any specific storage backend, including RDF. """ @property...
Arello-Mobile/swagger2rst
swg2rst/swagger/abstract_type_object.py
convert
python
def convert(data): try: st = basestring except NameError: st = str if isinstance(data, st): return str(data) elif isinstance(data, Mapping): return dict(map(convert, data.iteritems())) elif isinstance(data, Iterable): return type(data)(map(convert, data)) ...
Convert from unicode to native ascii
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/swagger/abstract_type_object.py#L103-L118
null
import json from hashlib import md5 from collections import Mapping, Iterable from .constants import SchemaTypes class AbstractTypeObject(object): _type = None type_format = None properties = None item = None #: set if type is array def __init__(self, obj, name, root, storage): self.raw ...
Arello-Mobile/swagger2rst
swg2rst/swagger/abstract_type_object.py
AbstractTypeObject.get_type_properties
python
def get_type_properties(self, property_obj, name, additional_prop=False): property_type = property_obj.get('type', 'object') property_format = property_obj.get('format') property_dict = {} if property_type in ['object', 'array']: schema_type = SchemaTypes.MAPPED if additiona...
Get internal properties of property (extended in schema) :param dict property_obj: raw property object :param str name: name of property :param bool additional_prop: recursion's param :return: Type, format and internal properties of property :rtype: tuple(str, str, dict)
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/swagger/abstract_type_object.py#L19-L55
[ "def convert(data):\n \"\"\"\n Convert from unicode to native ascii\n \"\"\"\n try:\n st = basestring\n except NameError:\n st = str\n if isinstance(data, st):\n return str(data)\n elif isinstance(data, Mapping):\n return dict(map(convert, data.iteritems()))\n eli...
class AbstractTypeObject(object): _type = None type_format = None properties = None item = None #: set if type is array def __init__(self, obj, name, root, storage): self.raw = obj self.name = name self.root = root self.storage = storage @staticmethod def ...
Arello-Mobile/swagger2rst
swg2rst/swagger/abstract_type_object.py
AbstractTypeObject.set_type_by_schema
python
def set_type_by_schema(self, schema_obj, schema_type): schema_id = self._get_object_schema_id(schema_obj, schema_type) if not self.storage.contains(schema_id): schema = self.storage.create_schema( schema_obj, self.name, schema_type, root=self.root) assert schema....
Set property type by schema object Schema will create, if it doesn't exists in collection :param dict schema_obj: raw schema object :param str schema_type:
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/swagger/abstract_type_object.py#L75-L89
[ "def _get_object_schema_id(self, obj, schema_type):\n if (schema_type == SchemaTypes.prefixes[SchemaTypes.MAPPED]) and ('$ref' in obj):\n base = obj['$ref']\n prefix = schema_type\n elif '$ref' in obj:\n base = obj['$ref']\n prefix = SchemaTypes.prefixes[SchemaTypes.DEFINITION]\n ...
class AbstractTypeObject(object): _type = None type_format = None properties = None item = None #: set if type is array def __init__(self, obj, name, root, storage): self.raw = obj self.name = name self.root = root self.storage = storage def get_type_properties...
Arello-Mobile/swagger2rst
swg2rst/swagger/base_swagger_object.py
BaseSwaggerObject._fill_schemas_from_definitions
python
def _fill_schemas_from_definitions(self, obj): if obj.get('definitions'): self.schemas.clear() all_of_stack = [] for name, definition in obj['definitions'].items(): if 'allOf' in definition: all_of_stack.append((name, definition)) ...
At first create schemas without 'AllOf' :param obj: :return: None
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/swagger/base_swagger_object.py#L108-L125
null
class BaseSwaggerObject(SecurityMixin): """ Represents Swagger Object """ raw = None #: Operation collection #: #: key: operation_id, value: Operation object operations = None #: Operations grouped by tags #: #: key: tag name, value: list of Operation object tags = None...
Arello-Mobile/swagger2rst
swg2rst/swagger/schema.py
Schema.get_type_properties
python
def get_type_properties(self, property_obj, name, additional_prop=False): property_type, property_format, property_dict = \ super(Schema, self).get_type_properties(property_obj, name, additional_prop=additional_prop) _schema = self.storage.get(property_type) if _schema and ('addition...
Extend parents 'Get internal properties of property'-method
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/swagger/schema.py#L55-L71
[ "def get_type_properties(self, property_obj, name, additional_prop=False):\n \"\"\" Get internal properties of property (extended in schema)\n\n :param dict property_obj: raw property object\n :param str name: name of property\n :param bool additional_prop: recursion's param\n :return: Type, format a...
class Schema(AbstractTypeObject): """ Represents Swagger Schema Object """ schema_id = None schema_type = None #: definition or inline ref_path = None #: path for definition schemas nested_schemas = None all_of = None def __init__(self, obj, schema_type, **kwargs): assert ...
Arello-Mobile/swagger2rst
swg2rst/utils/rst.py
SwaggerObject.sorted
python
def sorted(collection): if len(collection) < 1: return collection if isinstance(collection, dict): return sorted(collection.items(), key=lambda x: x[0]) if isinstance(list(collection)[0], Operation): key = lambda x: x.operation_id elif isinstance(lis...
sorting dict by key, schema-collection by schema-name operations by id
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/utils/rst.py#L24-L42
null
class SwaggerObject(BaseSwaggerObject): @staticmethod def get_regular_properties(self, _type, *args, **kwargs): """Make table with properties by schema_id :param str _type: :rtype: str """ if not SchemaObjects.contains(_type): return _type schema = ...
Arello-Mobile/swagger2rst
swg2rst/utils/rst.py
SwaggerObject.get_regular_properties
python
def get_regular_properties(self, _type, *args, **kwargs): if not SchemaObjects.contains(_type): return _type schema = SchemaObjects.get(_type) if schema.schema_type == SchemaTypes.DEFINITION and not kwargs.get('definition'): return '' head = """.. csv-table:: ...
Make table with properties by schema_id :param str _type: :rtype: str
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/utils/rst.py#L44-L72
[ "def contains(cls, key):\n \"\"\" Check schema existence in collection by id\n\n :param str key:\n :rtype: bool\n \"\"\"\n return key in cls._schemas\n" ]
class SwaggerObject(BaseSwaggerObject): @staticmethod def sorted(collection): """ sorting dict by key, schema-collection by schema-name operations by id """ if len(collection) < 1: return collection if isinstance(collection, dict): ...
Arello-Mobile/swagger2rst
swg2rst/utils/rst.py
SwaggerObject.get_type_description
python
def get_type_description(self, _type, suffix='', *args, **kwargs): if not SchemaObjects.contains(_type): return _type schema = SchemaObjects.get(_type) if schema.all_of: models = ','.join( (self.get_type_description(_type, *args, **kwargs) for _type in sch...
Get description of type :param suffix: :param str _type: :rtype: str
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/utils/rst.py#L74-L95
[ "def contains(cls, key):\n \"\"\" Check schema existence in collection by id\n\n :param str key:\n :rtype: bool\n \"\"\"\n return key in cls._schemas\n" ]
class SwaggerObject(BaseSwaggerObject): @staticmethod def sorted(collection): """ sorting dict by key, schema-collection by schema-name operations by id """ if len(collection) < 1: return collection if isinstance(collection, dict): ...
Arello-Mobile/swagger2rst
swg2rst/utils/rst.py
SwaggerObject.get_additional_properties
python
def get_additional_properties(self, _type, *args, **kwargs): if not SchemaObjects.contains(_type): return _type schema = SchemaObjects.get(_type) body = [] for sch in schema.nested_schemas: # complex types nested_schema = SchemaObjects.get(sch) if not...
Make head and table with additional properties by schema_id :param str _type: :rtype: str
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/utils/rst.py#L97-L123
[ "def contains(cls, key):\n \"\"\" Check schema existence in collection by id\n\n :param str key:\n :rtype: bool\n \"\"\"\n return key in cls._schemas\n" ]
class SwaggerObject(BaseSwaggerObject): @staticmethod def sorted(collection): """ sorting dict by key, schema-collection by schema-name operations by id """ if len(collection) < 1: return collection if isinstance(collection, dict): ...
Arello-Mobile/swagger2rst
swg2rst/swagger/schema_objects.py
SchemaObjects.create_schema
python
def create_schema(cls, obj, name, schema_type, root): if schema_type == SchemaTypes.MAPPED: schema = SchemaMapWrapper(obj, storage=cls, name=name, root=root) else: schema = Schema(obj, schema_type, storage=cls, name=name, root=root) cls.add_schema(schema) return s...
Create Schema object :param dict obj: swagger schema object :param str name: schema name :param str schema_type: schema location. Can be ``inline``, ``definition`` or ``mapped`` :param BaseSwaggerObject root: root doc :return: new schema :rtype: Schema
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/swagger/schema_objects.py#L15-L31
null
class SchemaObjects(object): """ Schema collection """ _schemas = OrderedDict() @classmethod @classmethod def add_schema(cls, schema): """ Add schema object to collection :param Schema schema: """ cls._schemas[schema.schema_id] = schema @classmethod ...
Arello-Mobile/swagger2rst
swg2rst/swagger/schema_objects.py
SchemaObjects.get_schemas
python
def get_schemas(cls, schema_types=None, sort=True): result = filter(lambda x: not x.is_inline_array, cls._schemas.values()) if schema_types: result = filter(lambda x: x.schema_type in schema_types, result) if sort: result = sorted(result, key=attrgetter('name')) r...
Get schemas by type. If ``schema_type`` is None, return all schemas :param schema_types: list of schema types :type schema_types: list or None :param bool sort: sort by name :return: list of schemas :rtype: list
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/swagger/schema_objects.py#L52-L67
null
class SchemaObjects(object): """ Schema collection """ _schemas = OrderedDict() @classmethod def create_schema(cls, obj, name, schema_type, root): """ Create Schema object :param dict obj: swagger schema object :param str name: schema name :param str schema_typ...
Arello-Mobile/swagger2rst
swg2rst/swagger/schema_objects.py
SchemaObjects.merge_schemas
python
def merge_schemas(cls, schema, _schema): tmp = schema.properties[:] # copy prop = {} to_dict = lambda e: prop.update({e.pop('name'): e}) [to_dict(i) for i in tmp] # map(to_dict, tmp) for _prop in _schema.properties: if prop.get(_prop['name']): prop.p...
Return second Schema, which is extended by first Schema https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#composition-and-inheritance-polymorphism
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/swagger/schema_objects.py#L83-L98
null
class SchemaObjects(object): """ Schema collection """ _schemas = OrderedDict() @classmethod def create_schema(cls, obj, name, schema_type, root): """ Create Schema object :param dict obj: swagger schema object :param str name: schema name :param str schema_typ...
Arello-Mobile/swagger2rst
swg2rst/utils/exampilators.py
Exampilator.get_example_by_schema
python
def get_example_by_schema(cls, schema, ignored_schemas=None, paths=None, name=''): if schema.schema_example: return schema.schema_example if ignored_schemas is None: ignored_schemas = [] if paths is None: paths = [] if name: paths = list...
Get example by schema object :param Schema schema: current schema :param list ignored_schemas: list of previous schemas for avoid circular references :param list paths: list object paths (ex. #/definitions/Model.property) If nested schemas exists, custom examples checks ...
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/utils/exampilators.py#L107-L156
[ "def get(cls, schema_id):\n \"\"\" Get schema object from collection by id\n\n :param str schema_id:\n :return: schema\n :rtype: Schema\n \"\"\"\n return cls._schemas.get(schema_id)\n" ]
class Exampilator(object): """ Example Manager """ DEFAULT_EXAMPLES = DEFAULT_EXAMPLES.copy() CUSTOM_EXAMPLES = dict() EXAMPLE_ARRAY_ITEMS_COUNT = 2 logger = get_logger() _json_format_checker = FormatChecker() @classmethod def fill_examples(cls, examples): if 'array_i...
Arello-Mobile/swagger2rst
swg2rst/utils/exampilators.py
Exampilator.get_body_example
python
def get_body_example(cls, operation): path = "#/paths/'{0.path}'/{0.method}/parameters/{name}".format( operation, name=operation.body.name or 'body') return cls.get_example_by_schema(operation.body, paths=[path])
Get example for body parameter example by operation :param Operation operation: operation object
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/utils/exampilators.py#L159-L166
null
class Exampilator(object): """ Example Manager """ DEFAULT_EXAMPLES = DEFAULT_EXAMPLES.copy() CUSTOM_EXAMPLES = dict() EXAMPLE_ARRAY_ITEMS_COUNT = 2 logger = get_logger() _json_format_checker = FormatChecker() @classmethod def fill_examples(cls, examples): if 'array_i...
Arello-Mobile/swagger2rst
swg2rst/utils/exampilators.py
Exampilator.get_response_example
python
def get_response_example(cls, operation, response): path = "#/paths/'{}'/{}/responses/{}".format( operation.path, operation.method, response.name) kwargs = dict(paths=[path]) if response.type in PRIMITIVE_TYPES: result = cls.get_example_value_for_primitive_type( ...
Get example for response object by operation object :param Operation operation: operation object :param Response response: response object
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/utils/exampilators.py#L169-L186
[ "def get(cls, schema_id):\n \"\"\" Get schema object from collection by id\n\n :param str schema_id:\n :return: schema\n :rtype: Schema\n \"\"\"\n return cls._schemas.get(schema_id)\n" ]
class Exampilator(object): """ Example Manager """ DEFAULT_EXAMPLES = DEFAULT_EXAMPLES.copy() CUSTOM_EXAMPLES = dict() EXAMPLE_ARRAY_ITEMS_COUNT = 2 logger = get_logger() _json_format_checker = FormatChecker() @classmethod def fill_examples(cls, examples): if 'array_i...
Arello-Mobile/swagger2rst
swg2rst/utils/exampilators.py
Exampilator.get_header_example
python
def get_header_example(cls, header): if header.is_array: result = cls.get_example_for_array(header.item) else: example_method = getattr(cls, '{}_example'.format(header.type)) result = example_method(header.properties, header.type_format) return {header.name: r...
Get example for header object :param Header header: Header object :return: example :rtype: dict
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/utils/exampilators.py#L189-L201
null
class Exampilator(object): """ Example Manager """ DEFAULT_EXAMPLES = DEFAULT_EXAMPLES.copy() CUSTOM_EXAMPLES = dict() EXAMPLE_ARRAY_ITEMS_COUNT = 2 logger = get_logger() _json_format_checker = FormatChecker() @classmethod def fill_examples(cls, examples): if 'array_i...
Arello-Mobile/swagger2rst
swg2rst/utils/exampilators.py
Exampilator.get_property_example
python
def get_property_example(cls, property_, nested=None, **kw): paths = kw.get('paths', []) name = kw.get('name', '') result = None if name and paths: paths = list(map(lambda path: '.'.join((path, name)), paths)) result, path = cls._get_custom_example(paths) ...
Get example for property :param dict property_: :param set nested: :return: example value
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/utils/exampilators.py#L204-L253
[ "def contains(cls, key):\n \"\"\" Check schema existence in collection by id\n\n :param str key:\n :rtype: bool\n \"\"\"\n return key in cls._schemas\n" ]
class Exampilator(object): """ Example Manager """ DEFAULT_EXAMPLES = DEFAULT_EXAMPLES.copy() CUSTOM_EXAMPLES = dict() EXAMPLE_ARRAY_ITEMS_COUNT = 2 logger = get_logger() _json_format_checker = FormatChecker() @classmethod def fill_examples(cls, examples): if 'array_i...
Arello-Mobile/swagger2rst
swg2rst/swagger/operation.py
Operation.get_parameters_by_location
python
def get_parameters_by_location(self, locations=None, excludes=None): result = self.parameters if locations: result = filter(lambda x: x.location_in in locations, result) if excludes: result = filter(lambda x: x.location_in not in excludes, result) return list(resu...
Get parameters list by location :param locations: list of locations :type locations: list or None :param excludes: list of excludes locations :type excludes: list or None :return: list of Parameter :rtype: list
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/swagger/operation.py#L72-L87
null
class Operation(SecurityMixin): """ Represents Swagger Operation Object """ parameters = None responses = None method = None path = None root = None #: root swagger object def __init__(self, obj, method, path, root, storage, path_params=None): self.method = method s...
Arello-Mobile/swagger2rst
swg2rst/swagger/operation.py
Operation.body
python
def body(self): body = self.get_parameters_by_location(['body']) return self.root.schemas.get(body[0].type) if body else None
Return body request parameter :return: Body parameter :rtype: Parameter or None
train
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/swagger/operation.py#L90-L97
[ "def get_parameters_by_location(self, locations=None, excludes=None):\n \"\"\" Get parameters list by location\n\n :param locations: list of locations\n :type locations: list or None\n :param excludes: list of excludes locations\n :type excludes: list or None\n :return: list of Parameter\n :rty...
class Operation(SecurityMixin): """ Represents Swagger Operation Object """ parameters = None responses = None method = None path = None root = None #: root swagger object def __init__(self, obj, method, path, root, storage, path_params=None): self.method = method s...
todbot/blink1-python
blink1/blink1.py
blink1
python
def blink1(switch_off=True, gamma=None, white_point=None): b1 = Blink1(gamma=gamma, white_point=white_point) yield b1 if switch_off: b1.off() b1.close()
Context manager which automatically shuts down the Blink(1) after use. :param switch_off: turn blink(1) off when existing context :param gamma: set gamma curve (as tuple) :param white_point: set white point (as tuple)
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L303-L314
[ "def close(self):\n self.dev.close()\n self.dev = None\n", "def off(self):\n \"\"\"Switch the blink(1) off instantly\n \"\"\"\n self.fade_to_color(0, 'black')\n" ]
""" blink1.py -- blink(1) Python library using python hidapi All platforms: % pip install blink1 """ import logging import time import sys from contextlib import contextmanager import webcolors import hid import os #from builtins import str as text from .kelvin import kelvin_to_rgb, COLOR_TEMPERATURES class Blink...
todbot/blink1-python
blink1/blink1.py
Blink1.find
python
def find(serial_number=None): try: hidraw = hid.device(VENDOR_ID,PRODUCT_ID,serial_number) hidraw.open(VENDOR_ID,PRODUCT_ID,serial_number) # hidraw = hid.device(VENDOR_ID,PRODUCT_ID,unicode(serial_number)) # hidraw.open(VENDOR_ID,PRODUCT_ID,unicode(serial_number))...
Find a praticular blink(1) device, or the first one :param serial_number: serial number of blink(1) device (from Blink1.list())
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L90-L107
null
class Blink1: """Light controller class, sends messages to the blink(1) and blink(1) mk2 via USB HID. """ def __init__(self, serial_number=None, gamma=None, white_point=None): """ :param serial_number: serial number of blink(1) to open, otherwise first found :param gamma: Triple of g...
todbot/blink1-python
blink1/blink1.py
Blink1.list
python
def list(): try: devs = hid.enumerate(VENDOR_ID,PRODUCT_ID) serials = list(map(lambda d:d.get('serial_number'), devs)) return serials except IOError as e: return []
List blink(1) devices connected, by serial number :return: List of blink(1) device serial numbers
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L110-L120
null
class Blink1: """Light controller class, sends messages to the blink(1) and blink(1) mk2 via USB HID. """ def __init__(self, serial_number=None, gamma=None, white_point=None): """ :param serial_number: serial number of blink(1) to open, otherwise first found :param gamma: Triple of g...
todbot/blink1-python
blink1/blink1.py
Blink1.write
python
def write(self,buf): log.debug("blink1write:" + ",".join('0x%02x' % v for v in buf)) self.dev.send_feature_report(buf)
Write command to blink(1), low-level internal use Send USB Feature Report 0x01 to blink(1) with 8-byte payload Note: arg 'buf' must be 8 bytes or bad things happen
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L125-L132
null
class Blink1: """Light controller class, sends messages to the blink(1) and blink(1) mk2 via USB HID. """ def __init__(self, serial_number=None, gamma=None, white_point=None): """ :param serial_number: serial number of blink(1) to open, otherwise first found :param gamma: Triple of g...
todbot/blink1-python
blink1/blink1.py
Blink1.read
python
def read(self): buf = self.dev.get_feature_report(REPORT_ID,9) log.debug("blink1read: " + ",".join('0x%02x' % v for v in buf)) return buf
Read command result from blink(1), low-level internal use Receive USB Feature Report 0x01 from blink(1) with 8-byte payload Note: buf must be 8 bytes or bad things happen
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L134-L142
null
class Blink1: """Light controller class, sends messages to the blink(1) and blink(1) mk2 via USB HID. """ def __init__(self, serial_number=None, gamma=None, white_point=None): """ :param serial_number: serial number of blink(1) to open, otherwise first found :param gamma: Triple of g...
todbot/blink1-python
blink1/blink1.py
Blink1.fade_to_rgb_uncorrected
python
def fade_to_rgb_uncorrected(self, fade_milliseconds, red, green, blue, led_number=0): action = ord('c') fade_time = int(fade_milliseconds / 10) th = (fade_time & 0xff00) >> 8 tl = fade_time & 0x00ff buf = [REPORT_ID, action, int(red), int(green), int(blue), th, tl, led_number, 0]...
Command blink(1) to fade to RGB color, no color correction applied.
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L144-L153
[ "def write(self,buf):\n \"\"\"\n Write command to blink(1), low-level internal use\n Send USB Feature Report 0x01 to blink(1) with 8-byte payload\n Note: arg 'buf' must be 8 bytes or bad things happen\n \"\"\"\n log.debug(\"blink1write:\" + \",\".join('0x%02x' % v for v in buf))\n self.dev.send...
class Blink1: """Light controller class, sends messages to the blink(1) and blink(1) mk2 via USB HID. """ def __init__(self, serial_number=None, gamma=None, white_point=None): """ :param serial_number: serial number of blink(1) to open, otherwise first found :param gamma: Triple of g...
todbot/blink1-python
blink1/blink1.py
Blink1.color_to_rgb
python
def color_to_rgb(color): if isinstance(color, tuple): return color if color.startswith('#'): try: return webcolors.hex_to_rgb(color) except ValueError: raise InvalidColor(color) try: return webcolors.name_to_rgb(col...
Convert color name or hexcode to (r,g,b) tuple
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L160-L175
null
class Blink1: """Light controller class, sends messages to the blink(1) and blink(1) mk2 via USB HID. """ def __init__(self, serial_number=None, gamma=None, white_point=None): """ :param serial_number: serial number of blink(1) to open, otherwise first found :param gamma: Triple of g...
todbot/blink1-python
blink1/blink1.py
Blink1.fade_to_color
python
def fade_to_color(self, fade_milliseconds, color): red, green, blue = self.color_to_rgb(color) return self.fade_to_rgb(fade_milliseconds, red, green, blue)
Fade the light to a known colour in a :param fade_milliseconds: Duration of the fade in milliseconds :param color: Named color to fade to :return: None
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L178-L187
[ "def fade_to_rgb(self,fade_milliseconds, red, green, blue, led_number=0):\n r, g, b = self.cc(red, green, blue)\n return self.fade_to_rgb_uncorrected(fade_milliseconds, r, g, b, led_number)\n", "def color_to_rgb(color):\n \"\"\"\n Convert color name or hexcode to (r,g,b) tuple\n \"\"\"\n if isin...
class Blink1: """Light controller class, sends messages to the blink(1) and blink(1) mk2 via USB HID. """ def __init__(self, serial_number=None, gamma=None, white_point=None): """ :param serial_number: serial number of blink(1) to open, otherwise first found :param gamma: Triple of g...
todbot/blink1-python
blink1/blink1.py
Blink1.get_version
python
def get_version(self): if ( self.dev == None ): return '' buf = [REPORT_ID, ord('v'), 0, 0, 0, 0, 0, 0, 0] self.write(buf) time.sleep(.05) version_raw = self.read() version = (version_raw[3] - ord('0')) * 100 + (version_raw[4] - ord('0')) return str(version)
Get blink(1) firmware version
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L194-L203
[ "def write(self,buf):\n \"\"\"\n Write command to blink(1), low-level internal use\n Send USB Feature Report 0x01 to blink(1) with 8-byte payload\n Note: arg 'buf' must be 8 bytes or bad things happen\n \"\"\"\n log.debug(\"blink1write:\" + \",\".join('0x%02x' % v for v in buf))\n self.dev.send...
class Blink1: """Light controller class, sends messages to the blink(1) and blink(1) mk2 via USB HID. """ def __init__(self, serial_number=None, gamma=None, white_point=None): """ :param serial_number: serial number of blink(1) to open, otherwise first found :param gamma: Triple of g...
todbot/blink1-python
blink1/blink1.py
Blink1.play
python
def play(self, start_pos=0, end_pos=0, count=0): if ( self.dev == None ): return '' buf = [REPORT_ID, ord('p'), 1, int(start_pos), int(end_pos), int(count), 0, 0, 0] return self.write(buf);
Play internal color pattern :param start_pos: pattern line to start from :param end_pos: pattern line to end at :param count: number of times to play, 0=play forever
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L212-L220
[ "def write(self,buf):\n \"\"\"\n Write command to blink(1), low-level internal use\n Send USB Feature Report 0x01 to blink(1) with 8-byte payload\n Note: arg 'buf' must be 8 bytes or bad things happen\n \"\"\"\n log.debug(\"blink1write:\" + \",\".join('0x%02x' % v for v in buf))\n self.dev.send...
class Blink1: """Light controller class, sends messages to the blink(1) and blink(1) mk2 via USB HID. """ def __init__(self, serial_number=None, gamma=None, white_point=None): """ :param serial_number: serial number of blink(1) to open, otherwise first found :param gamma: Triple of g...
todbot/blink1-python
blink1/blink1.py
Blink1.stop
python
def stop(self): if ( self.dev == None ): return '' buf = [REPORT_ID, ord('p'), 0, 0, 0, 0, 0, 0, 0] return self.write(buf);
Stop internal color pattern playing
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L222-L227
[ "def write(self,buf):\n \"\"\"\n Write command to blink(1), low-level internal use\n Send USB Feature Report 0x01 to blink(1) with 8-byte payload\n Note: arg 'buf' must be 8 bytes or bad things happen\n \"\"\"\n log.debug(\"blink1write:\" + \",\".join('0x%02x' % v for v in buf))\n self.dev.send...
class Blink1: """Light controller class, sends messages to the blink(1) and blink(1) mk2 via USB HID. """ def __init__(self, serial_number=None, gamma=None, white_point=None): """ :param serial_number: serial number of blink(1) to open, otherwise first found :param gamma: Triple of g...
todbot/blink1-python
blink1/blink1.py
Blink1.savePattern
python
def savePattern(self): if ( self.dev == None ): return '' buf = [REPORT_ID, ord('W'), 0xBE, 0xEF, 0xCA, 0xFE, 0, 0, 0] return self.write(buf);
Save internal RAM pattern to flash
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L229-L234
[ "def write(self,buf):\n \"\"\"\n Write command to blink(1), low-level internal use\n Send USB Feature Report 0x01 to blink(1) with 8-byte payload\n Note: arg 'buf' must be 8 bytes or bad things happen\n \"\"\"\n log.debug(\"blink1write:\" + \",\".join('0x%02x' % v for v in buf))\n self.dev.send...
class Blink1: """Light controller class, sends messages to the blink(1) and blink(1) mk2 via USB HID. """ def __init__(self, serial_number=None, gamma=None, white_point=None): """ :param serial_number: serial number of blink(1) to open, otherwise first found :param gamma: Triple of g...
todbot/blink1-python
blink1/blink1.py
Blink1.setLedN
python
def setLedN(self, led_number=0): if ( self.dev == None ): return '' buf = [REPORT_ID, ord('l'), led_number, 0,0,0,0,0,0] self.write(buf)
Set the 'current LED' value for writePatternLine :param led_number: LED to adjust, 0=all, 1=LEDA, 2=LEDB
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L236-L242
[ "def write(self,buf):\n \"\"\"\n Write command to blink(1), low-level internal use\n Send USB Feature Report 0x01 to blink(1) with 8-byte payload\n Note: arg 'buf' must be 8 bytes or bad things happen\n \"\"\"\n log.debug(\"blink1write:\" + \",\".join('0x%02x' % v for v in buf))\n self.dev.send...
class Blink1: """Light controller class, sends messages to the blink(1) and blink(1) mk2 via USB HID. """ def __init__(self, serial_number=None, gamma=None, white_point=None): """ :param serial_number: serial number of blink(1) to open, otherwise first found :param gamma: Triple of g...
todbot/blink1-python
blink1/blink1.py
Blink1.writePatternLine
python
def writePatternLine(self, step_milliseconds, color, pos, led_number=0): if ( self.dev == None ): return '' self.setLedN(led_number) red, green, blue = self.color_to_rgb(color) r, g, b = self.cc(red, green, blue) step_time = int(step_milliseconds / 10) th = (step_time & 0...
Write a color & step time color pattern line to RAM :param step_milliseconds: how long for this pattern line to take :param color: LED color :param pos: color pattern line number (0-15) :param led_number: LED to adjust, 0=all, 1=LEDA, 2=LEDB
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L244-L259
[ "def write(self,buf):\n \"\"\"\n Write command to blink(1), low-level internal use\n Send USB Feature Report 0x01 to blink(1) with 8-byte payload\n Note: arg 'buf' must be 8 bytes or bad things happen\n \"\"\"\n log.debug(\"blink1write:\" + \",\".join('0x%02x' % v for v in buf))\n self.dev.send...
class Blink1: """Light controller class, sends messages to the blink(1) and blink(1) mk2 via USB HID. """ def __init__(self, serial_number=None, gamma=None, white_point=None): """ :param serial_number: serial number of blink(1) to open, otherwise first found :param gamma: Triple of g...
todbot/blink1-python
blink1/blink1.py
Blink1.readPatternLine
python
def readPatternLine(self, pos): if ( self.dev == None ): return '' buf = [REPORT_ID, ord('R'), 0, 0, 0, 0, 0, int(pos), 0] self.write(buf) buf = self.read() (r,g,b) = (buf[2],buf[3],buf[4]) step_millis = ((buf[5] << 8) | buf[6]) * 10 return (r,g,b,step_millis)
Read a color pattern line at position :param pos: pattern line to read :return pattern line data as tuple (r,g,b, step_millis)
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L261-L272
[ "def write(self,buf):\n \"\"\"\n Write command to blink(1), low-level internal use\n Send USB Feature Report 0x01 to blink(1) with 8-byte payload\n Note: arg 'buf' must be 8 bytes or bad things happen\n \"\"\"\n log.debug(\"blink1write:\" + \",\".join('0x%02x' % v for v in buf))\n self.dev.send...
class Blink1: """Light controller class, sends messages to the blink(1) and blink(1) mk2 via USB HID. """ def __init__(self, serial_number=None, gamma=None, white_point=None): """ :param serial_number: serial number of blink(1) to open, otherwise first found :param gamma: Triple of g...
todbot/blink1-python
blink1/blink1.py
Blink1.readPattern
python
def readPattern(self): if ( self.dev == None ): return '' pattern=[] for i in range(0,16): # FIXME: adjustable for diff blink(1) models pattern.append( self.readPatternLine(i) ) return pattern
Read the entire color pattern :return List of pattern line tuples
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L274-L282
[ "def readPatternLine(self, pos):\n \"\"\"Read a color pattern line at position\n :param pos: pattern line to read\n :return pattern line data as tuple (r,g,b, step_millis)\n \"\"\"\n if ( self.dev == None ): return ''\n buf = [REPORT_ID, ord('R'), 0, 0, 0, 0, 0, int(pos), 0]\n self.write(buf)\n...
class Blink1: """Light controller class, sends messages to the blink(1) and blink(1) mk2 via USB HID. """ def __init__(self, serial_number=None, gamma=None, white_point=None): """ :param serial_number: serial number of blink(1) to open, otherwise first found :param gamma: Triple of g...
todbot/blink1-python
blink1/blink1.py
Blink1.serverTickle
python
def serverTickle(self, enable, timeout_millis=0, stay_lit=False, start_pos=0, end_pos=16): if ( self.dev == None ): return '' en = int(enable == True) timeout_time = int(timeout_millis/10) th = (timeout_time & 0xff00) >>8 tl = timeout_time & 0x00ff st = int(stay_lit == Tr...
Enable/disable servertickle / serverdown watchdog :param: enable: Set True to enable serverTickle :param: timeout_millis: millisecs until servertickle is triggered :param: stay_lit: Set True to keep current color of blink(1), False to turn off :param: start_pos: Sub-pattern start positio...
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L284-L299
[ "def write(self,buf):\n \"\"\"\n Write command to blink(1), low-level internal use\n Send USB Feature Report 0x01 to blink(1) with 8-byte payload\n Note: arg 'buf' must be 8 bytes or bad things happen\n \"\"\"\n log.debug(\"blink1write:\" + \",\".join('0x%02x' % v for v in buf))\n self.dev.send...
class Blink1: """Light controller class, sends messages to the blink(1) and blink(1) mk2 via USB HID. """ def __init__(self, serial_number=None, gamma=None, white_point=None): """ :param serial_number: serial number of blink(1) to open, otherwise first found :param gamma: Triple of g...
todbot/blink1-python
blink1/kelvin.py
correct_output
python
def correct_output(luminosity): if luminosity < 0: val = 0 elif luminosity > 255: val = 255 else: val = luminosity return round(val)
:param luminosity: Input luminosity :return: Luminosity limited to the 0 <= l <= 255 range.
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/kelvin.py#L24-L35
null
""" Python implementation of Tanner Helland's color color conversion code. http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/ """ import math # Aproximate colour temperatures for common lighting conditions. COLOR_TEMPERATURES={ 'candle':1900, 'sunrise':2000, 'incandescent':2500, ...
todbot/blink1-python
blink1/kelvin.py
kelvin_to_rgb
python
def kelvin_to_rgb(kelvin): temp = kelvin / 100.0 # Calculate Red: if temp <= 66: red = 255 else: red = 329.698727446 * ((temp - 60) ** -0.1332047592) # Calculate Green: if temp <= 66: green = 99.4708025861 * math.log(temp) - 161.1195681661 else: green = 288...
Convert a color temperature given in kelvin to an approximate RGB value. :param kelvin: Color temp in K :return: Tuple of (r, g, b), equivalent color for the temperature
train
https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/kelvin.py#L37-L67
null
""" Python implementation of Tanner Helland's color color conversion code. http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/ """ import math # Aproximate colour temperatures for common lighting conditions. COLOR_TEMPERATURES={ 'candle':1900, 'sunrise':2000, 'incandescent':2500, ...
Pixelapse/pyglass
pyglass/quicklook/export.py
embedded_preview
python
def embedded_preview(src_path): ''' Returns path to temporary copy of embedded QuickLook preview, if it exists ''' try: assert(exists(src_path) and isdir(src_path)) preview_list = glob(join(src_path, '[Q|q]uicklook', '[P|p]review.*')) assert(preview_list) # Assert there's at least one preview file ...
Returns path to temporary copy of embedded QuickLook preview, if it exists
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/quicklook/export.py#L20-L36
[ "def extension(path_str):\n ''' Returns lowercased file extension for the path '''\n return os.path.splitext(path_str)[1].lower()\n" ]
# -*- coding: utf-8 -*- # Default libs import shutil from tempfile import NamedTemporaryFile, mkdtemp from os.path import isdir, exists, join, basename from glob import glob # Library modules from pxprocess import check_call # Project modules from ..settings import QLMANAGE from ..utils import extension ##########...
Pixelapse/pyglass
pyglass/quicklook/export.py
thumbnail_preview
python
def thumbnail_preview(src_path): ''' Returns the path to small thumbnail preview. ''' try: assert(exists(src_path)) width = '1980' dest_dir = mkdtemp(prefix='pyglass') cmd = [QLMANAGE, '-t', '-s', width, src_path, '-o', dest_dir] assert(check_call(cmd) == 0) src_filename = basename(src_pa...
Returns the path to small thumbnail preview.
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/quicklook/export.py#L60-L80
null
# -*- coding: utf-8 -*- # Default libs import shutil from tempfile import NamedTemporaryFile, mkdtemp from os.path import isdir, exists, join, basename from glob import glob # Library modules from pxprocess import check_call # Project modules from ..settings import QLMANAGE from ..utils import extension ##########...
Pixelapse/pyglass
pyglass/sketch/export.py
export_cmd
python
def export_cmd(cmd, src_path, dest_dir=None, item_id=None, export_format=None, scale=None): ''' Executes a `sketchtool export` command and returns formatted output :src_path: File to export. :type <str> :dest_dir: Items are exported at /dest_dir/name@scale.export_format e.g. `~/Desktop/Page 1@2x.png` :param ex...
Executes a `sketchtool export` command and returns formatted output :src_path: File to export. :type <str> :dest_dir: Items are exported at /dest_dir/name@scale.export_format e.g. `~/Desktop/Page 1@2x.png` :param export_format: 'png', 'pdf' etc. :type <ExportFormat> :param scale: Specify as 1.0, 2.0 etc. :type...
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/sketch/export.py#L19-L54
[ "def execute(cmd):\n ''' Call cmd and return output. return None if any exception occurs '''\n try:\n return safely_decode(check_output(cmd))\n except Exception as e:\n logger.warn(u'Couldnt execute cmd: %s.\\nReason: %s' % (cmd, e))\n return None\n" ]
# -*- coding: utf-8 -*- # Default libs import logging import os from glob import glob from tempfile import mkdtemp # Project modules from ..settings import SKETCHTOOL from ..utils import execute logger = logging.getLogger(__name__) ############################################################ # EXPORT COMMANDS - PA...
Pixelapse/pyglass
pyglass/sketch/api.py
list_cmd
python
def list_cmd(cmd, src_path): ''' Executes a `sketchtool list` command and parse the output :cmd: A sketchtool list command :type <list> :src_path: File to export. :type <str> :returns: A list of pages. Artboards & slices are included in the page hierarchy ''' cmd.extend([src_path]) logger.debug(u'Executi...
Executes a `sketchtool list` command and parse the output :cmd: A sketchtool list command :type <list> :src_path: File to export. :type <str> :returns: A list of pages. Artboards & slices are included in the page hierarchy
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/sketch/api.py#L24-L40
[ "def execute(cmd):\n ''' Call cmd and return output. return None if any exception occurs '''\n try:\n return safely_decode(check_output(cmd))\n except Exception as e:\n logger.warn(u'Couldnt execute cmd: %s.\\nReason: %s' % (cmd, e))\n return None\n", "def parse_pages(filename, list_dict):\n from .mo...
# -*- coding: utf-8 -*- # Default libs import json import logging # Project modules from ..settings import SKETCHTOOL from ..utils import execute, extension from .parse import parse_pages logger = logging.getLogger(__name__) def is_sketchfile(src_path): ''' Returns True if src_path is a sketch file ''' if exten...
Pixelapse/pyglass
pyglass/sketch/api.py
slices
python
def slices(src_path): ''' Return slices as a flat list ''' pages = list_slices(src_path) slices = [] for page in pages: slices.extend(page.slices) return slices
Return slices as a flat list
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/sketch/api.py#L67-L73
[ "def list_slices(src_path):\n cmd = [SKETCHTOOL, 'list', 'slices']\n return list_cmd(cmd, src_path)\n" ]
# -*- coding: utf-8 -*- # Default libs import json import logging # Project modules from ..settings import SKETCHTOOL from ..utils import execute, extension from .parse import parse_pages logger = logging.getLogger(__name__) def is_sketchfile(src_path): ''' Returns True if src_path is a sketch file ''' if exten...
Pixelapse/pyglass
pyglass/sketch/api.py
artboards
python
def artboards(src_path): ''' Return artboards as a flat list ''' pages = list_artboards(src_path) artboards = [] for page in pages: artboards.extend(page.artboards) return artboards
Return artboards as a flat list
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/sketch/api.py#L76-L82
[ "def list_artboards(src_path):\n cmd = [SKETCHTOOL, 'list', 'artboards']\n return list_cmd(cmd, src_path)\n" ]
# -*- coding: utf-8 -*- # Default libs import json import logging # Project modules from ..settings import SKETCHTOOL from ..utils import execute, extension from .parse import parse_pages logger = logging.getLogger(__name__) def is_sketchfile(src_path): ''' Returns True if src_path is a sketch file ''' if exten...
Pixelapse/pyglass
pyglass/sketch/api.py
preview
python
def preview(src_path): ''' Generates a preview of src_path as PNG. :returns: A list of preview paths, one for each page. ''' previews = [] for page in list_artboards(src_path): previews.append(page.export()) for artboard in page.artboards: previews.append(artboard.export()) return previews
Generates a preview of src_path as PNG. :returns: A list of preview paths, one for each page.
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/sketch/api.py#L88-L97
[ "def list_artboards(src_path):\n cmd = [SKETCHTOOL, 'list', 'artboards']\n return list_cmd(cmd, src_path)\n" ]
# -*- coding: utf-8 -*- # Default libs import json import logging # Project modules from ..settings import SKETCHTOOL from ..utils import execute, extension from .parse import parse_pages logger = logging.getLogger(__name__) def is_sketchfile(src_path): ''' Returns True if src_path is a sketch file ''' if exten...
Pixelapse/pyglass
pyglass/quicklook/api.py
is_valid_preview
python
def is_valid_preview(preview): ''' Verifies that the preview is a valid filetype ''' if not preview: return False if mimetype(preview) not in [ExportMimeType.PNG, ExportMimeType.PDF]: return False return True
Verifies that the preview is a valid filetype
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/quicklook/api.py#L13-L21
[ "def mimetype(path_str):\n ''' Returns the mimetype of the file at path_str. Depends on OS X's `file` util '''\n return execute(['file', '--mime-type', '--brief', path_str]).strip().lower()\n" ]
# -*- coding: utf-8 -*- # Default libs # Installed libs # Project modules from ..models import ExportMimeType from ..pdf import to_pngs from ..utils import mimetype from .export import embedded_preview, generator_preview, thumbnail_preview def preview(src_path): ''' Generates a preview of src_path in the request...
Pixelapse/pyglass
pyglass/quicklook/api.py
preview
python
def preview(src_path): ''' Generates a preview of src_path in the requested format. :returns: A list of preview paths, one for each page. Blank list if unsupported. ''' preview = embedded_preview(src_path) if not is_valid_preview(preview): preview = generator_preview(src_path) if not is_valid_preview(...
Generates a preview of src_path in the requested format. :returns: A list of preview paths, one for each page. Blank list if unsupported.
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/quicklook/api.py#L24-L44
[ "def to_pngs(pdf_path):\n ''' Converts a multi-page pdfs to a list of pngs via the `sips` command\n :returns: A list of converted pngs\n '''\n pdf_list = split_pdf(pdf_path)\n pngs = []\n for pdf in pdf_list:\n pngs.append(to_png(pdf))\n os.remove(pdf) # Clean up\n return pngs\n", "def mimetype(path...
# -*- coding: utf-8 -*- # Default libs # Installed libs # Project modules from ..models import ExportMimeType from ..pdf import to_pngs from ..utils import mimetype from .export import embedded_preview, generator_preview, thumbnail_preview def is_valid_preview(preview): ''' Verifies that the preview is a valid fi...
Pixelapse/pyglass
pyglass/utils.py
execute
python
def execute(cmd): ''' Call cmd and return output. return None if any exception occurs ''' try: return safely_decode(check_output(cmd)) except Exception as e: logger.warn(u'Couldnt execute cmd: %s.\nReason: %s' % (cmd, e)) return None
Call cmd and return output. return None if any exception occurs
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/utils.py#L13-L19
null
# -*- coding: utf-8 -*- # Default libs import logging import os # Library modules from pxprocess import check_output from pyunicode import safely_decode logger = logging.getLogger(__name__) def unicode_or_none(dictionary, key): if dictionary is None or key is None: return None return None if key not in dic...
Pixelapse/pyglass
setup.py
rm_tempdirs
python
def rm_tempdirs(): ''' Remove temporary build folders ''' tempdirs = [Dir.BUILD, Dir.COCOA_BUILD, Dir.LIB] for tempdir in tempdirs: if os.path.exists(tempdir): shutil.rmtree(tempdir, ignore_errors=True)
Remove temporary build folders
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/setup.py#L38-L43
null
#!/usr/bin/env python # System modules import sys import os import shutil import platform from os.path import join # Library modules try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup from distutils.dir_util import copy_tree # Package modules if sys.version_in...
Pixelapse/pyglass
setup.py
lib_list
python
def lib_list(): ''' Returns the contents of 'pyglass/lib' as a list of 'lib/*' items for package_data ''' lib_list = [] for (root, dirs, files) in os.walk(Dir.LIB): for filename in files: root = root.replace('pyglass/', '') lib_list.append(join(root, filename)) return lib_list
Returns the contents of 'pyglass/lib' as a list of 'lib/*' items for package_data
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/setup.py#L51-L58
null
#!/usr/bin/env python # System modules import sys import os import shutil import platform from os.path import join # Library modules try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup from distutils.dir_util import copy_tree # Package modules if sys.version_in...
Pixelapse/pyglass
pyglass/quicklook/models.py
Page
python
def Page(QLExportable): ''' For multi-page files, e.g. if pdf preview ''' def __init__(self, filename, page_id): self.id = page_id super(Page, self).__init__(filename) def export(self, export_format=ExportFormat.PNG): pass
For multi-page files, e.g. if pdf preview
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/quicklook/models.py#L17-L24
null
# -*- coding: utf-8 -*- # Project modules from ..models import Exportable, ExportFormat class QLExportable(Exportable): ''' Base class for any exportable QuickLook item ''' def __init__(self, filename): self.filename = filename super(QLExportable, self).__init__() def __unicode__(self): return u'<...
Pixelapse/pyglass
pyglass/api.py
preview
python
def preview(src_path): ''' Generates a preview of src_path in the requested format. :returns: A list of preview paths, one for each page. ''' previews = [] if sketch.is_sketchfile(src_path): previews = sketch.preview(src_path) if not previews: previews = quicklook.preview(src_path) previews = [...
Generates a preview of src_path in the requested format. :returns: A list of preview paths, one for each page.
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/api.py#L9-L23
[ "def preview(src_path):\n ''' Generates a preview of src_path in the requested format.\n :returns: A list of preview paths, one for each page. Blank list if unsupported.\n '''\n preview = embedded_preview(src_path)\n\n if not is_valid_preview(preview):\n preview = generator_preview(src_path)\n\n if not is_...
# -*- coding: utf-8 -*- # Library modules from pyunicode import safely_decode # Project modules from . import quicklook, sketch
Pixelapse/pyglass
pyglass/settings.py
make_executable
python
def make_executable(path_str): ''' Performs the equivalent of `chmod +x` on the file at path_str. :returns: path_str if success, else None ''' try: mode = os.stat(path_str).st_mode os.chmod(path_str, mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) except Exception as e: print 'Exception: %s' % ...
Performs the equivalent of `chmod +x` on the file at path_str. :returns: path_str if success, else None
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/settings.py#L11-L21
null
# -*- coding: utf-8 -*- # Default libs import os import stat from os.path import dirname, join, abspath curr_dir = dirname(abspath(__file__)) def sketchtool_executable(): make_executable(join(curr_dir, 'lib', 'SketchTool', 'sketchmigrate')) return make_executable(join(curr_dir, 'lib', 'SketchTool', 'sketchtool...
Pixelapse/pyglass
pyglass/pdf/api.py
stitch_pdfs
python
def stitch_pdfs(pdf_list): ''' Merges a series of single page pdfs into one multi-page doc ''' pdf_merger = PdfFileMerger() for pdf in pdf_list: pdf_merger.append(pdf) with NamedTemporaryFile(prefix='pyglass', suffix='.pdf', delete=False) as tempfileobj: dest_path = tempfileobj.name pdf_merger.write...
Merges a series of single page pdfs into one multi-page doc
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/pdf/api.py#L16-L27
null
# -*- coding: utf-8 -*- # Default libs import os from tempfile import NamedTemporaryFile from os.path import exists # Library modules from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter from pxprocess import check_call ############################################################ # PDF CLASSES ###########...
Pixelapse/pyglass
pyglass/pdf/api.py
split_pdf
python
def split_pdf(pdf_path): ''' Splits a multi-page pdf into a list of single page pdfs ''' pdf = PdfFileReader(pdf_path) pdf_list = [] for page_num in range(pdf.numPages): page = pdf.getPage(page_num) pdf_writer = PdfFileWriter() pdf_writer.addPage(page) with NamedTemporaryFile(prefix='pyglass'...
Splits a multi-page pdf into a list of single page pdfs
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/pdf/api.py#L30-L47
null
# -*- coding: utf-8 -*- # Default libs import os from tempfile import NamedTemporaryFile from os.path import exists # Library modules from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter from pxprocess import check_call ############################################################ # PDF CLASSES ###########...
Pixelapse/pyglass
pyglass/pdf/api.py
to_png
python
def to_png(pdf_path): ''' Converts a single-page pdf to a png image via the `sips` command :returns: Path to the converted png ''' try: with NamedTemporaryFile(prefix='pyglass', suffix='.png', delete=False) as tempfileobj: png_path = tempfileobj.name cmd = ['sips', '-s', 'format', 'png', pdf_path...
Converts a single-page pdf to a png image via the `sips` command :returns: Path to the converted png
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/pdf/api.py#L50-L64
null
# -*- coding: utf-8 -*- # Default libs import os from tempfile import NamedTemporaryFile from os.path import exists # Library modules from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter from pxprocess import check_call ############################################################ # PDF CLASSES ###########...
Pixelapse/pyglass
pyglass/pdf/api.py
to_pngs
python
def to_pngs(pdf_path): ''' Converts a multi-page pdfs to a list of pngs via the `sips` command :returns: A list of converted pngs ''' pdf_list = split_pdf(pdf_path) pngs = [] for pdf in pdf_list: pngs.append(to_png(pdf)) os.remove(pdf) # Clean up return pngs
Converts a multi-page pdfs to a list of pngs via the `sips` command :returns: A list of converted pngs
train
https://github.com/Pixelapse/pyglass/blob/83cd0ff2b0b7cdaf4ec6f54559a626e67455cd33/pyglass/pdf/api.py#L67-L76
[ "def split_pdf(pdf_path):\n ''' Splits a multi-page pdf into a list of single page pdfs '''\n pdf = PdfFileReader(pdf_path)\n pdf_list = []\n\n for page_num in range(pdf.numPages):\n page = pdf.getPage(page_num)\n\n pdf_writer = PdfFileWriter()\n pdf_writer.addPage(page)\n\n with NamedTemporaryFile(...
# -*- coding: utf-8 -*- # Default libs import os from tempfile import NamedTemporaryFile from os.path import exists # Library modules from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter from pxprocess import check_call ############################################################ # PDF CLASSES ###########...
misli/django-cms-articles
cms_articles/templatetags/cms_articles.py
_get_article_by_untyped_arg
python
def _get_article_by_untyped_arg(article_lookup, request, site_id): if article_lookup is None: return request.current_article if isinstance(article_lookup, Article): if hasattr(request, 'current_article') and request.current_article.pk == article_lookup.pk: return request.current_arti...
The `article_lookup` argument can be of any of the following types: - Integer: interpreted as `pk` of the desired article - `dict`: a dictionary containing keyword arguments to find the desired article (for instance: `{'pk': 1}`) - `Article`: you can also pass an Article object directly, in which case t...
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/templatetags/cms_articles.py#L30-L83
null
# -*- coding: utf-8 -*- from classytags.arguments import Argument, MultiValueArgument from classytags.core import Options, Tag from classytags.helpers import AsTag from cms.exceptions import PlaceholderNotFound from cms.templatetags.cms_tags import DeclaredPlaceholder, PlaceholderOptions from cms.toolbar.utils import ...
misli/django-cms-articles
cms_articles/search_indexes.py
TitleIndex.get_article_placeholders
python
def get_article_placeholders(self, article): placeholders_search_list = getattr(settings, 'CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST', {}) included = placeholders_search_list.get('include', []) excluded = placeholders_search_list.get('exclude', []) diff = set(included) - set(excluded) ...
In the project settings set up the variable CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST = { 'include': [ 'slot1', 'slot2', etc. ], 'exclude': [ 'slot3', 'slot4', etc. ], } or leave it empty CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST = {}
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/search_indexes.py#L46-L69
null
class TitleIndex(get_index_base()): index_title = True object_actions = ('publish', 'unpublish') haystack_use_for_indexing = settings.CMS_ARTICLES_USE_HAYSTACK def prepare_pub_date(self, obj): return obj.article.publication_date def prepare_login_required(self, obj): return obj.ar...
misli/django-cms-articles
cms_articles/utils/article.py
get_article_from_slug
python
def get_article_from_slug(tree, slug, preview=False, draft=False): from ..models import Title titles = Title.objects.select_related('article').filter(article__tree=tree) published_only = (not draft and not preview) if draft: titles = titles.filter(publisher_is_draft=True) elif preview: ...
Resolves a slug to a single article object. Returns None if article does not exist
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/utils/article.py#L7-L31
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals from cms.utils.page import _page_is_published
misli/django-cms-articles
cms_articles/models/managers.py
ArticleManager.search
python
def search(self, q, language=None, current_site_only=True): from cms.plugin_pool import plugin_pool qs = self.get_queryset() qs = qs.public() if current_site_only: site = Site.objects.get_current() qs = qs.filter(tree__site=site) qt = Q(title_set__title...
Simple search function Plugins can define a 'search_fields' tuple similar to ModelAdmin classes
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/models/managers.py#L19-L60
null
class ArticleManager(PublisherManager): """Use draft() and public() methods for accessing the corresponding instances. """ def get_queryset(self): """Change standard model queryset to our own. """ return ArticleQuerySet(self.model)
misli/django-cms-articles
cms_articles/models/managers.py
TitleManager.get_title
python
def get_title(self, article, language, language_fallback=False): try: title = self.get(language=language, article=article) return title except self.model.DoesNotExist: if language_fallback: try: titles = self.filter(article=article)...
Gets the latest content for a particular article and language. Falls back to another language if wanted.
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/models/managers.py#L64-L86
null
class TitleManager(PublisherManager): # created new public method to meet test case requirement and to get a list of titles for published articles def public(self): return self.get_queryset().filter(publisher_is_draft=False, published=True) def drafts(self): return self.get_queryset().fil...
misli/django-cms-articles
cms_articles/models/managers.py
TitleManager.set_or_create
python
def set_or_create(self, request, article, form, language): base_fields = [ 'slug', 'title', 'description', 'meta_description', 'page_title', 'menu_title', 'image', ] cleaned_data = form.cleaned_data try: ...
set or create a title for a particular article and language
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/models/managers.py#L95-L124
null
class TitleManager(PublisherManager): def get_title(self, article, language, language_fallback=False): """ Gets the latest content for a particular article and language. Falls back to another language if wanted. """ try: title = self.get(language=language, article...
misli/django-cms-articles
cms_articles/article_rendering.py
render_article
python
def render_article(request, article, current_language, slug): context = {} context['article'] = article context['lang'] = current_language context['current_article'] = article context['has_change_permissions'] = article.has_change_permission(request) response = TemplateResponse(request, article...
Renders an article
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/article_rendering.py#L7-L38
null
# -*- coding: utf-8 -*- from cms.cache.page import set_page_cache from cms.models import Page from django.template.response import TemplateResponse
misli/django-cms-articles
cms_articles/views.py
article
python
def article(request, slug): # Get current CMS Page as article tree tree = request.current_page.get_public_object() # Check whether it really is a tree. # It could also be one of its sub-pages. if tree.application_urls != 'CMSArticlesApp': # In such case show regular CMS Page return ...
The main view of the Django-CMS Articles! Takes a request and a slug, renders the article.
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/views.py#L20-L120
[ "def get_article_from_slug(tree, slug, preview=False, draft=False):\n \"\"\"\n Resolves a slug to a single article object.\n Returns None if article does not exist\n \"\"\"\n from ..models import Title\n\n titles = Title.objects.select_related('article').filter(article__tree=tree)\n published_o...
from cms.exceptions import LanguageError from cms.page_rendering import _handle_no_page, render_object_structure from cms.utils.conf import get_cms_setting from cms.utils.i18n import ( get_default_language_for_site, get_fallback_languages, get_language_list, get_public_languages, get_redirect_on_fallback, ) fro...
misli/django-cms-articles
cms_articles/utils/__init__.py
is_valid_article_slug
python
def is_valid_article_slug(article, language, slug): from ..models import Title qs = Title.objects.filter(slug=slug, language=language) if article.pk: qs = qs.exclude(Q(language=language) & Q(article=article)) qs = qs.exclude(article__publisher_public=article) if qs.count(): re...
Validates given slug depending on settings.
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/utils/__init__.py#L4-L18
null
from django.db.models import Q
misli/django-cms-articles
cms_articles/admin/article.py
ArticleAdmin.get_urls
python
def get_urls(self): info = '%s_%s' % (self.model._meta.app_label, self.model._meta.model_name) def pat(regex, fn): return url(regex, self.admin_site.admin_view(fn), name='%s_%s' % (info, fn.__name__)) url_patterns = [ pat(r'^([0-9]+)/delete-translation/$', self.delete_t...
Get the admin urls
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/admin/article.py#L102-L118
[ "def pat(regex, fn):\n return url(regex, self.admin_site.admin_view(fn), name='%s_%s' % (info, fn.__name__))\n" ]
class ArticleAdmin(PlaceholderAdminMixin, admin.ModelAdmin): change_list_template = 'admin/cms_articles/article_changelist.html' search_fields = ('=id', 'title_set__slug', 'title_set__title', 'title_set__description') list_display = ('__str__', 'order_date', 'preview_link') + tuple( 'lang_{}'.format...
misli/django-cms-articles
cms_articles/admin/article.py
ArticleAdmin.get_form
python
def get_form(self, request, obj=None, **kwargs): language = get_language_from_request(request) form = super(ArticleAdmin, self).get_form( request, obj, form=(obj and ArticleForm or ArticleCreateForm), **kwargs ) # get_form method operates by overriding...
Get ArticleForm for the Article model and modify its fields depending on the request.
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/admin/article.py#L140-L175
null
class ArticleAdmin(PlaceholderAdminMixin, admin.ModelAdmin): change_list_template = 'admin/cms_articles/article_changelist.html' search_fields = ('=id', 'title_set__slug', 'title_set__title', 'title_set__description') list_display = ('__str__', 'order_date', 'preview_link') + tuple( 'lang_{}'.format...
misli/django-cms-articles
cms_articles/admin/article.py
ArticleAdmin.unpublish
python
def unpublish(self, request, article_id, language): article = get_object_or_404(self.model, pk=article_id) if not article.has_publish_permission(request): return HttpResponseForbidden(force_text(_('You do not have permission to unpublish this article'))) if not article.publisher_publ...
Publish or unpublish a language of a article
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/admin/article.py#L306-L341
null
class ArticleAdmin(PlaceholderAdminMixin, admin.ModelAdmin): change_list_template = 'admin/cms_articles/article_changelist.html' search_fields = ('=id', 'title_set__slug', 'title_set__title', 'title_set__description') list_display = ('__str__', 'order_date', 'preview_link') + tuple( 'lang_{}'.format...
misli/django-cms-articles
cms_articles/admin/article.py
ArticleAdmin.preview_article
python
def preview_article(self, request, object_id, language): article = get_object_or_404(self.model, id=object_id) attrs = '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') attrs += '&language=' + language with force_language(language): url = article.get_absolute_url(language) ...
Redirecting preview function based on draft_id
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/admin/article.py#L439-L447
null
class ArticleAdmin(PlaceholderAdminMixin, admin.ModelAdmin): change_list_template = 'admin/cms_articles/article_changelist.html' search_fields = ('=id', 'title_set__slug', 'title_set__title', 'title_set__description') list_display = ('__str__', 'order_date', 'preview_link') + tuple( 'lang_{}'.format...
misli/django-cms-articles
cms_articles/signals/title.py
pre_save_title
python
def pre_save_title(instance, **kwargs): ''' Update article.languages ''' if instance.article.languages: languages = instance.article.languages.split(',') else: languages = [] if instance.language not in languages: languages.append(instance.language) instance.article.l...
Update article.languages
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/signals/title.py#L1-L12
null
def pre_delete_title(instance, **kwargs): ''' Update article.languages ''' if instance.article.languages: languages = instance.article.languages.split(',') else: languages = [] if instance.language in languages: languages.remove(instance.language) instance.article...
misli/django-cms-articles
cms_articles/signals/title.py
pre_delete_title
python
def pre_delete_title(instance, **kwargs): ''' Update article.languages ''' if instance.article.languages: languages = instance.article.languages.split(',') else: languages = [] if instance.language in languages: languages.remove(instance.language) instance.article.lan...
Update article.languages
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/signals/title.py#L15-L26
null
def pre_save_title(instance, **kwargs): ''' Update article.languages ''' if instance.article.languages: languages = instance.article.languages.split(',') else: languages = [] if instance.language not in languages: languages.append(instance.language) instance.article.l...
misli/django-cms-articles
cms_articles/api.py
create_article
python
def create_article(tree, template, title, language, slug=None, description=None, page_title=None, menu_title=None, meta_description=None, created_by=None, image=None, publication_date=None, publication_end_date=None, published=False, login_required=False, creatio...
Create a CMS Article and it's title for the given language
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/api.py#L26-L100
[ "def create_title(article, language, title, slug=None, description=None,\n page_title=None, menu_title=None, meta_description=None,\n creation_date=None, image=None):\n \"\"\"\n Create an article title.\n \"\"\"\n # validate article\n assert isinstance(article, Article...
import datetime from cms.api import add_plugin from cms.utils.i18n import get_language_list from cms.utils.permissions import current_user from django.template.defaultfilters import slugify from django.template.loader import get_template from django.utils.encoding import force_text from django.utils.timezone import no...
misli/django-cms-articles
cms_articles/api.py
create_title
python
def create_title(article, language, title, slug=None, description=None, page_title=None, menu_title=None, meta_description=None, creation_date=None, image=None): # validate article assert isinstance(article, Article) # validate language: assert language in get_language...
Create an article title.
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/api.py#L103-L148
null
import datetime from cms.api import add_plugin from cms.utils.i18n import get_language_list from cms.utils.permissions import current_user from django.template.defaultfilters import slugify from django.template.loader import get_template from django.utils.encoding import force_text from django.utils.timezone import no...
misli/django-cms-articles
cms_articles/api.py
add_content
python
def add_content(obj, language, slot, content): placeholder = obj.placeholders.get(slot=slot) add_plugin(placeholder, TextPlugin, language, body=content)
Adds a TextPlugin with given content to given slot
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/api.py#L151-L156
null
import datetime from cms.api import add_plugin from cms.utils.i18n import get_language_list from cms.utils.permissions import current_user from django.template.defaultfilters import slugify from django.template.loader import get_template from django.utils.encoding import force_text from django.utils.timezone import no...
misli/django-cms-articles
cms_articles/api.py
publish_article
python
def publish_article(article, language, changed_by=None): article = article.reload() # get username if changed_by: username = changed_by.get_username() else: username = 'script' with current_user(username): article.publish(language) return article.reload()
Publish an article. This sets `article.published` to `True` and calls article.publish() which does the actual publishing.
train
https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/api.py#L159-L175
null
import datetime from cms.api import add_plugin from cms.utils.i18n import get_language_list from cms.utils.permissions import current_user from django.template.defaultfilters import slugify from django.template.loader import get_template from django.utils.encoding import force_text from django.utils.timezone import no...
epio/mantrid
mantrid/socketmeld.py
SocketMelder.piper
python
def piper(self, in_sock, out_sock, out_addr, onkill): "Worker thread for data reading" try: while True: written = in_sock.recv(32768) if not written: try: out_sock.shutdown(socket.SHUT_WR) except ...
Worker thread for data reading
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/socketmeld.py#L16-L33
null
class SocketMelder(object): """ Takes two sockets and directly connects them together. """ def __init__(self, client, server): self.client = client self.server = server self.data_handled = 0 def run(self): self.threads = { "ctos": eventlet.spawn(self.pi...
epio/mantrid
mantrid/management.py
ManagementApp.handle
python
def handle(self, environ, start_response): "Main entry point" # Pass off to the router try: handler = self.route( environ['PATH_INFO'].lower(), environ['REQUEST_METHOD'].lower(), ) if handler is None: raise HttpN...
Main entry point
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/management.py#L33-L60
[ "def route(self, path, method):\n # Simple routing for paths\n if path == \"/\":\n raise HttpMethodNotAllowed()\n elif path == \"/stats/\":\n if method == \"get\":\n return self.get_all_stats\n else:\n raise HttpMethodNotAllowed()\n elif self.stats_host_regex.m...
class ManagementApp(object): """ Management WSGI app for the Mantrid loadbalancer. Allows endpoints to be changed via HTTP requests to the management port. """ host_regex = re.compile(r"^/hostname/([^/]+)/?$") stats_host_regex = re.compile(r"^/stats/([^/]+)/?$") def __init__(self, bala...
epio/mantrid
mantrid/management.py
ManagementApp.host_errors
python
def host_errors(self, hostname, details): if not hostname or not isinstance(hostname, basestring): return "hostname_invalid" if not isinstance(details, list): return "host_details_not_list" if len(details) != 3: return "host_details_wrong_length" if de...
Validates the format of a host entry Returns an error string, or None if it is valid.
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/management.py#L97-L114
null
class ManagementApp(object): """ Management WSGI app for the Mantrid loadbalancer. Allows endpoints to be changed via HTTP requests to the management port. """ host_regex = re.compile(r"^/hostname/([^/]+)/?$") stats_host_regex = re.compile(r"^/stats/([^/]+)/?$") def __init__(self, bala...
epio/mantrid
mantrid/management.py
ManagementApp.set_all
python
def set_all(self, path, body): "Replaces the hosts list with the provided input" # Do some error checking if not isinstance(body, dict): raise HttpBadRequest("body_not_a_dict") for hostname, details in body.items(): error = self.host_errors(hostname, details) ...
Replaces the hosts list with the provided input
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/management.py#L119-L140
[ "def host_errors(self, hostname, details):\n \"\"\"\n Validates the format of a host entry\n Returns an error string, or None if it is valid.\n \"\"\"\n if not hostname or not isinstance(hostname, basestring):\n return \"hostname_invalid\"\n if not isinstance(details, list):\n return...
class ManagementApp(object): """ Management WSGI app for the Mantrid loadbalancer. Allows endpoints to be changed via HTTP requests to the management port. """ host_regex = re.compile(r"^/hostname/([^/]+)/?$") stats_host_regex = re.compile(r"^/stats/([^/]+)/?$") def __init__(self, bala...
epio/mantrid
mantrid/cli.py
MantridCli.action_list
python
def action_list(self): "Lists all hosts on the LB" format = "%-35s %-25s %-8s" print format % ("HOST", "ACTION", "SUBDOMS") for host, details in sorted(self.client.get_all().items()): if details[0] in ("proxy", "mirror"): action = "%s<%s>" % ( ...
Lists all hosts on the LB
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/cli.py#L44-L74
null
class MantridCli(object): """Command line interface to Mantrid""" def __init__(self, base_url): self.client = MantridClient(base_url) @classmethod def main(cls): cli = cls("http://localhost:8042") cli.run(sys.argv) @property def action_names(self): for method_n...
epio/mantrid
mantrid/cli.py
MantridCli.action_set
python
def action_set(self, hostname=None, action=None, subdoms=None, *args): "Adds a hostname to the LB, or alters an existing one" usage = "set <hostname> <action> <subdoms> [option=value, ...]" if hostname is None: sys.stderr.write("You must supply a hostname.\n") sys.stderr....
Adds a hostname to the LB, or alters an existing one
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/cli.py#L76-L124
null
class MantridCli(object): """Command line interface to Mantrid""" def __init__(self, base_url): self.client = MantridClient(base_url) @classmethod def main(cls): cli = cls("http://localhost:8042") cli.run(sys.argv) @property def action_names(self): for method_n...
epio/mantrid
mantrid/cli.py
MantridCli.action_stats
python
def action_stats(self, hostname=None): "Shows stats (possibly limited by hostname)" format = "%-35s %-11s %-11s %-11s %-11s" print format % ("HOST", "OPEN", "COMPLETED", "BYTES IN", "BYTES OUT") for host, details in sorted(self.client.stats(hostname).items()): print format % ...
Shows stats (possibly limited by hostname)
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/cli.py#L132-L143
null
class MantridCli(object): """Command line interface to Mantrid""" def __init__(self, base_url): self.client = MantridClient(base_url) @classmethod def main(cls): cli = cls("http://localhost:8042") cli.run(sys.argv) @property def action_names(self): for method_n...
epio/mantrid
mantrid/loadbalancer.py
Balancer.load
python
def load(self): "Loads the state from the state file" try: if os.path.getsize(self.state_file) <= 1: raise IOError("File is empty.") with open(self.state_file) as fh: state = json.load(fh) assert isinstance(state, dict) ...
Loads the state from the state file
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/loadbalancer.py#L100-L115
null
class Balancer(object): """ Main loadbalancer class. """ nofile = 102400 save_interval = 10 action_mapping = { "proxy": Proxy, "empty": Empty, "static": Static, "redirect": Redirect, "unknown": Unknown, "spin": Spin, "no_hosts": NoHosts, ...
epio/mantrid
mantrid/loadbalancer.py
Balancer.save
python
def save(self): "Saves the state to the state file" with open(self.state_file, "w") as fh: json.dump({ "hosts": self.hosts, "stats": self.stats, }, fh)
Saves the state to the state file
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/loadbalancer.py#L117-L123
null
class Balancer(object): """ Main loadbalancer class. """ nofile = 102400 save_interval = 10 action_mapping = { "proxy": Proxy, "empty": Empty, "static": Static, "redirect": Redirect, "unknown": Unknown, "spin": Spin, "no_hosts": NoHosts, ...
epio/mantrid
mantrid/loadbalancer.py
Balancer.save_loop
python
def save_loop(self): last_hash = hash(repr(self.hosts)) while self.running: eventlet.sleep(self.save_interval) next_hash = hash(repr(self.hosts)) if next_hash != last_hash: self.save() last_hash = next_hash
Saves the state if it has changed.
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/loadbalancer.py#L195-L205
[ "def save(self):\n \"Saves the state to the state file\"\n with open(self.state_file, \"w\") as fh:\n json.dump({\n \"hosts\": self.hosts,\n \"stats\": self.stats,\n }, fh)\n" ]
class Balancer(object): """ Main loadbalancer class. """ nofile = 102400 save_interval = 10 action_mapping = { "proxy": Proxy, "empty": Empty, "static": Static, "redirect": Redirect, "unknown": Unknown, "spin": Spin, "no_hosts": NoHosts, ...
epio/mantrid
mantrid/loadbalancer.py
Balancer.management_loop
python
def management_loop(self, address, family): try: sock = eventlet.listen(address, family) except socket.error, e: logging.critical("Cannot listen on (%s, %s): %s" % (address, family, e)) return # Sleep to ensure we've dropped privileges by the time we start ser...
Accepts management requests.
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/loadbalancer.py#L207-L229
null
class Balancer(object): """ Main loadbalancer class. """ nofile = 102400 save_interval = 10 action_mapping = { "proxy": Proxy, "empty": Empty, "static": Static, "redirect": Redirect, "unknown": Unknown, "spin": Spin, "no_hosts": NoHosts, ...
epio/mantrid
mantrid/loadbalancer.py
Balancer.listen_loop
python
def listen_loop(self, address, family, internal=False): try: sock = eventlet.listen(address, family) except socket.error, e: if e.errno == errno.EADDRINUSE: logging.critical("Cannot listen on (%s, %s): already in use" % (address, family)) raise ...
Accepts incoming connections.
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/loadbalancer.py#L233-L259
null
class Balancer(object): """ Main loadbalancer class. """ nofile = 102400 save_interval = 10 action_mapping = { "proxy": Proxy, "empty": Empty, "static": Static, "redirect": Redirect, "unknown": Unknown, "spin": Spin, "no_hosts": NoHosts, ...
epio/mantrid
mantrid/loadbalancer.py
Balancer.handle
python
def handle(self, sock, address, internal=False): try: sock = StatsSocket(sock) rfile = sock.makefile('rb', 4096) # Read the first line first = rfile.readline().strip("\r\n") words = first.split() # Ensure it looks kind of like HTTP ...
Handles an incoming HTTP connection.
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/loadbalancer.py#L282-L350
[ "def resolve_host(self, host, protocol=\"http\"):\n # Special case for empty hosts dict\n if not self.hosts:\n return NoHosts(self, host, \"unknown\")\n # Check for an exact or any subdomain matches\n bits = host.split(\".\")\n for i in range(len(bits)):\n for prefix in [\"%s://\" % pro...
class Balancer(object): """ Main loadbalancer class. """ nofile = 102400 save_interval = 10 action_mapping = { "proxy": Proxy, "empty": Empty, "static": Static, "redirect": Redirect, "unknown": Unknown, "spin": Spin, "no_hosts": NoHosts, ...
epio/mantrid
mantrid/client.py
MantridClient._request
python
def _request(self, path, method, body=None): "Base request function" h = httplib2.Http() resp, content = h.request( self.base_url + path, method, body = json.dumps(body), ) if resp['status'] == "200": return json.loads(content) ...
Base request function
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/client.py#L17-L33
null
class MantridClient(object): """ Class encapsulating Mantrid client operations. """ def __init__(self, base_url): self.base_url = base_url.rstrip("/") def get_all(self): "Returns all endpoints" return self._request("/hostname/", "GET") def set_all(self, data): ...
epio/mantrid
mantrid/actions.py
Empty.handle
python
def handle(self, sock, read_data, path, headers): "Sends back a static error page." try: sock.sendall("HTTP/1.0 %s %s\r\nConnection: close\r\nContent-length: 0\r\n\r\n" % (self.code, responses.get(self.code, "Unknown"))) except socket.error, e: if e.errno != errno.EPIPE: ...
Sends back a static error page.
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/actions.py#L35-L41
[ "def sendall(self, data):\n self.data += data\n" ]
class Empty(Action): "Sends a code-only HTTP response" code = None def __init__(self, balancer, host, matched_host, code): super(Empty, self).__init__(balancer, host, matched_host) self.code = code
epio/mantrid
mantrid/actions.py
Static.handle
python
def handle(self, sock, read_data, path, headers): "Sends back a static error page." assert self.type is not None try: # Get the correct file try: fh = open(os.path.join(self.balancer.static_dir, "%s.http" % self.type)) except IOError: ...
Sends back a static error page.
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/actions.py#L63-L82
[ "def sendall(self, data):\n self.data += data\n", "def close(self):\n pass\n" ]
class Static(Action): "Sends a static HTTP response" type = None def __init__(self, balancer, host, matched_host, type=None): super(Static, self).__init__(balancer, host, matched_host) if type is not None: self.type = type # Try to get sendfile() using ctypes; otherwise, f...
epio/mantrid
mantrid/actions.py
Redirect.handle
python
def handle(self, sock, read_data, path, headers): "Sends back a static error page." if "://" not in self.redirect_to: destination = "http%s://%s" % ( "s" if headers.get('X-Forwarded-Protocol', headers.get('X-Forwarded-Proto', "")).lower() in ("https", "ssl") else "", ...
Sends back a static error page.
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/actions.py#L106-L122
[ "def sendall(self, data):\n self.data += data\n" ]
class Redirect(Action): "Sends a redirect" type = None def __init__(self, balancer, host, matched_host, redirect_to): super(Redirect, self).__init__(balancer, host, matched_host) self.redirect_to = redirect_to
epio/mantrid
mantrid/actions.py
Proxy.handle
python
def handle(self, sock, read_data, path, headers): "Sends back a static error page." for i in range(self.attempts): try: server_sock = eventlet.connect( tuple(random.choice(self.backends)), ) except socket.error: ...
Sends back a static error page.
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/actions.py#L140-L159
[ "def run(self):\n self.threads = {\n \"ctos\": eventlet.spawn(self.piper, self.server, self.client, \"client\", \"stoc\"),\n \"stoc\": eventlet.spawn(self.piper, self.client, self.server, \"server\", \"ctos\"),\n }\n try:\n self.threads['stoc'].wait()\n except (greenlet.GreenletExit...
class Proxy(Action): "Proxies them through to a server. What loadbalancers do." attempts = 1 delay = 1 def __init__(self, balancer, host, matched_host, backends, attempts=None, delay=None): super(Proxy, self).__init__(balancer, host, matched_host) self.backends = backends asser...
epio/mantrid
mantrid/actions.py
Spin.handle
python
def handle(self, sock, read_data, path, headers): "Just waits, and checks for other actions to replace us" for i in range(self.timeout // self.check_interval): # Sleep first eventlet.sleep(self.check_interval) # Check for another action action = self.balan...
Just waits, and checks for other actions to replace us
train
https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/actions.py#L178-L189
[ "def handle(self, sock, read_data, path, headers):\n \"Sends back a static error page.\"\n assert self.type is not None\n try:\n # Get the correct file\n try:\n fh = open(os.path.join(self.balancer.static_dir, \"%s.http\" % self.type))\n except IOError:\n fh = ope...
class Spin(Action): """ Just holds the request open until either the timeout expires, or another action becomes available. """ timeout = 120 check_interval = 1 def __init__(self, balancer, host, matched_host, timeout=None, check_interval=None): super(Spin, self).__init__(balancer, ...