repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictProvider.get_connection
def get_connection(self): """Return the dictionary database object """ database = { 'data': _databases.setdefault(self.identifier, defaultdict(dict)), 'lock': _locks.setdefault(self.identifier, Lock()), 'counters': _counters } return database
python
def get_connection(self): """Return the dictionary database object """ database = { 'data': _databases.setdefault(self.identifier, defaultdict(dict)), 'lock': _locks.setdefault(self.identifier, Lock()), 'counters': _counters } return database
[ "def", "get_connection", "(", "self", ")", ":", "database", "=", "{", "'data'", ":", "_databases", ".", "setdefault", "(", "self", ".", "identifier", ",", "defaultdict", "(", "dict", ")", ")", ",", "'lock'", ":", "_locks", ".", "setdefault", "(", "self",...
Return the dictionary database object
[ "Return", "the", "dictionary", "database", "object" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L54-L61
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictProvider.get_repository
def get_repository(self, entity_cls): """Return a repository object configured with a live connection""" model_cls = self.get_model(entity_cls) return DictRepository(self, entity_cls, model_cls)
python
def get_repository(self, entity_cls): """Return a repository object configured with a live connection""" model_cls = self.get_model(entity_cls) return DictRepository(self, entity_cls, model_cls)
[ "def", "get_repository", "(", "self", ",", "entity_cls", ")", ":", "model_cls", "=", "self", ".", "get_model", "(", "entity_cls", ")", "return", "DictRepository", "(", "self", ",", "entity_cls", ",", "model_cls", ")" ]
Return a repository object configured with a live connection
[ "Return", "a", "repository", "object", "configured", "with", "a", "live", "connection" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L74-L77
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictProvider._evaluate_lookup
def _evaluate_lookup(self, key, value, negated, db): """Extract values from DB that match the given criteria""" results = {} for record_key, record_value in db.items(): match = True stripped_key, lookup_class = self._extract_lookup(key) lookup = lookup_class(...
python
def _evaluate_lookup(self, key, value, negated, db): """Extract values from DB that match the given criteria""" results = {} for record_key, record_value in db.items(): match = True stripped_key, lookup_class = self._extract_lookup(key) lookup = lookup_class(...
[ "def", "_evaluate_lookup", "(", "self", ",", "key", ",", "value", ",", "negated", ",", "db", ")", ":", "results", "=", "{", "}", "for", "record_key", ",", "record_value", "in", "db", ".", "items", "(", ")", ":", "match", "=", "True", "stripped_key", ...
Extract values from DB that match the given criteria
[ "Extract", "values", "from", "DB", "that", "match", "the", "given", "criteria" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L79-L96
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictProvider.raw
def raw(self, query: Any, data: Any = None): """Run raw queries on the database As an example of running ``raw`` queries on a Dict repository, we will run the query on all possible schemas, and return all results. """ assert isinstance(query, str) conn = self.get_connec...
python
def raw(self, query: Any, data: Any = None): """Run raw queries on the database As an example of running ``raw`` queries on a Dict repository, we will run the query on all possible schemas, and return all results. """ assert isinstance(query, str) conn = self.get_connec...
[ "def", "raw", "(", "self", ",", "query", ":", "Any", ",", "data", ":", "Any", "=", "None", ")", ":", "assert", "isinstance", "(", "query", ",", "str", ")", "conn", "=", "self", ".", "get_connection", "(", ")", "items", "=", "[", "]", "for", "sche...
Run raw queries on the database As an example of running ``raw`` queries on a Dict repository, we will run the query on all possible schemas, and return all results.
[ "Run", "raw", "queries", "on", "the", "database" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L98-L128
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictRepository._set_auto_fields
def _set_auto_fields(self, model_obj): """Set the values of the auto field using counter""" for field_name, field_obj in \ self.entity_cls.meta_.auto_fields: counter_key = f'{self.schema_name}_{field_name}' if not (field_name in model_obj and model_obj[field_name]...
python
def _set_auto_fields(self, model_obj): """Set the values of the auto field using counter""" for field_name, field_obj in \ self.entity_cls.meta_.auto_fields: counter_key = f'{self.schema_name}_{field_name}' if not (field_name in model_obj and model_obj[field_name]...
[ "def", "_set_auto_fields", "(", "self", ",", "model_obj", ")", ":", "for", "field_name", ",", "field_obj", "in", "self", ".", "entity_cls", ".", "meta_", ".", "auto_fields", ":", "counter_key", "=", "f'{self.schema_name}_{field_name}'", "if", "not", "(", "field_...
Set the values of the auto field using counter
[ "Set", "the", "values", "of", "the", "auto", "field", "using", "counter" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L134-L146
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictRepository.create
def create(self, model_obj): """Write a record to the dict repository""" # Update the value of the counters model_obj = self._set_auto_fields(model_obj) # Add the entity to the repository identifier = model_obj[self.entity_cls.meta_.id_field.field_name] with self.conn['l...
python
def create(self, model_obj): """Write a record to the dict repository""" # Update the value of the counters model_obj = self._set_auto_fields(model_obj) # Add the entity to the repository identifier = model_obj[self.entity_cls.meta_.id_field.field_name] with self.conn['l...
[ "def", "create", "(", "self", ",", "model_obj", ")", ":", "# Update the value of the counters", "model_obj", "=", "self", ".", "_set_auto_fields", "(", "model_obj", ")", "# Add the entity to the repository", "identifier", "=", "model_obj", "[", "self", ".", "entity_cl...
Write a record to the dict repository
[ "Write", "a", "record", "to", "the", "dict", "repository" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L148-L158
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictRepository._filter
def _filter(self, criteria: Q, db): """Recursive function to filter items from dictionary""" # Filter the dictionary objects based on the filters negated = criteria.negated input_db = None if criteria.connector == criteria.AND: # Trim database records over successive...
python
def _filter(self, criteria: Q, db): """Recursive function to filter items from dictionary""" # Filter the dictionary objects based on the filters negated = criteria.negated input_db = None if criteria.connector == criteria.AND: # Trim database records over successive...
[ "def", "_filter", "(", "self", ",", "criteria", ":", "Q", ",", "db", ")", ":", "# Filter the dictionary objects based on the filters", "negated", "=", "criteria", ".", "negated", "input_db", "=", "None", "if", "criteria", ".", "connector", "==", "criteria", ".",...
Recursive function to filter items from dictionary
[ "Recursive", "function", "to", "filter", "items", "from", "dictionary" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L160-L188
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictRepository.filter
def filter(self, criteria: Q, offset: int = 0, limit: int = 10, order_by: list = ()): """Read the repository and return results as per the filer""" if criteria.children: items = list(self._filter(criteria, self.conn['data'][self.schema_name]).values()) else: items = list...
python
def filter(self, criteria: Q, offset: int = 0, limit: int = 10, order_by: list = ()): """Read the repository and return results as per the filer""" if criteria.children: items = list(self._filter(criteria, self.conn['data'][self.schema_name]).values()) else: items = list...
[ "def", "filter", "(", "self", ",", "criteria", ":", "Q", ",", "offset", ":", "int", "=", "0", ",", "limit", ":", "int", "=", "10", ",", "order_by", ":", "list", "=", "(", ")", ")", ":", "if", "criteria", ".", "children", ":", "items", "=", "lis...
Read the repository and return results as per the filer
[ "Read", "the", "repository", "and", "return", "results", "as", "per", "the", "filer" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L190-L211
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictRepository.update
def update(self, model_obj): """Update the entity record in the dictionary """ identifier = model_obj[self.entity_cls.meta_.id_field.field_name] with self.conn['lock']: # Check if object is present if identifier not in self.conn['data'][self.schema_name]: ...
python
def update(self, model_obj): """Update the entity record in the dictionary """ identifier = model_obj[self.entity_cls.meta_.id_field.field_name] with self.conn['lock']: # Check if object is present if identifier not in self.conn['data'][self.schema_name]: ...
[ "def", "update", "(", "self", ",", "model_obj", ")", ":", "identifier", "=", "model_obj", "[", "self", ".", "entity_cls", ".", "meta_", ".", "id_field", ".", "field_name", "]", "with", "self", ".", "conn", "[", "'lock'", "]", ":", "# Check if object is pre...
Update the entity record in the dictionary
[ "Update", "the", "entity", "record", "in", "the", "dictionary" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L213-L224
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictRepository.update_all
def update_all(self, criteria: Q, *args, **kwargs): """Update all objects satisfying the criteria """ items = self._filter(criteria, self.conn['data'][self.schema_name]) update_count = 0 for key in items: item = items[key] item.update(*args) item.upda...
python
def update_all(self, criteria: Q, *args, **kwargs): """Update all objects satisfying the criteria """ items = self._filter(criteria, self.conn['data'][self.schema_name]) update_count = 0 for key in items: item = items[key] item.update(*args) item.upda...
[ "def", "update_all", "(", "self", ",", "criteria", ":", "Q", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "items", "=", "self", ".", "_filter", "(", "criteria", ",", "self", ".", "conn", "[", "'data'", "]", "[", "self", ".", "schema_name", ...
Update all objects satisfying the criteria
[ "Update", "all", "objects", "satisfying", "the", "criteria" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L226-L239
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictRepository.delete_all
def delete_all(self, criteria: Q = None): """Delete the dictionary object by its criteria""" if criteria: # Delete the object from the dictionary and return the deletion count items = self._filter(criteria, self.conn['data'][self.schema_name]) # Delete all the matchi...
python
def delete_all(self, criteria: Q = None): """Delete the dictionary object by its criteria""" if criteria: # Delete the object from the dictionary and return the deletion count items = self._filter(criteria, self.conn['data'][self.schema_name]) # Delete all the matchi...
[ "def", "delete_all", "(", "self", ",", "criteria", ":", "Q", "=", "None", ")", ":", "if", "criteria", ":", "# Delete the object from the dictionary and return the deletion count", "items", "=", "self", ".", "_filter", "(", "criteria", ",", "self", ".", "conn", "...
Delete the dictionary object by its criteria
[ "Delete", "the", "dictionary", "object", "by", "its", "criteria" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L254-L269
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictRepository.raw
def raw(self, query: Any, data: Any = None): """Run raw query on Repository. For this stand-in repository, the query string is a json string that contains kwargs criteria with straigh-forward equality checks. Individual criteria are always ANDed and the result is always a subset of the ...
python
def raw(self, query: Any, data: Any = None): """Run raw query on Repository. For this stand-in repository, the query string is a json string that contains kwargs criteria with straigh-forward equality checks. Individual criteria are always ANDed and the result is always a subset of the ...
[ "def", "raw", "(", "self", ",", "query", ":", "Any", ",", "data", ":", "Any", "=", "None", ")", ":", "# Ensure that we are dealing with a string, for this repository", "assert", "isinstance", "(", "query", ",", "str", ")", "input_db", "=", "self", ".", "conn",...
Run raw query on Repository. For this stand-in repository, the query string is a json string that contains kwargs criteria with straigh-forward equality checks. Individual criteria are always ANDed and the result is always a subset of the full repository. We will ignore the `data` para...
[ "Run", "raw", "query", "on", "Repository", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L271-L305
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DefaultDictLookup.process_source
def process_source(self): """Return source with transformations, if any""" if isinstance(self.source, str): # Replace single and double quotes with escaped single-quote self.source = self.source.replace("'", "\'").replace('"', "\'") return "\"{source}\"".format(source...
python
def process_source(self): """Return source with transformations, if any""" if isinstance(self.source, str): # Replace single and double quotes with escaped single-quote self.source = self.source.replace("'", "\'").replace('"', "\'") return "\"{source}\"".format(source...
[ "def", "process_source", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "source", ",", "str", ")", ":", "# Replace single and double quotes with escaped single-quote", "self", ".", "source", "=", "self", ".", "source", ".", "replace", "(", "\"'\"",...
Return source with transformations, if any
[ "Return", "source", "with", "transformations", "if", "any" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L323-L329
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DefaultDictLookup.process_target
def process_target(self): """Return target with transformations, if any""" if isinstance(self.target, str): # Replace single and double quotes with escaped single-quote self.target = self.target.replace("'", "\'").replace('"', "\'") return "\"{target}\"".format(target...
python
def process_target(self): """Return target with transformations, if any""" if isinstance(self.target, str): # Replace single and double quotes with escaped single-quote self.target = self.target.replace("'", "\'").replace('"', "\'") return "\"{target}\"".format(target...
[ "def", "process_target", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "target", ",", "str", ")", ":", "# Replace single and double quotes with escaped single-quote", "self", ".", "target", "=", "self", ".", "target", ".", "replace", "(", "\"'\"",...
Return target with transformations, if any
[ "Return", "target", "with", "transformations", "if", "any" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L331-L337
tadashi-aikawa/jumeaux
jumeaux/executor.py
challenge
def challenge(arg: ChallengeArg) -> dict: """ Response is dict like `Trial` because Status(OwlEnum) can't be pickled. """ name: str = arg.req.name.get_or(str(arg.seq)) log_prefix = f"[{arg.seq} / {arg.number_of_request}]" logger.info_lv3(f"{log_prefix} {'-'*80}") logger.info_lv3(f"{log_prefix}...
python
def challenge(arg: ChallengeArg) -> dict: """ Response is dict like `Trial` because Status(OwlEnum) can't be pickled. """ name: str = arg.req.name.get_or(str(arg.seq)) log_prefix = f"[{arg.seq} / {arg.number_of_request}]" logger.info_lv3(f"{log_prefix} {'-'*80}") logger.info_lv3(f"{log_prefix}...
[ "def", "challenge", "(", "arg", ":", "ChallengeArg", ")", "->", "dict", ":", "name", ":", "str", "=", "arg", ".", "req", ".", "name", ".", "get_or", "(", "str", "(", "arg", ".", "seq", ")", ")", "log_prefix", "=", "f\"[{arg.seq} / {arg.number_of_request}...
Response is dict like `Trial` because Status(OwlEnum) can't be pickled.
[ "Response", "is", "dict", "like", "Trial", "because", "Status", "(", "OwlEnum", ")", "can", "t", "be", "pickled", "." ]
train
https://github.com/tadashi-aikawa/jumeaux/blob/23389bde3e9b27b3a646d99289f8b5ced411f6f0/jumeaux/executor.py#L248-L398
wasp/waspy
waspy/transports/rabbitmqtransport.py
parse_url_to_topic
def parse_url_to_topic(method, route): """ Transforms a URL to a topic. `GET /bar/{id}` -> `get.bar.*` `POST /bar/{id}` -> `post.bar.*` `GET /foo/bar/{id}/baz` -? `get.foo.bar.*.baz` Possible gotchas `GET /foo/{id}` -> `get.foo.*` `GET /foo/{id}:action` -> `get.foo.*` However, on...
python
def parse_url_to_topic(method, route): """ Transforms a URL to a topic. `GET /bar/{id}` -> `get.bar.*` `POST /bar/{id}` -> `post.bar.*` `GET /foo/bar/{id}/baz` -? `get.foo.bar.*.baz` Possible gotchas `GET /foo/{id}` -> `get.foo.*` `GET /foo/{id}:action` -> `get.foo.*` However, on...
[ "def", "parse_url_to_topic", "(", "method", ",", "route", ")", ":", "route", "=", "route", ".", "replace", "(", "'.'", ",", "'?'", ")", "route", "=", "route", ".", "replace", "(", "'/'", ",", "'.'", ")", ".", "strip", "(", "'.'", ")", "topic", "=",...
Transforms a URL to a topic. `GET /bar/{id}` -> `get.bar.*` `POST /bar/{id}` -> `post.bar.*` `GET /foo/bar/{id}/baz` -? `get.foo.bar.*.baz` Possible gotchas `GET /foo/{id}` -> `get.foo.*` `GET /foo/{id}:action` -> `get.foo.*` However, once it hits the service the router will be able to d...
[ "Transforms", "a", "URL", "to", "a", "topic", "." ]
train
https://github.com/wasp/waspy/blob/31cc352f300a089f9607d7f13d93591d4c69d5ec/waspy/transports/rabbitmqtransport.py#L500-L519
wasp/waspy
waspy/transports/rabbitmqtransport.py
RabbitMQTransport.handle_request
async def handle_request(self, channel: Channel, body, envelope, properties, futurize=True): """ the 'futurize' param is simply because aioamqp doesnt send another job until this method returns (completes), so we ensure the future of ourselves and return im...
python
async def handle_request(self, channel: Channel, body, envelope, properties, futurize=True): """ the 'futurize' param is simply because aioamqp doesnt send another job until this method returns (completes), so we ensure the future of ourselves and return im...
[ "async", "def", "handle_request", "(", "self", ",", "channel", ":", "Channel", ",", "body", ",", "envelope", ",", "properties", ",", "futurize", "=", "True", ")", ":", "if", "futurize", ":", "asyncio", ".", "ensure_future", "(", "self", ".", "handle_reques...
the 'futurize' param is simply because aioamqp doesnt send another job until this method returns (completes), so we ensure the future of ourselves and return immediately so we can handle many requests at a time.
[ "the", "futurize", "param", "is", "simply", "because", "aioamqp", "doesnt", "send", "another", "job", "until", "this", "method", "returns", "(", "completes", ")", "so", "we", "ensure", "the", "future", "of", "ourselves", "and", "return", "immediately", "so", ...
train
https://github.com/wasp/waspy/blob/31cc352f300a089f9607d7f13d93591d4c69d5ec/waspy/transports/rabbitmqtransport.py#L404-L477
tadashi-aikawa/jumeaux
jumeaux/addons/res2res/json.py
wrap
def wrap(anything: bytes, encoding: str) -> str: """Use for example of Transformer.function """ return json.dumps({ "wrap": load_json(anything.decode(encoding)) }, ensure_ascii=False)
python
def wrap(anything: bytes, encoding: str) -> str: """Use for example of Transformer.function """ return json.dumps({ "wrap": load_json(anything.decode(encoding)) }, ensure_ascii=False)
[ "def", "wrap", "(", "anything", ":", "bytes", ",", "encoding", ":", "str", ")", "->", "str", ":", "return", "json", ".", "dumps", "(", "{", "\"wrap\"", ":", "load_json", "(", "anything", ".", "decode", "(", "encoding", ")", ")", "}", ",", "ensure_asc...
Use for example of Transformer.function
[ "Use", "for", "example", "of", "Transformer", ".", "function" ]
train
https://github.com/tadashi-aikawa/jumeaux/blob/23389bde3e9b27b3a646d99289f8b5ced411f6f0/jumeaux/addons/res2res/json.py#L19-L24
proteanhq/protean
src/protean/core/repository/base.py
BaseRepository.filter
def filter(self, criteria: Q, offset: int = 0, limit: int = 10, order_by: list = ()) -> ResultSet: """ Filter objects from the repository. Method must return a `ResultSet` object """
python
def filter(self, criteria: Q, offset: int = 0, limit: int = 10, order_by: list = ()) -> ResultSet: """ Filter objects from the repository. Method must return a `ResultSet` object """
[ "def", "filter", "(", "self", ",", "criteria", ":", "Q", ",", "offset", ":", "int", "=", "0", ",", "limit", ":", "int", "=", "10", ",", "order_by", ":", "list", "=", "(", ")", ")", "->", "ResultSet", ":" ]
Filter objects from the repository. Method must return a `ResultSet` object
[ "Filter", "objects", "from", "the", "repository", ".", "Method", "must", "return", "a", "ResultSet", "object" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/repository/base.py#L29-L34
proteanhq/protean
src/protean/core/transport/request.py
RequestObjectFactory.construct
def construct(cls, name: str, declared_fields: typing.List[tuple]): """ Utility method packaged along with the factory to be able to construct Request Object classes on the fly. Example: .. code-block:: python UserShowRequestObject = Factory.create_request_object( ...
python
def construct(cls, name: str, declared_fields: typing.List[tuple]): """ Utility method packaged along with the factory to be able to construct Request Object classes on the fly. Example: .. code-block:: python UserShowRequestObject = Factory.create_request_object( ...
[ "def", "construct", "(", "cls", ",", "name", ":", "str", ",", "declared_fields", ":", "typing", ".", "List", "[", "tuple", "]", ")", ":", "# FIXME Refactor this method to make it simpler", "@", "classmethod", "def", "from_dict", "(", "cls", ",", "adict", ")", ...
Utility method packaged along with the factory to be able to construct Request Object classes on the fly. Example: .. code-block:: python UserShowRequestObject = Factory.create_request_object( 'CreateRequestObject', [('identifier', int, {'required':...
[ "Utility", "method", "packaged", "along", "with", "the", "factory", "to", "be", "able", "to", "construct", "Request", "Object", "classes", "on", "the", "fly", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/transport/request.py#L40-L117
proteanhq/protean
src/protean/core/transport/request.py
RequestObjectFactory._format_fields
def _format_fields(cls, declared_fields: typing.List[tuple]): """Process declared fields and construct a list of tuples that can be fed into dataclass constructor factory. """ formatted_fields = [] for declared_field in declared_fields: field_name = field_type = field...
python
def _format_fields(cls, declared_fields: typing.List[tuple]): """Process declared fields and construct a list of tuples that can be fed into dataclass constructor factory. """ formatted_fields = [] for declared_field in declared_fields: field_name = field_type = field...
[ "def", "_format_fields", "(", "cls", ",", "declared_fields", ":", "typing", ".", "List", "[", "tuple", "]", ")", ":", "formatted_fields", "=", "[", "]", "for", "declared_field", "in", "declared_fields", ":", "field_name", "=", "field_type", "=", "field_defn", ...
Process declared fields and construct a list of tuples that can be fed into dataclass constructor factory.
[ "Process", "declared", "fields", "and", "construct", "a", "list", "of", "tuples", "that", "can", "be", "fed", "into", "dataclass", "constructor", "factory", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/transport/request.py#L120-L157
martinmcbride/pysound
pysound/soundfile.py
save
def save(params, filename, source): ''' Write a sequence of samples as a WAV file Currently a 16 bit mono file ''' writer = wave.open(filename, 'wb'); # Set the WAV file parameters, currently default values writer.setnchannels(1) writer.setsampwidth(2) writer.setframerate(params.samp...
python
def save(params, filename, source): ''' Write a sequence of samples as a WAV file Currently a 16 bit mono file ''' writer = wave.open(filename, 'wb'); # Set the WAV file parameters, currently default values writer.setnchannels(1) writer.setsampwidth(2) writer.setframerate(params.samp...
[ "def", "save", "(", "params", ",", "filename", ",", "source", ")", ":", "writer", "=", "wave", ".", "open", "(", "filename", ",", "'wb'", ")", "# Set the WAV file parameters, currently default values", "writer", ".", "setnchannels", "(", "1", ")", "writer", "....
Write a sequence of samples as a WAV file Currently a 16 bit mono file
[ "Write", "a", "sequence", "of", "samples", "as", "a", "WAV", "file", "Currently", "a", "16", "bit", "mono", "file" ]
train
https://github.com/martinmcbride/pysound/blob/253c8f712ad475318350e5a8ba21f6fefd7a3de2/pysound/soundfile.py#L9-L23
deep-compute/deeputil
deeputil/priority_dict.py
PriorityDict.smallest
def smallest(self): """Return the item with the lowest priority. Raises IndexError if the object is empty. """ heap = self._heap v, k = heap[0] while k not in self or self[k] != v: heappop(heap) v, k = heap[0] return k
python
def smallest(self): """Return the item with the lowest priority. Raises IndexError if the object is empty. """ heap = self._heap v, k = heap[0] while k not in self or self[k] != v: heappop(heap) v, k = heap[0] return k
[ "def", "smallest", "(", "self", ")", ":", "heap", "=", "self", ".", "_heap", "v", ",", "k", "=", "heap", "[", "0", "]", "while", "k", "not", "in", "self", "or", "self", "[", "k", "]", "!=", "v", ":", "heappop", "(", "heap", ")", "v", ",", "...
Return the item with the lowest priority. Raises IndexError if the object is empty.
[ "Return", "the", "item", "with", "the", "lowest", "priority", "." ]
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/priority_dict.py#L76-L88
deep-compute/deeputil
deeputil/priority_dict.py
PriorityDict.pop_smallest
def pop_smallest(self): """Return the item with the lowest priority and remove it. Raises IndexError if the object is empty. """ heap = self._heap v, k = heappop(heap) while k not in self or self[k] != v: v, k = heappop(heap) del self[k] retu...
python
def pop_smallest(self): """Return the item with the lowest priority and remove it. Raises IndexError if the object is empty. """ heap = self._heap v, k = heappop(heap) while k not in self or self[k] != v: v, k = heappop(heap) del self[k] retu...
[ "def", "pop_smallest", "(", "self", ")", ":", "heap", "=", "self", ".", "_heap", "v", ",", "k", "=", "heappop", "(", "heap", ")", "while", "k", "not", "in", "self", "or", "self", "[", "k", "]", "!=", "v", ":", "v", ",", "k", "=", "heappop", "...
Return the item with the lowest priority and remove it. Raises IndexError if the object is empty.
[ "Return", "the", "item", "with", "the", "lowest", "priority", "and", "remove", "it", "." ]
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/priority_dict.py#L90-L101
proteanhq/protean
src/protean/core/tasklet.py
Tasklet.perform
def perform(cls, entity_cls, usecase_cls, request_object_cls, payload: dict, raise_error=False): """ This method bundles all essential artifacts and initiates usecase execution. :param entity_cls: The entity class to be used for running the usecase :param usecase_...
python
def perform(cls, entity_cls, usecase_cls, request_object_cls, payload: dict, raise_error=False): """ This method bundles all essential artifacts and initiates usecase execution. :param entity_cls: The entity class to be used for running the usecase :param usecase_...
[ "def", "perform", "(", "cls", ",", "entity_cls", ",", "usecase_cls", ",", "request_object_cls", ",", "payload", ":", "dict", ",", "raise_error", "=", "False", ")", ":", "# Initialize the use case and request objects", "use_case", "=", "usecase_cls", "(", ")", "pay...
This method bundles all essential artifacts and initiates usecase execution. :param entity_cls: The entity class to be used for running the usecase :param usecase_cls: The usecase class that will be executed by the tasklet. :param request_object_cls: The request object to be used...
[ "This", "method", "bundles", "all", "essential", "artifacts", "and", "initiates", "usecase", "execution", ".", ":", "param", "entity_cls", ":", "The", "entity", "class", "to", "be", "used", "for", "running", "the", "usecase", ":", "param", "usecase_cls", ":", ...
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/tasklet.py#L10-L42
wasp/waspy
waspy/webtypes.py
Parseable.body
def body(self) -> dict: """ Decoded Body """ if self.ignore_content_type: return self.original_body if self._body is None and self.original_body is not None: if isinstance(self.original_body, bytes): self._body = self.parser.decode(self.original_body) ...
python
def body(self) -> dict: """ Decoded Body """ if self.ignore_content_type: return self.original_body if self._body is None and self.original_body is not None: if isinstance(self.original_body, bytes): self._body = self.parser.decode(self.original_body) ...
[ "def", "body", "(", "self", ")", "->", "dict", ":", "if", "self", ".", "ignore_content_type", ":", "return", "self", ".", "original_body", "if", "self", ".", "_body", "is", "None", "and", "self", ".", "original_body", "is", "not", "None", ":", "if", "i...
Decoded Body
[ "Decoded", "Body" ]
train
https://github.com/wasp/waspy/blob/31cc352f300a089f9607d7f13d93591d4c69d5ec/waspy/webtypes.py#L95-L104
wasp/waspy
waspy/webtypes.py
Parseable.raw_body
def raw_body(self) -> bytes: """ Encoded Body """ if self._raw_body is None and self.original_body is not None: if isinstance(self.original_body, dict): self._raw_body = self.parser.encode(self.original_body) if isinstance(self._raw_body, str): ...
python
def raw_body(self) -> bytes: """ Encoded Body """ if self._raw_body is None and self.original_body is not None: if isinstance(self.original_body, dict): self._raw_body = self.parser.encode(self.original_body) if isinstance(self._raw_body, str): ...
[ "def", "raw_body", "(", "self", ")", "->", "bytes", ":", "if", "self", ".", "_raw_body", "is", "None", "and", "self", ".", "original_body", "is", "not", "None", ":", "if", "isinstance", "(", "self", ".", "original_body", ",", "dict", ")", ":", "self", ...
Encoded Body
[ "Encoded", "Body" ]
train
https://github.com/wasp/waspy/blob/31cc352f300a089f9607d7f13d93591d4c69d5ec/waspy/webtypes.py#L122-L137
proteanhq/protean
src/protean/impl/email/local_mem.py
EmailBackend.send_messages
def send_messages(self, messages): """Redirect messages to the dummy outbox""" msg_count = 0 for message in messages: # .message() triggers header validation message.message() email.outbox.append(message) msg_count += 1 return msg_count
python
def send_messages(self, messages): """Redirect messages to the dummy outbox""" msg_count = 0 for message in messages: # .message() triggers header validation message.message() email.outbox.append(message) msg_count += 1 return msg_count
[ "def", "send_messages", "(", "self", ",", "messages", ")", ":", "msg_count", "=", "0", "for", "message", "in", "messages", ":", "# .message() triggers header validation", "message", ".", "message", "(", ")", "email", ".", "outbox", ".", "append", "(", "message...
Redirect messages to the dummy outbox
[ "Redirect", "messages", "to", "the", "dummy", "outbox" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/email/local_mem.py#L19-L27
martinmcbride/pysound
pysound/oscillators.py
square_wave
def square_wave(params, frequency=400, amplitude=1, offset=0, ratio=0.5): ''' Generate a square wave :param params: buffer parameters, controls length of signal created :param frequency: wave frequency (array or value) :param amplitude: wave amplitude (array or value) :param offs...
python
def square_wave(params, frequency=400, amplitude=1, offset=0, ratio=0.5): ''' Generate a square wave :param params: buffer parameters, controls length of signal created :param frequency: wave frequency (array or value) :param amplitude: wave amplitude (array or value) :param offs...
[ "def", "square_wave", "(", "params", ",", "frequency", "=", "400", ",", "amplitude", "=", "1", ",", "offset", "=", "0", ",", "ratio", "=", "0.5", ")", ":", "frequency", "=", "create_buffer", "(", "params", ",", "frequency", ")", "amplitude", "=", "crea...
Generate a square wave :param params: buffer parameters, controls length of signal created :param frequency: wave frequency (array or value) :param amplitude: wave amplitude (array or value) :param offset: offset of wave mean from zero (array or value) :param ratio: ratio of high to low time (array ...
[ "Generate", "a", "square", "wave", ":", "param", "params", ":", "buffer", "parameters", "controls", "length", "of", "signal", "created", ":", "param", "frequency", ":", "wave", "frequency", "(", "array", "or", "value", ")", ":", "param", "amplitude", ":", ...
train
https://github.com/martinmcbride/pysound/blob/253c8f712ad475318350e5a8ba21f6fefd7a3de2/pysound/oscillators.py#L16-L33
martinmcbride/pysound
pysound/oscillators.py
noise
def noise(params, amplitude=1, offset=0): ''' Generate a noise signal :param params: buffer parameters, controls length of signal created :param amplitude: wave amplitude (array or value) :param offset: offset of wave mean from zero (array or value) :return: array of resulting signal ''' ...
python
def noise(params, amplitude=1, offset=0): ''' Generate a noise signal :param params: buffer parameters, controls length of signal created :param amplitude: wave amplitude (array or value) :param offset: offset of wave mean from zero (array or value) :return: array of resulting signal ''' ...
[ "def", "noise", "(", "params", ",", "amplitude", "=", "1", ",", "offset", "=", "0", ")", ":", "amplitude", "=", "create_buffer", "(", "params", ",", "amplitude", ")", "offset", "=", "create_buffer", "(", "params", ",", "offset", ")", "output", "=", "of...
Generate a noise signal :param params: buffer parameters, controls length of signal created :param amplitude: wave amplitude (array or value) :param offset: offset of wave mean from zero (array or value) :return: array of resulting signal
[ "Generate", "a", "noise", "signal", ":", "param", "params", ":", "buffer", "parameters", "controls", "length", "of", "signal", "created", ":", "param", "amplitude", ":", "wave", "amplitude", "(", "array", "or", "value", ")", ":", "param", "offset", ":", "o...
train
https://github.com/martinmcbride/pysound/blob/253c8f712ad475318350e5a8ba21f6fefd7a3de2/pysound/oscillators.py#L55-L66
martinmcbride/pysound
pysound/oscillators.py
table_wave
def table_wave(params, frequency=400, amplitude=1, offset=0, table=None): ''' Generate a wave from a wavetable :param params: buffer parameters, controls length of signal created :param frequency: wave frequency (array or value) :param amplitude: wave amplitude (array or value) :...
python
def table_wave(params, frequency=400, amplitude=1, offset=0, table=None): ''' Generate a wave from a wavetable :param params: buffer parameters, controls length of signal created :param frequency: wave frequency (array or value) :param amplitude: wave amplitude (array or value) :...
[ "def", "table_wave", "(", "params", ",", "frequency", "=", "400", ",", "amplitude", "=", "1", ",", "offset", "=", "0", ",", "table", "=", "None", ")", ":", "if", "not", "table", ":", "table", "=", "create_sine_table", "(", "65536", ")", "size", "=", ...
Generate a wave from a wavetable :param params: buffer parameters, controls length of signal created :param frequency: wave frequency (array or value) :param amplitude: wave amplitude (array or value) :param offset: offset of wave mean from zero (array or value) :param table: table of values represe...
[ "Generate", "a", "wave", "from", "a", "wavetable", ":", "param", "params", ":", "buffer", "parameters", "controls", "length", "of", "signal", "created", ":", "param", "frequency", ":", "wave", "frequency", "(", "array", "or", "value", ")", ":", "param", "a...
train
https://github.com/martinmcbride/pysound/blob/253c8f712ad475318350e5a8ba21f6fefd7a3de2/pysound/oscillators.py#L68-L88
martinmcbride/pysound
pysound/oscillators.py
sine_wave
def sine_wave(params, frequency=400, amplitude=1, offset=0): ''' Generate a sine wave Convenience function, table_wave generates a sine wave by default :param params: buffer parameters, controls length of signal created :param frequency: wave frequency (array or value) :param amplitude: wave amp...
python
def sine_wave(params, frequency=400, amplitude=1, offset=0): ''' Generate a sine wave Convenience function, table_wave generates a sine wave by default :param params: buffer parameters, controls length of signal created :param frequency: wave frequency (array or value) :param amplitude: wave amp...
[ "def", "sine_wave", "(", "params", ",", "frequency", "=", "400", ",", "amplitude", "=", "1", ",", "offset", "=", "0", ")", ":", "return", "table_wave", "(", "params", ",", "frequency", ",", "amplitude", ",", "offset", ")" ]
Generate a sine wave Convenience function, table_wave generates a sine wave by default :param params: buffer parameters, controls length of signal created :param frequency: wave frequency (array or value) :param amplitude: wave amplitude (array or value) :param offset: offset of wave mean from zero ...
[ "Generate", "a", "sine", "wave", "Convenience", "function", "table_wave", "generates", "a", "sine", "wave", "by", "default", ":", "param", "params", ":", "buffer", "parameters", "controls", "length", "of", "signal", "created", ":", "param", "frequency", ":", "...
train
https://github.com/martinmcbride/pysound/blob/253c8f712ad475318350e5a8ba21f6fefd7a3de2/pysound/oscillators.py#L90-L100
martinmcbride/pysound
pysound/oscillators.py
midi2f
def midi2f(params, midi=69): ''' Convert a midi value to a frequency. Midi value 69 corresponds to A4 (440Hz). Changing the midi value by 1 corresponds to one semitone :param params: buffer parameters, controls length of signal created :param midi: midi value :return: array of resulting freq...
python
def midi2f(params, midi=69): ''' Convert a midi value to a frequency. Midi value 69 corresponds to A4 (440Hz). Changing the midi value by 1 corresponds to one semitone :param params: buffer parameters, controls length of signal created :param midi: midi value :return: array of resulting freq...
[ "def", "midi2f", "(", "params", ",", "midi", "=", "69", ")", ":", "midi", "=", "create_buffer", "(", "params", ",", "midi", ")", "output", "=", "2", "**", "(", "(", "midi", "-", "69", ")", "/", "12", ")", "*", "440", "return", "output" ]
Convert a midi value to a frequency. Midi value 69 corresponds to A4 (440Hz). Changing the midi value by 1 corresponds to one semitone :param params: buffer parameters, controls length of signal created :param midi: midi value :return: array of resulting frequency
[ "Convert", "a", "midi", "value", "to", "a", "frequency", ".", "Midi", "value", "69", "corresponds", "to", "A4", "(", "440Hz", ")", ".", "Changing", "the", "midi", "value", "by", "1", "corresponds", "to", "one", "semitone", ":", "param", "params", ":", ...
train
https://github.com/martinmcbride/pysound/blob/253c8f712ad475318350e5a8ba21f6fefd7a3de2/pysound/oscillators.py#L102-L113
proteanhq/protean
src/protean/utils/query.py
RegisterLookupMixin.get_lookups
def get_lookups(cls): """Fetch all Lookups""" class_lookups = [parent.__dict__.get('class_lookups', {}) for parent in inspect.getmro(cls)] return cls.merge_dicts(class_lookups)
python
def get_lookups(cls): """Fetch all Lookups""" class_lookups = [parent.__dict__.get('class_lookups', {}) for parent in inspect.getmro(cls)] return cls.merge_dicts(class_lookups)
[ "def", "get_lookups", "(", "cls", ")", ":", "class_lookups", "=", "[", "parent", ".", "__dict__", ".", "get", "(", "'class_lookups'", ",", "{", "}", ")", "for", "parent", "in", "inspect", ".", "getmro", "(", "cls", ")", "]", "return", "cls", ".", "me...
Fetch all Lookups
[ "Fetch", "all", "Lookups" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/utils/query.py#L22-L25
proteanhq/protean
src/protean/utils/query.py
RegisterLookupMixin.get_lookup
def get_lookup(self, lookup_name): """Fetch Lookup by name""" from protean.core.repository import BaseLookup lookup = self._get_lookup(lookup_name) # If unable to find Lookup, or if Lookup is the wrong class, raise Error if lookup is None or (lookup is not None and not issubclas...
python
def get_lookup(self, lookup_name): """Fetch Lookup by name""" from protean.core.repository import BaseLookup lookup = self._get_lookup(lookup_name) # If unable to find Lookup, or if Lookup is the wrong class, raise Error if lookup is None or (lookup is not None and not issubclas...
[ "def", "get_lookup", "(", "self", ",", "lookup_name", ")", ":", "from", "protean", ".", "core", ".", "repository", "import", "BaseLookup", "lookup", "=", "self", ".", "_get_lookup", "(", "lookup_name", ")", "# If unable to find Lookup, or if Lookup is the wrong class,...
Fetch Lookup by name
[ "Fetch", "Lookup", "by", "name" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/utils/query.py#L27-L36
proteanhq/protean
src/protean/utils/query.py
RegisterLookupMixin.merge_dicts
def merge_dicts(dicts): """ Merge dicts in reverse to preference the order of the original list. e.g., merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'. """ merged = {} for d in reversed(dicts): merged.update(d) return merged
python
def merge_dicts(dicts): """ Merge dicts in reverse to preference the order of the original list. e.g., merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'. """ merged = {} for d in reversed(dicts): merged.update(d) return merged
[ "def", "merge_dicts", "(", "dicts", ")", ":", "merged", "=", "{", "}", "for", "d", "in", "reversed", "(", "dicts", ")", ":", "merged", ".", "update", "(", "d", ")", "return", "merged" ]
Merge dicts in reverse to preference the order of the original list. e.g., merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'.
[ "Merge", "dicts", "in", "reverse", "to", "preference", "the", "order", "of", "the", "original", "list", ".", "e", ".", "g", ".", "merge_dicts", "(", "[", "a", "b", "]", ")", "will", "preference", "the", "keys", "in", "a", "over", "those", "in", "b", ...
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/utils/query.py#L39-L47
proteanhq/protean
src/protean/utils/query.py
RegisterLookupMixin.register_lookup
def register_lookup(cls, lookup, lookup_name=None): """Register a Lookup to a class""" if lookup_name is None: lookup_name = lookup.lookup_name if 'class_lookups' not in cls.__dict__: cls.class_lookups = {} cls.class_lookups[lookup_name] = lookup cls._cle...
python
def register_lookup(cls, lookup, lookup_name=None): """Register a Lookup to a class""" if lookup_name is None: lookup_name = lookup.lookup_name if 'class_lookups' not in cls.__dict__: cls.class_lookups = {} cls.class_lookups[lookup_name] = lookup cls._cle...
[ "def", "register_lookup", "(", "cls", ",", "lookup", ",", "lookup_name", "=", "None", ")", ":", "if", "lookup_name", "is", "None", ":", "lookup_name", "=", "lookup", ".", "lookup_name", "if", "'class_lookups'", "not", "in", "cls", ".", "__dict__", ":", "cl...
Register a Lookup to a class
[ "Register", "a", "Lookup", "to", "a", "class" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/utils/query.py#L55-L65
proteanhq/protean
src/protean/utils/query.py
RegisterLookupMixin._unregister_lookup
def _unregister_lookup(cls, lookup, lookup_name=None): """ Remove given lookup from cls lookups. For use in tests only as it's not thread-safe. """ if lookup_name is None: lookup_name = lookup.lookup_name del cls.class_lookups[lookup_name]
python
def _unregister_lookup(cls, lookup, lookup_name=None): """ Remove given lookup from cls lookups. For use in tests only as it's not thread-safe. """ if lookup_name is None: lookup_name = lookup.lookup_name del cls.class_lookups[lookup_name]
[ "def", "_unregister_lookup", "(", "cls", ",", "lookup", ",", "lookup_name", "=", "None", ")", ":", "if", "lookup_name", "is", "None", ":", "lookup_name", "=", "lookup", ".", "lookup_name", "del", "cls", ".", "class_lookups", "[", "lookup_name", "]" ]
Remove given lookup from cls lookups. For use in tests only as it's not thread-safe.
[ "Remove", "given", "lookup", "from", "cls", "lookups", ".", "For", "use", "in", "tests", "only", "as", "it", "s", "not", "thread", "-", "safe", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/utils/query.py#L68-L75
proteanhq/protean
src/protean/utils/query.py
Q.deconstruct
def deconstruct(self): """Deconstruct a Q Object""" path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__) args, kwargs = (), {} if len(self.children) == 1 and not isinstance(self.children[0], Q): child = self.children[0] kwargs = {child[0]: child[...
python
def deconstruct(self): """Deconstruct a Q Object""" path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__) args, kwargs = (), {} if len(self.children) == 1 and not isinstance(self.children[0], Q): child = self.children[0] kwargs = {child[0]: child[...
[ "def", "deconstruct", "(", "self", ")", ":", "path", "=", "'%s.%s'", "%", "(", "self", ".", "__class__", ".", "__module__", ",", "self", ".", "__class__", ".", "__name__", ")", "args", ",", "kwargs", "=", "(", ")", ",", "{", "}", "if", "len", "(", ...
Deconstruct a Q Object
[ "Deconstruct", "a", "Q", "Object" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/utils/query.py#L238-L252
proteanhq/protean
src/protean/utils/importlib.py
perform_import
def perform_import(val): """ If the given setting is a string import notation, then perform the necessary import or imports. """ if val is None: return None elif isinstance(val, str): return import_from_string(val) elif isinstance(val, (list, tuple)): return [import_f...
python
def perform_import(val): """ If the given setting is a string import notation, then perform the necessary import or imports. """ if val is None: return None elif isinstance(val, str): return import_from_string(val) elif isinstance(val, (list, tuple)): return [import_f...
[ "def", "perform_import", "(", "val", ")", ":", "if", "val", "is", "None", ":", "return", "None", "elif", "isinstance", "(", "val", ",", "str", ")", ":", "return", "import_from_string", "(", "val", ")", "elif", "isinstance", "(", "val", ",", "(", "list"...
If the given setting is a string import notation, then perform the necessary import or imports.
[ "If", "the", "given", "setting", "is", "a", "string", "import", "notation", "then", "perform", "the", "necessary", "import", "or", "imports", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/utils/importlib.py#L6-L17
proteanhq/protean
src/protean/utils/importlib.py
import_from_string
def import_from_string(val): """ Attempt to import a class from a string representation. """ try: module_path, class_name = val.rsplit('.', 1) module = import_module(module_path) return getattr(module, class_name) except (ImportError, AttributeError) as e: msg = f"Cou...
python
def import_from_string(val): """ Attempt to import a class from a string representation. """ try: module_path, class_name = val.rsplit('.', 1) module = import_module(module_path) return getattr(module, class_name) except (ImportError, AttributeError) as e: msg = f"Cou...
[ "def", "import_from_string", "(", "val", ")", ":", "try", ":", "module_path", ",", "class_name", "=", "val", ".", "rsplit", "(", "'.'", ",", "1", ")", "module", "=", "import_module", "(", "module_path", ")", "return", "getattr", "(", "module", ",", "clas...
Attempt to import a class from a string representation.
[ "Attempt", "to", "import", "a", "class", "from", "a", "string", "representation", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/utils/importlib.py#L20-L30
proteanhq/protean
src/protean/context.py
Context.set_context
def set_context(self, data): """Load Context with data""" for key in data: setattr(self.local_context, key, data[key])
python
def set_context(self, data): """Load Context with data""" for key in data: setattr(self.local_context, key, data[key])
[ "def", "set_context", "(", "self", ",", "data", ")", ":", "for", "key", "in", "data", ":", "setattr", "(", "self", ".", "local_context", ",", "key", ",", "data", "[", "key", "]", ")" ]
Load Context with data
[ "Load", "Context", "with", "data" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/context.py#L27-L30
proteanhq/protean
src/protean/core/field/association.py
_ReferenceField._reset_values
def _reset_values(self, instance): """Reset all associated values and clean up dictionary items""" self.value = None self.reference.value = None instance.__dict__.pop(self.field_name, None) instance.__dict__.pop(self.reference.field_name, None) self.reference.delete_cache...
python
def _reset_values(self, instance): """Reset all associated values and clean up dictionary items""" self.value = None self.reference.value = None instance.__dict__.pop(self.field_name, None) instance.__dict__.pop(self.reference.field_name, None) self.reference.delete_cache...
[ "def", "_reset_values", "(", "self", ",", "instance", ")", ":", "self", ".", "value", "=", "None", "self", ".", "reference", ".", "value", "=", "None", "instance", ".", "__dict__", ".", "pop", "(", "self", ".", "field_name", ",", "None", ")", "instance...
Reset all associated values and clean up dictionary items
[ "Reset", "all", "associated", "values", "and", "clean", "up", "dictionary", "items" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/association.py#L41-L47
proteanhq/protean
src/protean/core/field/association.py
Reference.to_cls
def to_cls(self): """Property to retrieve to_cls as an entity when possible""" # Checks if ``to_cls`` is a string # If it is, checks if the entity is imported and available # If it is, register the class try: if isinstance(self._to_cls, str): self....
python
def to_cls(self): """Property to retrieve to_cls as an entity when possible""" # Checks if ``to_cls`` is a string # If it is, checks if the entity is imported and available # If it is, register the class try: if isinstance(self._to_cls, str): self....
[ "def", "to_cls", "(", "self", ")", ":", "# Checks if ``to_cls`` is a string", "# If it is, checks if the entity is imported and available", "# If it is, register the class", "try", ":", "if", "isinstance", "(", "self", ".", "_to_cls", ",", "str", ")", ":", "self", "."...
Property to retrieve to_cls as an entity when possible
[ "Property", "to", "retrieve", "to_cls", "as", "an", "entity", "when", "possible" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/association.py#L68-L80
proteanhq/protean
src/protean/core/field/association.py
Reference.linked_attribute
def linked_attribute(self): """Choose the Linkage attribute between `via` and designated `id_field` of the target class This method is initially called from `__set_name__()` -> `get_attribute_name()` at which point, the `to_cls` has not been initialized properly. We simply default the l...
python
def linked_attribute(self): """Choose the Linkage attribute between `via` and designated `id_field` of the target class This method is initially called from `__set_name__()` -> `get_attribute_name()` at which point, the `to_cls` has not been initialized properly. We simply default the l...
[ "def", "linked_attribute", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "to_cls", ",", "str", ")", ":", "return", "'id'", "else", ":", "return", "self", ".", "via", "or", "self", ".", "to_cls", ".", "meta_", ".", "id_field", ".", "att...
Choose the Linkage attribute between `via` and designated `id_field` of the target class This method is initially called from `__set_name__()` -> `get_attribute_name()` at which point, the `to_cls` has not been initialized properly. We simply default the linked attribute to 'id' in that case. ...
[ "Choose", "the", "Linkage", "attribute", "between", "via", "and", "designated", "id_field", "of", "the", "target", "class" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/association.py#L95-L108
proteanhq/protean
src/protean/core/field/association.py
Association._linked_attribute
def _linked_attribute(self, owner): """Choose the Linkage attribute between `via` and own entity's `id_field` FIXME Explore converting this method into an attribute, and treating it uniformly at `association` level. """ return self.via or (utils.inflection.underscore(owner...
python
def _linked_attribute(self, owner): """Choose the Linkage attribute between `via` and own entity's `id_field` FIXME Explore converting this method into an attribute, and treating it uniformly at `association` level. """ return self.via or (utils.inflection.underscore(owner...
[ "def", "_linked_attribute", "(", "self", ",", "owner", ")", ":", "return", "self", ".", "via", "or", "(", "utils", ".", "inflection", ".", "underscore", "(", "owner", ".", "__name__", ")", "+", "'_id'", ")" ]
Choose the Linkage attribute between `via` and own entity's `id_field` FIXME Explore converting this method into an attribute, and treating it uniformly at `association` level.
[ "Choose", "the", "Linkage", "attribute", "between", "via", "and", "own", "entity", "s", "id_field" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/association.py#L211-L217
proteanhq/protean
src/protean/core/field/association.py
HasMany._fetch_objects
def _fetch_objects(self, key, value): """Fetch Multiple linked objects""" return self.to_cls.query.filter(**{key: value})
python
def _fetch_objects(self, key, value): """Fetch Multiple linked objects""" return self.to_cls.query.filter(**{key: value})
[ "def", "_fetch_objects", "(", "self", ",", "key", ",", "value", ")", ":", "return", "self", ".", "to_cls", ".", "query", ".", "filter", "(", "*", "*", "{", "key", ":", "value", "}", ")" ]
Fetch Multiple linked objects
[ "Fetch", "Multiple", "linked", "objects" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/association.py#L290-L292
wasp/waspy
waspy/transports/rabbit_patches.py
_write_frame_awaiting_response
async def _write_frame_awaiting_response(self, waiter_id, frame, request, no_wait, check_open=True, drain=True): '''Write a frame and set a waiter for the response (unless no_wait is set)''' if no_wait: await self._write_frame(frame, request, check_open=check...
python
async def _write_frame_awaiting_response(self, waiter_id, frame, request, no_wait, check_open=True, drain=True): '''Write a frame and set a waiter for the response (unless no_wait is set)''' if no_wait: await self._write_frame(frame, request, check_open=check...
[ "async", "def", "_write_frame_awaiting_response", "(", "self", ",", "waiter_id", ",", "frame", ",", "request", ",", "no_wait", ",", "check_open", "=", "True", ",", "drain", "=", "True", ")", ":", "if", "no_wait", ":", "await", "self", ".", "_write_frame", ...
Write a frame and set a waiter for the response (unless no_wait is set)
[ "Write", "a", "frame", "and", "set", "a", "waiter", "for", "the", "response", "(", "unless", "no_wait", "is", "set", ")" ]
train
https://github.com/wasp/waspy/blob/31cc352f300a089f9607d7f13d93591d4c69d5ec/waspy/transports/rabbit_patches.py#L99-L122
martinmcbride/pysound
pysound/mixers.py
sequencer
def sequencer(params, source_specs): ''' Add a sequence of sounds to a buffer :param params: buffer parameters, controls length of signal created :param source_spec: list of tuples containing (source, sample). The source is added into the output buffer at the sample position given by the second elem...
python
def sequencer(params, source_specs): ''' Add a sequence of sounds to a buffer :param params: buffer parameters, controls length of signal created :param source_spec: list of tuples containing (source, sample). The source is added into the output buffer at the sample position given by the second elem...
[ "def", "sequencer", "(", "params", ",", "source_specs", ")", ":", "output", "=", "np", ".", "zeros", "(", "params", ".", "length", ",", "dtype", "=", "np", ".", "float", ")", "for", "source", ",", "pos", "in", "source_specs", ":", "if", "pos", ">=", ...
Add a sequence of sounds to a buffer :param params: buffer parameters, controls length of signal created :param source_spec: list of tuples containing (source, sample). The source is added into the output buffer at the sample position given by the second element in the tuple :return:
[ "Add", "a", "sequence", "of", "sounds", "to", "a", "buffer", ":", "param", "params", ":", "buffer", "parameters", "controls", "length", "of", "signal", "created", ":", "param", "source_spec", ":", "list", "of", "tuples", "containing", "(", "source", "sample"...
train
https://github.com/martinmcbride/pysound/blob/253c8f712ad475318350e5a8ba21f6fefd7a3de2/pysound/mixers.py#L29-L43
proteanhq/protean
src/protean/core/entity.py
EntityBase._load_base_class_fields
def _load_base_class_fields(new_class, bases, attrs): """If this class is subclassing another Entity, add that Entity's fields. Note that we loop over the bases in *reverse*. This is necessary in order to maintain the correct order of fields. """ for base in reversed(bases): ...
python
def _load_base_class_fields(new_class, bases, attrs): """If this class is subclassing another Entity, add that Entity's fields. Note that we loop over the bases in *reverse*. This is necessary in order to maintain the correct order of fields. """ for base in reversed(bases): ...
[ "def", "_load_base_class_fields", "(", "new_class", ",", "bases", ",", "attrs", ")", ":", "for", "base", "in", "reversed", "(", "bases", ")", ":", "if", "hasattr", "(", "base", ",", "'meta_'", ")", "and", "hasattr", "(", "base", ".", "meta_", ",", "'de...
If this class is subclassing another Entity, add that Entity's fields. Note that we loop over the bases in *reverse*. This is necessary in order to maintain the correct order of fields.
[ "If", "this", "class", "is", "subclassing", "another", "Entity", "add", "that", "Entity", "s", "fields", ".", "Note", "that", "we", "loop", "over", "the", "bases", "in", "*", "reverse", "*", ".", "This", "is", "necessary", "in", "order", "to", "maintain"...
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L84-L97
proteanhq/protean
src/protean/core/entity.py
EntityBase._load_fields
def _load_fields(new_class, attrs): """Load field items into Class. This method sets up the primary attribute of an association. If Child class has defined an attribute so `parent = field.Reference(Parent)`, then `parent` is set up in this method, while `parent_id` is set up in `_set_up...
python
def _load_fields(new_class, attrs): """Load field items into Class. This method sets up the primary attribute of an association. If Child class has defined an attribute so `parent = field.Reference(Parent)`, then `parent` is set up in this method, while `parent_id` is set up in `_set_up...
[ "def", "_load_fields", "(", "new_class", ",", "attrs", ")", ":", "for", "attr_name", ",", "attr_obj", "in", "attrs", ".", "items", "(", ")", ":", "if", "isinstance", "(", "attr_obj", ",", "(", "Field", ",", "Reference", ")", ")", ":", "setattr", "(", ...
Load field items into Class. This method sets up the primary attribute of an association. If Child class has defined an attribute so `parent = field.Reference(Parent)`, then `parent` is set up in this method, while `parent_id` is set up in `_set_up_reference_fields()`.
[ "Load", "field", "items", "into", "Class", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L99-L109
proteanhq/protean
src/protean/core/entity.py
EntityBase._set_up_reference_fields
def _set_up_reference_fields(new_class): """Walk through relation fields and setup shadow attributes""" if new_class.meta_.declared_fields: for _, field in new_class.meta_.declared_fields.items(): if isinstance(field, Reference): shadow_field_name, shadow_...
python
def _set_up_reference_fields(new_class): """Walk through relation fields and setup shadow attributes""" if new_class.meta_.declared_fields: for _, field in new_class.meta_.declared_fields.items(): if isinstance(field, Reference): shadow_field_name, shadow_...
[ "def", "_set_up_reference_fields", "(", "new_class", ")", ":", "if", "new_class", ".", "meta_", ".", "declared_fields", ":", "for", "_", ",", "field", "in", "new_class", ".", "meta_", ".", "declared_fields", ".", "items", "(", ")", ":", "if", "isinstance", ...
Walk through relation fields and setup shadow attributes
[ "Walk", "through", "relation", "fields", "and", "setup", "shadow", "attributes" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L111-L118
proteanhq/protean
src/protean/core/entity.py
EntityBase._set_id_field
def _set_id_field(new_class): """Lookup the id field for this entity and assign""" # FIXME What does it mean when there are no declared fields? # Does it translate to an abstract entity? if new_class.meta_.declared_fields: try: new_class.meta_.id_field = nex...
python
def _set_id_field(new_class): """Lookup the id field for this entity and assign""" # FIXME What does it mean when there are no declared fields? # Does it translate to an abstract entity? if new_class.meta_.declared_fields: try: new_class.meta_.id_field = nex...
[ "def", "_set_id_field", "(", "new_class", ")", ":", "# FIXME What does it mean when there are no declared fields?", "# Does it translate to an abstract entity?", "if", "new_class", ".", "meta_", ".", "declared_fields", ":", "try", ":", "new_class", ".", "meta_", ".", "id_...
Lookup the id field for this entity and assign
[ "Lookup", "the", "id", "field", "for", "this", "entity", "and", "assign" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L120-L131
proteanhq/protean
src/protean/core/entity.py
EntityBase._create_id_field
def _create_id_field(new_class): """Create and return a default ID field that is Auto generated""" id_field = Auto(identifier=True) setattr(new_class, 'id', id_field) id_field.__set_name__(new_class, 'id') # Ensure ID field is updated properly in Meta attribute new_clas...
python
def _create_id_field(new_class): """Create and return a default ID field that is Auto generated""" id_field = Auto(identifier=True) setattr(new_class, 'id', id_field) id_field.__set_name__(new_class, 'id') # Ensure ID field is updated properly in Meta attribute new_clas...
[ "def", "_create_id_field", "(", "new_class", ")", ":", "id_field", "=", "Auto", "(", "identifier", "=", "True", ")", "setattr", "(", "new_class", ",", "'id'", ",", "id_field", ")", "id_field", ".", "__set_name__", "(", "new_class", ",", "'id'", ")", "# Ens...
Create and return a default ID field that is Auto generated
[ "Create", "and", "return", "a", "default", "ID", "field", "that", "is", "Auto", "generated" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L133-L142
proteanhq/protean
src/protean/core/entity.py
EntityBase._load_attributes
def _load_attributes(new_class): """Load list of attributes from declared fields""" for field_name, field_obj in new_class.meta_.declared_fields.items(): new_class.meta_.attributes[field_obj.get_attribute_name()] = field_obj
python
def _load_attributes(new_class): """Load list of attributes from declared fields""" for field_name, field_obj in new_class.meta_.declared_fields.items(): new_class.meta_.attributes[field_obj.get_attribute_name()] = field_obj
[ "def", "_load_attributes", "(", "new_class", ")", ":", "for", "field_name", ",", "field_obj", "in", "new_class", ".", "meta_", ".", "declared_fields", ".", "items", "(", ")", ":", "new_class", ".", "meta_", ".", "attributes", "[", "field_obj", ".", "get_attr...
Load list of attributes from declared fields
[ "Load", "list", "of", "attributes", "from", "declared", "fields" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L144-L147
proteanhq/protean
src/protean/core/entity.py
EntityMeta.unique_fields
def unique_fields(self): """ Return the unique fields for this entity """ return [(field_name, field_obj) for field_name, field_obj in self.declared_fields.items() if field_obj.unique]
python
def unique_fields(self): """ Return the unique fields for this entity """ return [(field_name, field_obj) for field_name, field_obj in self.declared_fields.items() if field_obj.unique]
[ "def", "unique_fields", "(", "self", ")", ":", "return", "[", "(", "field_name", ",", "field_obj", ")", "for", "field_name", ",", "field_obj", "in", "self", ".", "declared_fields", ".", "items", "(", ")", "if", "field_obj", ".", "unique", "]" ]
Return the unique fields for this entity
[ "Return", "the", "unique", "fields", "for", "this", "entity" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L189-L193
proteanhq/protean
src/protean/core/entity.py
Entity._update_data
def _update_data(self, *data_dict, **kwargs): """ A private method to process and update entity values correctly. :param data: A dictionary of values to be updated for the entity :param kwargs: keyword arguments with key-value pairs to be updated """ # Load each of the ...
python
def _update_data(self, *data_dict, **kwargs): """ A private method to process and update entity values correctly. :param data: A dictionary of values to be updated for the entity :param kwargs: keyword arguments with key-value pairs to be updated """ # Load each of the ...
[ "def", "_update_data", "(", "self", ",", "*", "data_dict", ",", "*", "*", "kwargs", ")", ":", "# Load each of the fields given in the data dictionary", "self", ".", "errors", "=", "{", "}", "for", "data", "in", "data_dict", ":", "if", "not", "isinstance", "(",...
A private method to process and update entity values correctly. :param data: A dictionary of values to be updated for the entity :param kwargs: keyword arguments with key-value pairs to be updated
[ "A", "private", "method", "to", "process", "and", "update", "entity", "values", "correctly", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L324-L351
proteanhq/protean
src/protean/core/entity.py
Entity.to_dict
def to_dict(self): """ Return entity data as a dictionary """ return {field_name: getattr(self, field_name, None) for field_name in self.meta_.declared_fields}
python
def to_dict(self): """ Return entity data as a dictionary """ return {field_name: getattr(self, field_name, None) for field_name in self.meta_.declared_fields}
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "field_name", ":", "getattr", "(", "self", ",", "field_name", ",", "None", ")", "for", "field_name", "in", "self", ".", "meta_", ".", "declared_fields", "}" ]
Return entity data as a dictionary
[ "Return", "entity", "data", "as", "a", "dictionary" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L353-L356
proteanhq/protean
src/protean/core/entity.py
Entity.clone
def clone(self): """Deepclone the entity, but reset state""" clone_copy = copy.deepcopy(self) clone_copy.state_ = EntityState() return clone_copy
python
def clone(self): """Deepclone the entity, but reset state""" clone_copy = copy.deepcopy(self) clone_copy.state_ = EntityState() return clone_copy
[ "def", "clone", "(", "self", ")", ":", "clone_copy", "=", "copy", ".", "deepcopy", "(", "self", ")", "clone_copy", ".", "state_", "=", "EntityState", "(", ")", "return", "clone_copy" ]
Deepclone the entity, but reset state
[ "Deepclone", "the", "entity", "but", "reset", "state" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L358-L363
proteanhq/protean
src/protean/core/entity.py
Entity.get
def get(cls, identifier: Any) -> 'Entity': """Get a specific Record from the Repository :param identifier: id of the record to be fetched from the repository. """ logger.debug(f'Lookup `{cls.__name__}` object with identifier {identifier}') # Get the ID field for the entity ...
python
def get(cls, identifier: Any) -> 'Entity': """Get a specific Record from the Repository :param identifier: id of the record to be fetched from the repository. """ logger.debug(f'Lookup `{cls.__name__}` object with identifier {identifier}') # Get the ID field for the entity ...
[ "def", "get", "(", "cls", ",", "identifier", ":", "Any", ")", "->", "'Entity'", ":", "logger", ".", "debug", "(", "f'Lookup `{cls.__name__}` object with identifier {identifier}'", ")", "# Get the ID field for the entity", "filters", "=", "{", "cls", ".", "meta_", "....
Get a specific Record from the Repository :param identifier: id of the record to be fetched from the repository.
[ "Get", "a", "specific", "Record", "from", "the", "Repository" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L370-L389
proteanhq/protean
src/protean/core/entity.py
Entity.reload
def reload(self) -> None: """Reload Entity from the repository""" if not self.state_.is_persisted or self.state_.is_changed: raise InvalidStateError(f'`{self.__class__.__name__}` object is in invalid state') # Retrieve the entity's ID by the configured Identifier field ident...
python
def reload(self) -> None: """Reload Entity from the repository""" if not self.state_.is_persisted or self.state_.is_changed: raise InvalidStateError(f'`{self.__class__.__name__}` object is in invalid state') # Retrieve the entity's ID by the configured Identifier field ident...
[ "def", "reload", "(", "self", ")", "->", "None", ":", "if", "not", "self", ".", "state_", ".", "is_persisted", "or", "self", ".", "state_", ".", "is_changed", ":", "raise", "InvalidStateError", "(", "f'`{self.__class__.__name__}` object is in invalid state'", ")",...
Reload Entity from the repository
[ "Reload", "Entity", "from", "the", "repository" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L391-L406
proteanhq/protean
src/protean/core/entity.py
Entity.find_by
def find_by(cls, **kwargs) -> 'Entity': """Find a specific entity record that matches one or more criteria. :param kwargs: named arguments consisting of attr_name and attr_value pairs to search on """ logger.debug(f'Lookup `{cls.__name__}` object with values ' f'{kw...
python
def find_by(cls, **kwargs) -> 'Entity': """Find a specific entity record that matches one or more criteria. :param kwargs: named arguments consisting of attr_name and attr_value pairs to search on """ logger.debug(f'Lookup `{cls.__name__}` object with values ' f'{kw...
[ "def", "find_by", "(", "cls", ",", "*", "*", "kwargs", ")", "->", "'Entity'", ":", "logger", ".", "debug", "(", "f'Lookup `{cls.__name__}` object with values '", "f'{kwargs}'", ")", "# Find this item in the repository or raise Error", "results", "=", "cls", ".", "quer...
Find a specific entity record that matches one or more criteria. :param kwargs: named arguments consisting of attr_name and attr_value pairs to search on
[ "Find", "a", "specific", "entity", "record", "that", "matches", "one", "or", "more", "criteria", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L409-L426
proteanhq/protean
src/protean/core/entity.py
Entity.exists
def exists(cls, excludes_, **filters): """ Return `True` if objects matching the provided filters and excludes exist if not return false. Calls the `filter` method by default, but can be overridden for better and quicker implementations that may be supported by a database. ...
python
def exists(cls, excludes_, **filters): """ Return `True` if objects matching the provided filters and excludes exist if not return false. Calls the `filter` method by default, but can be overridden for better and quicker implementations that may be supported by a database. ...
[ "def", "exists", "(", "cls", ",", "excludes_", ",", "*", "*", "filters", ")", ":", "results", "=", "cls", ".", "query", ".", "filter", "(", "*", "*", "filters", ")", ".", "exclude", "(", "*", "*", "excludes_", ")", "return", "bool", "(", "results",...
Return `True` if objects matching the provided filters and excludes exist if not return false. Calls the `filter` method by default, but can be overridden for better and quicker implementations that may be supported by a database. :param excludes_: entities without this combination...
[ "Return", "True", "if", "objects", "matching", "the", "provided", "filters", "and", "excludes", "exist", "if", "not", "return", "false", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L429-L440
proteanhq/protean
src/protean/core/entity.py
Entity.create
def create(cls, *args, **kwargs) -> 'Entity': """Create a new record in the repository. Also performs unique validations before creating the entity :param args: positional arguments for the entity :param kwargs: keyword arguments for the entity """ logger.debug( ...
python
def create(cls, *args, **kwargs) -> 'Entity': """Create a new record in the repository. Also performs unique validations before creating the entity :param args: positional arguments for the entity :param kwargs: keyword arguments for the entity """ logger.debug( ...
[ "def", "create", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "'Entity'", ":", "logger", ".", "debug", "(", "f'Creating new `{cls.__name__}` object using data {kwargs}'", ")", "model_cls", "=", "repo_factory", ".", "get_model", "(", "cls", ...
Create a new record in the repository. Also performs unique validations before creating the entity :param args: positional arguments for the entity :param kwargs: keyword arguments for the entity
[ "Create", "a", "new", "record", "in", "the", "repository", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L443-L489
proteanhq/protean
src/protean/core/entity.py
Entity.save
def save(self): """Save a new Entity into repository. Performs unique validations before creating the entity. """ logger.debug( f'Saving `{self.__class__.__name__}` object') # Fetch Model class and connected repository from Repository Factory model_cls = rep...
python
def save(self): """Save a new Entity into repository. Performs unique validations before creating the entity. """ logger.debug( f'Saving `{self.__class__.__name__}` object') # Fetch Model class and connected repository from Repository Factory model_cls = rep...
[ "def", "save", "(", "self", ")", ":", "logger", ".", "debug", "(", "f'Saving `{self.__class__.__name__}` object'", ")", "# Fetch Model class and connected repository from Repository Factory", "model_cls", "=", "repo_factory", ".", "get_model", "(", "self", ".", "__class__",...
Save a new Entity into repository. Performs unique validations before creating the entity.
[ "Save", "a", "new", "Entity", "into", "repository", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L491-L531
proteanhq/protean
src/protean/core/entity.py
Entity.update
def update(self, *data, **kwargs) -> 'Entity': """Update a Record in the repository. Also performs unique validations before creating the entity. Supports both dictionary and keyword argument updates to the entity:: dog.update({'age': 10}) dog.update(age=10) ...
python
def update(self, *data, **kwargs) -> 'Entity': """Update a Record in the repository. Also performs unique validations before creating the entity. Supports both dictionary and keyword argument updates to the entity:: dog.update({'age': 10}) dog.update(age=10) ...
[ "def", "update", "(", "self", ",", "*", "data", ",", "*", "*", "kwargs", ")", "->", "'Entity'", ":", "logger", ".", "debug", "(", "f'Updating existing `{self.__class__.__name__}` object with id {self.id}'", ")", "# Fetch Model class and connected repository from Repository ...
Update a Record in the repository. Also performs unique validations before creating the entity. Supports both dictionary and keyword argument updates to the entity:: dog.update({'age': 10}) dog.update(age=10) :param data: Dictionary of values to be updated for the en...
[ "Update", "a", "Record", "in", "the", "repository", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L533-L574
proteanhq/protean
src/protean/core/entity.py
Entity._validate_unique
def _validate_unique(self, create=True): """ Validate the unique constraints for the entity """ # Build the filters from the unique constraints filters, excludes = {}, {} for field_name, field_obj in self.meta_.unique_fields: lookup_value = getattr(self, field_name, None) ...
python
def _validate_unique(self, create=True): """ Validate the unique constraints for the entity """ # Build the filters from the unique constraints filters, excludes = {}, {} for field_name, field_obj in self.meta_.unique_fields: lookup_value = getattr(self, field_name, None) ...
[ "def", "_validate_unique", "(", "self", ",", "create", "=", "True", ")", ":", "# Build the filters from the unique constraints", "filters", ",", "excludes", "=", "{", "}", ",", "{", "}", "for", "field_name", ",", "field_obj", "in", "self", ".", "meta_", ".", ...
Validate the unique constraints for the entity
[ "Validate", "the", "unique", "constraints", "for", "the", "entity" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L576-L598
proteanhq/protean
src/protean/core/entity.py
Entity.delete
def delete(self): """Delete a Record from the Repository will perform callbacks and run validations before deletion. Throws ObjectNotFoundError if the object was not found in the repository. """ # Fetch Model class and connected repository from Repository Factory model_...
python
def delete(self): """Delete a Record from the Repository will perform callbacks and run validations before deletion. Throws ObjectNotFoundError if the object was not found in the repository. """ # Fetch Model class and connected repository from Repository Factory model_...
[ "def", "delete", "(", "self", ")", ":", "# Fetch Model class and connected repository from Repository Factory", "model_cls", "=", "repo_factory", ".", "get_model", "(", "self", ".", "__class__", ")", "repository", "=", "repo_factory", ".", "get_repository", "(", "self",...
Delete a Record from the Repository will perform callbacks and run validations before deletion. Throws ObjectNotFoundError if the object was not found in the repository.
[ "Delete", "a", "Record", "from", "the", "Repository" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L600-L622
deep-compute/deeputil
deeputil/streamcounter.py
StreamCounter.add
def add(self, item, count=1): ''' When we receive stream of data, we add them in the chunk which has limit on the no. of items that it will store. >>> s = StreamCounter(5,5) >>> data_stream = ['a','b','c','d'] >>> for item in data_stream: ... s.add(item) ...
python
def add(self, item, count=1): ''' When we receive stream of data, we add them in the chunk which has limit on the no. of items that it will store. >>> s = StreamCounter(5,5) >>> data_stream = ['a','b','c','d'] >>> for item in data_stream: ... s.add(item) ...
[ "def", "add", "(", "self", ",", "item", ",", "count", "=", "1", ")", ":", "self", ".", "n_items_seen", "+=", "count", "self", ".", "n_chunk_items_seen", "+=", "count", "# get current chunk", "chunk_id", "=", "self", ".", "n_chunks", "chunk", "=", "self", ...
When we receive stream of data, we add them in the chunk which has limit on the no. of items that it will store. >>> s = StreamCounter(5,5) >>> data_stream = ['a','b','c','d'] >>> for item in data_stream: ... s.add(item) >>> s.chunk_size 5 >>> s.n_item...
[ "When", "we", "receive", "stream", "of", "data", "we", "add", "them", "in", "the", "chunk", "which", "has", "limit", "on", "the", "no", ".", "of", "items", "that", "it", "will", "store", ".", ">>>", "s", "=", "StreamCounter", "(", "5", "5", ")", ">...
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/streamcounter.py#L47-L105
deep-compute/deeputil
deeputil/streamcounter.py
StreamCounter._drop_oldest_chunk
def _drop_oldest_chunk(self): ''' To handle the case when the items comming in the chunk is more than the maximum capacity of the chunk. Our intent behind is to remove the oldest chunk. So that the items come flowing in. >>> s = StreamCounter(5,5) >>> data_stream ...
python
def _drop_oldest_chunk(self): ''' To handle the case when the items comming in the chunk is more than the maximum capacity of the chunk. Our intent behind is to remove the oldest chunk. So that the items come flowing in. >>> s = StreamCounter(5,5) >>> data_stream ...
[ "def", "_drop_oldest_chunk", "(", "self", ")", ":", "chunk_id", "=", "min", "(", "self", ".", "chunked_counts", ".", "keys", "(", ")", ")", "chunk", "=", "self", ".", "chunked_counts", ".", "pop", "(", "chunk_id", ")", "self", ".", "n_counts", "-=", "l...
To handle the case when the items comming in the chunk is more than the maximum capacity of the chunk. Our intent behind is to remove the oldest chunk. So that the items come flowing in. >>> s = StreamCounter(5,5) >>> data_stream = ['a','b','c','d'] >>> for item in data_s...
[ "To", "handle", "the", "case", "when", "the", "items", "comming", "in", "the", "chunk", "is", "more", "than", "the", "maximum", "capacity", "of", "the", "chunk", ".", "Our", "intent", "behind", "is", "to", "remove", "the", "oldest", "chunk", ".", "So", ...
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/streamcounter.py#L107-L135
deep-compute/deeputil
deeputil/streamcounter.py
StreamCounter.get
def get(self, item, default=0, normalized=False): ''' When we have the stream of data pushed in the chunk we can retrive count of an item using this method. >>> stream_counter_obj = StreamCounter(5,5) >>> data_stream = ['a','b','c'] >>> for item in data_stream: .....
python
def get(self, item, default=0, normalized=False): ''' When we have the stream of data pushed in the chunk we can retrive count of an item using this method. >>> stream_counter_obj = StreamCounter(5,5) >>> data_stream = ['a','b','c'] >>> for item in data_stream: .....
[ "def", "get", "(", "self", ",", "item", ",", "default", "=", "0", ",", "normalized", "=", "False", ")", ":", "c", "=", "self", ".", "counts", ".", "get", "(", "item", ",", "default", ")", "if", "not", "normalized", ":", "return", "c", "return", "...
When we have the stream of data pushed in the chunk we can retrive count of an item using this method. >>> stream_counter_obj = StreamCounter(5,5) >>> data_stream = ['a','b','c'] >>> for item in data_stream: ... stream_counter_obj.add(item) >>> stream_counter_obj.get(...
[ "When", "we", "have", "the", "stream", "of", "data", "pushed", "in", "the", "chunk", "we", "can", "retrive", "count", "of", "an", "item", "using", "this", "method", ".", ">>>", "stream_counter_obj", "=", "StreamCounter", "(", "5", "5", ")", ">>>", "data_...
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/streamcounter.py#L137-L173
proteanhq/protean
src/protean/services/email/message.py
EmailMessage.message
def message(self): """ Convert the message to a mime compliant email string """ return '\n'.join( [self.from_email, str(self.to), self.subject, self.body])
python
def message(self): """ Convert the message to a mime compliant email string """ return '\n'.join( [self.from_email, str(self.to), self.subject, self.body])
[ "def", "message", "(", "self", ")", ":", "return", "'\\n'", ".", "join", "(", "[", "self", ".", "from_email", ",", "str", "(", "self", ".", "to", ")", ",", "self", ".", "subject", ",", "self", ".", "body", "]", ")" ]
Convert the message to a mime compliant email string
[ "Convert", "the", "message", "to", "a", "mime", "compliant", "email", "string" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/services/email/message.py#L44-L47
proteanhq/protean
src/protean/services/email/message.py
EmailMessage.recipients
def recipients(self): """ Return a list of all recipients of the email (includes direct addressees as well as Cc and Bcc entries). """ return [email for email in (self.to + self.cc + self.bcc) if email]
python
def recipients(self): """ Return a list of all recipients of the email (includes direct addressees as well as Cc and Bcc entries). """ return [email for email in (self.to + self.cc + self.bcc) if email]
[ "def", "recipients", "(", "self", ")", ":", "return", "[", "email", "for", "email", "in", "(", "self", ".", "to", "+", "self", ".", "cc", "+", "self", ".", "bcc", ")", "if", "email", "]" ]
Return a list of all recipients of the email (includes direct addressees as well as Cc and Bcc entries).
[ "Return", "a", "list", "of", "all", "recipients", "of", "the", "email", "(", "includes", "direct", "addressees", "as", "well", "as", "Cc", "and", "Bcc", "entries", ")", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/services/email/message.py#L49-L54
proteanhq/protean
src/protean/services/email/message.py
EmailMessage.get_connection
def get_connection(self, fail_silently=False): """Retrieve connection to send email""" from protean.services.email import get_connection if not self.connection: self.connection = get_connection(fail_silently=fail_silently) return self.connection
python
def get_connection(self, fail_silently=False): """Retrieve connection to send email""" from protean.services.email import get_connection if not self.connection: self.connection = get_connection(fail_silently=fail_silently) return self.connection
[ "def", "get_connection", "(", "self", ",", "fail_silently", "=", "False", ")", ":", "from", "protean", ".", "services", ".", "email", "import", "get_connection", "if", "not", "self", ".", "connection", ":", "self", ".", "connection", "=", "get_connection", "...
Retrieve connection to send email
[ "Retrieve", "connection", "to", "send", "email" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/services/email/message.py#L56-L63
proteanhq/protean
src/protean/services/email/message.py
EmailMessage.send
def send(self, fail_silently=False): """Send the email message.""" if not self.recipients(): # Don't bother creating the network connection if # there's nobody to send to. return 0 return self.get_connection(fail_silently).send_messages([self])
python
def send(self, fail_silently=False): """Send the email message.""" if not self.recipients(): # Don't bother creating the network connection if # there's nobody to send to. return 0 return self.get_connection(fail_silently).send_messages([self])
[ "def", "send", "(", "self", ",", "fail_silently", "=", "False", ")", ":", "if", "not", "self", ".", "recipients", "(", ")", ":", "# Don't bother creating the network connection if", "# there's nobody to send to.", "return", "0", "return", "self", ".", "get_connectio...
Send the email message.
[ "Send", "the", "email", "message", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/services/email/message.py#L65-L71
wasp/waspy
waspy/router.py
Router.add_static_route
def add_static_route(self, method: Union[str, Methods], route: str, handler: Callable, skip_middleware=False): """ Adds a static route. A static route is a special route that doesnt follow any of the normal rules, and never has any path parameters. Ideall...
python
def add_static_route(self, method: Union[str, Methods], route: str, handler: Callable, skip_middleware=False): """ Adds a static route. A static route is a special route that doesnt follow any of the normal rules, and never has any path parameters. Ideall...
[ "def", "add_static_route", "(", "self", ",", "method", ":", "Union", "[", "str", ",", "Methods", "]", ",", "route", ":", "str", ",", "handler", ":", "Callable", ",", "skip_middleware", "=", "False", ")", ":", "if", "isinstance", "(", "method", ",", "st...
Adds a static route. A static route is a special route that doesnt follow any of the normal rules, and never has any path parameters. Ideally, this is used for non-public facing endpoints such as "/healthcheck", or "/stats" or something of that nature. All static routes SKIP mid...
[ "Adds", "a", "static", "route", ".", "A", "static", "route", "is", "a", "special", "route", "that", "doesnt", "follow", "any", "of", "the", "normal", "rules", "and", "never", "has", "any", "path", "parameters", ".", "Ideally", "this", "is", "used", "for"...
train
https://github.com/wasp/waspy/blob/31cc352f300a089f9607d7f13d93591d4c69d5ec/waspy/router.py#L134-L151
wasp/waspy
waspy/router.py
Router.prefix
def prefix(self, prefix): """ Adds a prefix to routes contained within. """ original_prefix = self._prefix self._prefix += prefix yield self self._prefix = original_prefix
python
def prefix(self, prefix): """ Adds a prefix to routes contained within. """ original_prefix = self._prefix self._prefix += prefix yield self self._prefix = original_prefix
[ "def", "prefix", "(", "self", ",", "prefix", ")", ":", "original_prefix", "=", "self", ".", "_prefix", "self", ".", "_prefix", "+=", "prefix", "yield", "self", "self", ".", "_prefix", "=", "original_prefix" ]
Adds a prefix to routes contained within.
[ "Adds", "a", "prefix", "to", "routes", "contained", "within", "." ]
train
https://github.com/wasp/waspy/blob/31cc352f300a089f9607d7f13d93591d4c69d5ec/waspy/router.py#L239-L246
proteanhq/protean
src/protean/core/exceptions.py
ValidationError.normalized_messages
def normalized_messages(self, no_field_name='_entity'): """Return all the error messages as a dictionary""" if isinstance(self.messages, dict): return self.messages if not self.field_names: return {no_field_name: self.messages} return dict((name, self.messages) f...
python
def normalized_messages(self, no_field_name='_entity'): """Return all the error messages as a dictionary""" if isinstance(self.messages, dict): return self.messages if not self.field_names: return {no_field_name: self.messages} return dict((name, self.messages) f...
[ "def", "normalized_messages", "(", "self", ",", "no_field_name", "=", "'_entity'", ")", ":", "if", "isinstance", "(", "self", ".", "messages", ",", "dict", ")", ":", "return", "self", ".", "messages", "if", "not", "self", ".", "field_names", ":", "return",...
Return all the error messages as a dictionary
[ "Return", "all", "the", "error", "messages", "as", "a", "dictionary" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/exceptions.py#L52-L59
deep-compute/deeputil
deeputil/misc.py
generate_random_string
def generate_random_string(length=6): ''' Returns a random string of a specified length. >>> len(generate_random_string(length=25)) 25 Test randomness. Try N times and observe no duplicaton >>> N = 100 >>> len(set(generate_random_string(10) for i in range(N))) == N True ''' n =...
python
def generate_random_string(length=6): ''' Returns a random string of a specified length. >>> len(generate_random_string(length=25)) 25 Test randomness. Try N times and observe no duplicaton >>> N = 100 >>> len(set(generate_random_string(10) for i in range(N))) == N True ''' n =...
[ "def", "generate_random_string", "(", "length", "=", "6", ")", ":", "n", "=", "int", "(", "length", "/", "2", "+", "1", ")", "x", "=", "binascii", ".", "hexlify", "(", "os", ".", "urandom", "(", "n", ")", ")", "s", "=", "x", "[", ":", "length",...
Returns a random string of a specified length. >>> len(generate_random_string(length=25)) 25 Test randomness. Try N times and observe no duplicaton >>> N = 100 >>> len(set(generate_random_string(10) for i in range(N))) == N True
[ "Returns", "a", "random", "string", "of", "a", "specified", "length", "." ]
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L16-L31
deep-compute/deeputil
deeputil/misc.py
get_timestamp
def get_timestamp(dt=None): ''' Return current timestamp if @dt is None else return timestamp of @dt. >>> t = datetime.datetime(2015, 0o5, 21) >>> get_timestamp(t) 1432166400 ''' if dt is None: dt = datetime.datetime.utcnow() t = dt.utctimetuple() return calendar.timegm(t)
python
def get_timestamp(dt=None): ''' Return current timestamp if @dt is None else return timestamp of @dt. >>> t = datetime.datetime(2015, 0o5, 21) >>> get_timestamp(t) 1432166400 ''' if dt is None: dt = datetime.datetime.utcnow() t = dt.utctimetuple() return calendar.timegm(t)
[ "def", "get_timestamp", "(", "dt", "=", "None", ")", ":", "if", "dt", "is", "None", ":", "dt", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "t", "=", "dt", ".", "utctimetuple", "(", ")", "return", "calendar", ".", "timegm", "(", "t", ...
Return current timestamp if @dt is None else return timestamp of @dt. >>> t = datetime.datetime(2015, 0o5, 21) >>> get_timestamp(t) 1432166400
[ "Return", "current", "timestamp", "if", "@dt", "is", "None", "else", "return", "timestamp", "of", "@dt", "." ]
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L33-L46
deep-compute/deeputil
deeputil/misc.py
get_datetime
def get_datetime(epoch): ''' get datetime from an epoch timestamp >>> get_datetime(1432188772) datetime.datetime(2015, 5, 21, 6, 12, 52) ''' t = time.gmtime(epoch) dt = datetime.datetime(*t[:6]) return dt
python
def get_datetime(epoch): ''' get datetime from an epoch timestamp >>> get_datetime(1432188772) datetime.datetime(2015, 5, 21, 6, 12, 52) ''' t = time.gmtime(epoch) dt = datetime.datetime(*t[:6]) return dt
[ "def", "get_datetime", "(", "epoch", ")", ":", "t", "=", "time", ".", "gmtime", "(", "epoch", ")", "dt", "=", "datetime", ".", "datetime", "(", "*", "t", "[", ":", "6", "]", ")", "return", "dt" ]
get datetime from an epoch timestamp >>> get_datetime(1432188772) datetime.datetime(2015, 5, 21, 6, 12, 52)
[ "get", "datetime", "from", "an", "epoch", "timestamp" ]
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L48-L59
deep-compute/deeputil
deeputil/misc.py
convert_ts
def convert_ts(tt): ''' tt: time.struct_time(tm_year=2012, tm_mon=10, tm_mday=23, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=297, tm_isdst=-1) >>> tt = time.strptime("23.10.2012", "%d.%m.%Y") >>> convert_ts(tt) 1350950400 tt: time.struct_time(tm_year=1513, tm_mon=1, tm_mday=1, tm_ho...
python
def convert_ts(tt): ''' tt: time.struct_time(tm_year=2012, tm_mon=10, tm_mday=23, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=297, tm_isdst=-1) >>> tt = time.strptime("23.10.2012", "%d.%m.%Y") >>> convert_ts(tt) 1350950400 tt: time.struct_time(tm_year=1513, tm_mon=1, tm_mday=1, tm_ho...
[ "def", "convert_ts", "(", "tt", ")", ":", "try", ":", "ts", "=", "calendar", ".", "timegm", "(", "tt", ")", "'''\n As from the github issue https://github.com/prashanthellina/rsslurp/issues/680,\n there are some cases where we might get timestamp in negative values, so ...
tt: time.struct_time(tm_year=2012, tm_mon=10, tm_mday=23, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=297, tm_isdst=-1) >>> tt = time.strptime("23.10.2012", "%d.%m.%Y") >>> convert_ts(tt) 1350950400 tt: time.struct_time(tm_year=1513, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm...
[ "tt", ":", "time", ".", "struct_time", "(", "tm_year", "=", "2012", "tm_mon", "=", "10", "tm_mday", "=", "23", "tm_hour", "=", "0", "tm_min", "=", "0", "tm_sec", "=", "0", "tm_wday", "=", "1", "tm_yday", "=", "297", "tm_isdst", "=", "-", "1", ")" ]
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L61-L90
deep-compute/deeputil
deeputil/misc.py
xcode
def xcode(text, encoding='utf8', mode='ignore'): ''' Converts unicode encoding to str >>> xcode(b'hello') b'hello' >>> xcode('hello') b'hello' ''' return text.encode(encoding, mode) if isinstance(text, str) else text
python
def xcode(text, encoding='utf8', mode='ignore'): ''' Converts unicode encoding to str >>> xcode(b'hello') b'hello' >>> xcode('hello') b'hello' ''' return text.encode(encoding, mode) if isinstance(text, str) else text
[ "def", "xcode", "(", "text", ",", "encoding", "=", "'utf8'", ",", "mode", "=", "'ignore'", ")", ":", "return", "text", ".", "encode", "(", "encoding", ",", "mode", ")", "if", "isinstance", "(", "text", ",", "str", ")", "else", "text" ]
Converts unicode encoding to str >>> xcode(b'hello') b'hello' >>> xcode('hello') b'hello'
[ "Converts", "unicode", "encoding", "to", "str" ]
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L93-L102
deep-compute/deeputil
deeputil/misc.py
parse_location
def parse_location(loc, default_port): ''' loc can be of the format http://<ip/domain>[:<port>] eg: http://localhost:8888 http://localhost/ return ip (str), port (int) >>> parse_location('http://localhost/', 6379) ('localhost', 6379) >>> parse_location('http://localhost:8888'...
python
def parse_location(loc, default_port): ''' loc can be of the format http://<ip/domain>[:<port>] eg: http://localhost:8888 http://localhost/ return ip (str), port (int) >>> parse_location('http://localhost/', 6379) ('localhost', 6379) >>> parse_location('http://localhost:8888'...
[ "def", "parse_location", "(", "loc", ",", "default_port", ")", ":", "parsed", "=", "urlparse", "(", "loc", ")", "if", "':'", "in", "parsed", ".", "netloc", ":", "ip", ",", "port", "=", "parsed", ".", "netloc", ".", "split", "(", "':'", ")", "port", ...
loc can be of the format http://<ip/domain>[:<port>] eg: http://localhost:8888 http://localhost/ return ip (str), port (int) >>> parse_location('http://localhost/', 6379) ('localhost', 6379) >>> parse_location('http://localhost:8888', 6379) ('localhost', 8888)
[ "loc", "can", "be", "of", "the", "format", "http", ":", "//", "<ip", "/", "domain", ">", "[", ":", "<port", ">", "]", "eg", ":", "http", ":", "//", "localhost", ":", "8888", "http", ":", "//", "localhost", "/", "return", "ip", "(", "str", ")", ...
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L111-L132
deep-compute/deeputil
deeputil/misc.py
serialize_dict_keys
def serialize_dict_keys(d, prefix=""): """returns all the keys in nested a dictionary. >>> sorted(serialize_dict_keys({"a": {"b": {"c": 1, "b": 2} } })) ['a', 'a.b', 'a.b.b', 'a.b.c'] """ keys = [] for k, v in d.items(): fqk = '{}{}'.format(prefix, k) keys.append(fqk) if ...
python
def serialize_dict_keys(d, prefix=""): """returns all the keys in nested a dictionary. >>> sorted(serialize_dict_keys({"a": {"b": {"c": 1, "b": 2} } })) ['a', 'a.b', 'a.b.b', 'a.b.c'] """ keys = [] for k, v in d.items(): fqk = '{}{}'.format(prefix, k) keys.append(fqk) if ...
[ "def", "serialize_dict_keys", "(", "d", ",", "prefix", "=", "\"\"", ")", ":", "keys", "=", "[", "]", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "fqk", "=", "'{}{}'", ".", "format", "(", "prefix", ",", "k", ")", "keys", ".", ...
returns all the keys in nested a dictionary. >>> sorted(serialize_dict_keys({"a": {"b": {"c": 1, "b": 2} } })) ['a', 'a.b', 'a.b.b', 'a.b.c']
[ "returns", "all", "the", "keys", "in", "nested", "a", "dictionary", ".", ">>>", "sorted", "(", "serialize_dict_keys", "(", "{", "a", ":", "{", "b", ":", "{", "c", ":", "1", "b", ":", "2", "}", "}", "}", "))", "[", "a", "a", ".", "b", "a", "."...
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L172-L184
deep-compute/deeputil
deeputil/misc.py
flatten_dict
def flatten_dict(d, parent_key='', sep='.', ignore_under_prefixed=True, mark_value=True): ''' Flattens a nested dictionary >>> from pprint import pprint >>> d = {"a": {"b": {"c": 1, "b": 2, "__d": 'ignore', "_e": "mark"} } } >>> fd = flatten_dict(d...
python
def flatten_dict(d, parent_key='', sep='.', ignore_under_prefixed=True, mark_value=True): ''' Flattens a nested dictionary >>> from pprint import pprint >>> d = {"a": {"b": {"c": 1, "b": 2, "__d": 'ignore', "_e": "mark"} } } >>> fd = flatten_dict(d...
[ "def", "flatten_dict", "(", "d", ",", "parent_key", "=", "''", ",", "sep", "=", "'.'", ",", "ignore_under_prefixed", "=", "True", ",", "mark_value", "=", "True", ")", ":", "items", "=", "{", "}", "for", "k", "in", "d", ":", "if", "ignore_under_prefixed...
Flattens a nested dictionary >>> from pprint import pprint >>> d = {"a": {"b": {"c": 1, "b": 2, "__d": 'ignore', "_e": "mark"} } } >>> fd = flatten_dict(d) >>> pprint(fd) {'a.b._e': "'mark'", 'a.b.b': 2, 'a.b.c': 1}
[ "Flattens", "a", "nested", "dictionary" ]
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L192-L221
deep-compute/deeputil
deeputil/misc.py
deepgetattr
def deepgetattr(obj, attr, default=AttributeError): """ Recurses through an attribute chain to get the ultimate value (obj/data/member/value) from: http://pingfive.typepad.com/blog/2010/04/deep-getattr-python-function.html >>> class Universe(object): ... def __init__(self, galaxy): ... ...
python
def deepgetattr(obj, attr, default=AttributeError): """ Recurses through an attribute chain to get the ultimate value (obj/data/member/value) from: http://pingfive.typepad.com/blog/2010/04/deep-getattr-python-function.html >>> class Universe(object): ... def __init__(self, galaxy): ... ...
[ "def", "deepgetattr", "(", "obj", ",", "attr", ",", "default", "=", "AttributeError", ")", ":", "try", ":", "return", "reduce", "(", "getattr", ",", "attr", ".", "split", "(", "'.'", ")", ",", "obj", ")", "except", "AttributeError", ":", "if", "default...
Recurses through an attribute chain to get the ultimate value (obj/data/member/value) from: http://pingfive.typepad.com/blog/2010/04/deep-getattr-python-function.html >>> class Universe(object): ... def __init__(self, galaxy): ... self.galaxy = galaxy ... >>> class Galaxy(objec...
[ "Recurses", "through", "an", "attribute", "chain", "to", "get", "the", "ultimate", "value", "(", "obj", "/", "data", "/", "member", "/", "value", ")", "from", ":", "http", ":", "//", "pingfive", ".", "typepad", ".", "com", "/", "blog", "/", "2010", "...
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L223-L259
deep-compute/deeputil
deeputil/misc.py
set_file_limits
def set_file_limits(n): ''' Set the limit on number of file descriptors that this process can open. ''' try: resource.setrlimit(resource.RLIMIT_NOFILE, (n, n)) return True except ValueError: return False
python
def set_file_limits(n): ''' Set the limit on number of file descriptors that this process can open. ''' try: resource.setrlimit(resource.RLIMIT_NOFILE, (n, n)) return True except ValueError: return False
[ "def", "set_file_limits", "(", "n", ")", ":", "try", ":", "resource", ".", "setrlimit", "(", "resource", ".", "RLIMIT_NOFILE", ",", "(", "n", ",", "n", ")", ")", "return", "True", "except", "ValueError", ":", "return", "False" ]
Set the limit on number of file descriptors that this process can open.
[ "Set", "the", "limit", "on", "number", "of", "file", "descriptors", "that", "this", "process", "can", "open", "." ]
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L473-L484
deep-compute/deeputil
deeputil/misc.py
memoize
def memoize(f): ''' Caches result of a function From: https://goo.gl/aXt4Qy >>> import time >>> @memoize ... def test(msg): ... # Processing for result that takes time ... time.sleep(1) ... return msg >>> >>> for i in range(5): ... start = time.time(...
python
def memoize(f): ''' Caches result of a function From: https://goo.gl/aXt4Qy >>> import time >>> @memoize ... def test(msg): ... # Processing for result that takes time ... time.sleep(1) ... return msg >>> >>> for i in range(5): ... start = time.time(...
[ "def", "memoize", "(", "f", ")", ":", "class", "memodict", "(", "dict", ")", ":", "@", "wraps", "(", "f", ")", "def", "__getitem__", "(", "self", ",", "*", "args", ")", ":", "return", "super", "(", "memodict", ",", "self", ")", ".", "__getitem__", ...
Caches result of a function From: https://goo.gl/aXt4Qy >>> import time >>> @memoize ... def test(msg): ... # Processing for result that takes time ... time.sleep(1) ... return msg >>> >>> for i in range(5): ... start = time.time() ... test('calling ...
[ "Caches", "result", "of", "a", "function", "From", ":", "https", ":", "//", "goo", ".", "gl", "/", "aXt4Qy" ]
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L546-L588
deep-compute/deeputil
deeputil/misc.py
load_object
def load_object(imp_path): ''' Given a python import path, load the object For dynamic imports in a program >>> isdir = load_object('os.path.isdir') >>> isdir('/tmp') True >>> num = load_object('numbers.Number') >>> isinstance('x', num) False >>> isinstance(777, num) True ...
python
def load_object(imp_path): ''' Given a python import path, load the object For dynamic imports in a program >>> isdir = load_object('os.path.isdir') >>> isdir('/tmp') True >>> num = load_object('numbers.Number') >>> isinstance('x', num) False >>> isinstance(777, num) True ...
[ "def", "load_object", "(", "imp_path", ")", ":", "module_name", ",", "obj_name", "=", "imp_path", ".", "split", "(", "'.'", ",", "1", ")", "module", "=", "__import__", "(", "module_name", ")", "obj", "=", "attrgetter", "(", "obj_name", ")", "(", "module"...
Given a python import path, load the object For dynamic imports in a program >>> isdir = load_object('os.path.isdir') >>> isdir('/tmp') True >>> num = load_object('numbers.Number') >>> isinstance('x', num) False >>> isinstance(777, num) True
[ "Given", "a", "python", "import", "path", "load", "the", "object", "For", "dynamic", "imports", "in", "a", "program" ]
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L592-L611
proteanhq/protean
src/protean/core/field/base.py
Field.fail
def fail(self, key, **kwargs): """A helper method that simply raises a `ValidationError`. """ try: msg = self.error_messages[key] except KeyError: class_name = self.__class__.__name__ msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, ...
python
def fail(self, key, **kwargs): """A helper method that simply raises a `ValidationError`. """ try: msg = self.error_messages[key] except KeyError: class_name = self.__class__.__name__ msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, ...
[ "def", "fail", "(", "self", ",", "key", ",", "*", "*", "kwargs", ")", ":", "try", ":", "msg", "=", "self", ".", "error_messages", "[", "key", "]", "except", "KeyError", ":", "class_name", "=", "self", ".", "__class__", ".", "__name__", "msg", "=", ...
A helper method that simply raises a `ValidationError`.
[ "A", "helper", "method", "that", "simply", "raises", "a", "ValidationError", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/base.py#L118-L130
proteanhq/protean
src/protean/core/field/base.py
Field._run_validators
def _run_validators(self, value): """Perform validation on ``value``. Raise a :exc:`ValidationError` if validation does not succeed. """ if value in self.empty_values: return errors = [] for validator in self.validators: try: valid...
python
def _run_validators(self, value): """Perform validation on ``value``. Raise a :exc:`ValidationError` if validation does not succeed. """ if value in self.empty_values: return errors = [] for validator in self.validators: try: valid...
[ "def", "_run_validators", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "errors", "=", "[", "]", "for", "validator", "in", "self", ".", "validators", ":", "try", ":", "validator", "(", "value", ")...
Perform validation on ``value``. Raise a :exc:`ValidationError` if validation does not succeed.
[ "Perform", "validation", "on", "value", ".", "Raise", "a", ":", "exc", ":", "ValidationError", "if", "validation", "does", "not", "succeed", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/base.py#L149-L167
proteanhq/protean
src/protean/core/field/base.py
Field._load
def _load(self, value: Any): """ Load the value for the field, run validators and return the value. Subclasses can override this to provide custom load logic. :param value: value of the field """ if value in self.empty_values: # If a default has been set fo...
python
def _load(self, value: Any): """ Load the value for the field, run validators and return the value. Subclasses can override this to provide custom load logic. :param value: value of the field """ if value in self.empty_values: # If a default has been set fo...
[ "def", "_load", "(", "self", ",", "value", ":", "Any", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "# If a default has been set for the field return it", "if", "self", ".", "default", "is", "not", "None", ":", "default", "=", "self", "."...
Load the value for the field, run validators and return the value. Subclasses can override this to provide custom load logic. :param value: value of the field
[ "Load", "the", "value", "for", "the", "field", "run", "validators", "and", "return", "the", "value", ".", "Subclasses", "can", "override", "this", "to", "provide", "custom", "load", "logic", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/base.py#L169-L211
proteanhq/protean
src/protean/core/provider/base.py
BaseProvider._extract_lookup
def _extract_lookup(self, key): """Extract lookup method based on key name format""" parts = key.split('__') # 'exact' is the default lookup if there was no explicit comparison op in `key` # Assume there is only one `__` in the key. # FIXME Change for child attribute query su...
python
def _extract_lookup(self, key): """Extract lookup method based on key name format""" parts = key.split('__') # 'exact' is the default lookup if there was no explicit comparison op in `key` # Assume there is only one `__` in the key. # FIXME Change for child attribute query su...
[ "def", "_extract_lookup", "(", "self", ",", "key", ")", ":", "parts", "=", "key", ".", "split", "(", "'__'", ")", "# 'exact' is the default lookup if there was no explicit comparison op in `key`", "# Assume there is only one `__` in the key.", "# FIXME Change for child attrib...
Extract lookup method based on key name format
[ "Extract", "lookup", "method", "based", "on", "key", "name", "format" ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/provider/base.py#L21-L30
tadashi-aikawa/jumeaux
jumeaux/addons/log2reqs/json.py
Executor.exec
def exec(self, payload: Log2ReqsAddOnPayload) -> TList[Request]: """Transform from json to Request Exception: ValueError: If path does not exist. """ try: return Request.from_jsonf_to_list(payload.file, encoding=self.config.encoding) except TypeError as e...
python
def exec(self, payload: Log2ReqsAddOnPayload) -> TList[Request]: """Transform from json to Request Exception: ValueError: If path does not exist. """ try: return Request.from_jsonf_to_list(payload.file, encoding=self.config.encoding) except TypeError as e...
[ "def", "exec", "(", "self", ",", "payload", ":", "Log2ReqsAddOnPayload", ")", "->", "TList", "[", "Request", "]", ":", "try", ":", "return", "Request", ".", "from_jsonf_to_list", "(", "payload", ".", "file", ",", "encoding", "=", "self", ".", "config", "...
Transform from json to Request Exception: ValueError: If path does not exist.
[ "Transform", "from", "json", "to", "Request" ]
train
https://github.com/tadashi-aikawa/jumeaux/blob/23389bde3e9b27b3a646d99289f8b5ced411f6f0/jumeaux/addons/log2reqs/json.py#L18-L27
proteanhq/protean
src/protean/core/cache/base.py
BaseCache.get_backend_expiry
def get_backend_expiry(self, expiry=DEFAULT_EXPIRY): """ Return the expiry value usable by this backend based upon the provided timeout. """ if expiry == DEFAULT_EXPIRY: expiry = self.default_expiry elif expiry == 0: # avoid time.time() related pre...
python
def get_backend_expiry(self, expiry=DEFAULT_EXPIRY): """ Return the expiry value usable by this backend based upon the provided timeout. """ if expiry == DEFAULT_EXPIRY: expiry = self.default_expiry elif expiry == 0: # avoid time.time() related pre...
[ "def", "get_backend_expiry", "(", "self", ",", "expiry", "=", "DEFAULT_EXPIRY", ")", ":", "if", "expiry", "==", "DEFAULT_EXPIRY", ":", "expiry", "=", "self", ".", "default_expiry", "elif", "expiry", "==", "0", ":", "# avoid time.time() related precision issues", "...
Return the expiry value usable by this backend based upon the provided timeout.
[ "Return", "the", "expiry", "value", "usable", "by", "this", "backend", "based", "upon", "the", "provided", "timeout", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/cache/base.py#L21-L31
proteanhq/protean
src/protean/core/cache/base.py
BaseCache.get_many
def get_many(self, keys): """ Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster when fetching multiple values. Return a dict mapping each key in keys to its value. If the given key is missing, it will be missing from the respo...
python
def get_many(self, keys): """ Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster when fetching multiple values. Return a dict mapping each key in keys to its value. If the given key is missing, it will be missing from the respo...
[ "def", "get_many", "(", "self", ",", "keys", ")", ":", "d", "=", "{", "}", "for", "k", "in", "keys", ":", "val", "=", "self", ".", "get", "(", "k", ")", "if", "val", "is", "not", "None", ":", "d", "[", "k", "]", "=", "val", "return", "d" ]
Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster when fetching multiple values. Return a dict mapping each key in keys to its value. If the given key is missing, it will be missing from the response dict.
[ "Fetch", "a", "bunch", "of", "keys", "from", "the", "cache", ".", "For", "certain", "backends", "(", "memcached", "pgsql", ")", "this", "can", "be", "*", "much", "*", "faster", "when", "fetching", "multiple", "values", ".", "Return", "a", "dict", "mappin...
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/cache/base.py#L82-L95
proteanhq/protean
src/protean/core/cache/base.py
BaseCache.incr
def incr(self, key, delta=1): """ Add delta to value in the cache. If the key does not exist, raise a ValueError exception. """ value = self.get(key) if value is None: raise ValueError("Key '%s' not found" % key) new_value = value + delta self....
python
def incr(self, key, delta=1): """ Add delta to value in the cache. If the key does not exist, raise a ValueError exception. """ value = self.get(key) if value is None: raise ValueError("Key '%s' not found" % key) new_value = value + delta self....
[ "def", "incr", "(", "self", ",", "key", ",", "delta", "=", "1", ")", ":", "value", "=", "self", ".", "get", "(", "key", ")", "if", "value", "is", "None", ":", "raise", "ValueError", "(", "\"Key '%s' not found\"", "%", "key", ")", "new_value", "=", ...
Add delta to value in the cache. If the key does not exist, raise a ValueError exception.
[ "Add", "delta", "to", "value", "in", "the", "cache", ".", "If", "the", "key", "does", "not", "exist", "raise", "a", "ValueError", "exception", "." ]
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/cache/base.py#L103-L113
proteanhq/protean
src/protean/core/cache/base.py
BaseCache.set_many
def set_many(self, data, expiry=DEFAULT_EXPIRY): """ Set a bunch of values in the cache at once from a dict of key/value pairs. For certain backends (memcached), this is much more efficient than calling set() multiple times. If timeout is given, use that timeout for the key; oth...
python
def set_many(self, data, expiry=DEFAULT_EXPIRY): """ Set a bunch of values in the cache at once from a dict of key/value pairs. For certain backends (memcached), this is much more efficient than calling set() multiple times. If timeout is given, use that timeout for the key; oth...
[ "def", "set_many", "(", "self", ",", "data", ",", "expiry", "=", "DEFAULT_EXPIRY", ")", ":", "for", "key", ",", "value", "in", "data", ".", "items", "(", ")", ":", "self", ".", "set", "(", "key", ",", "value", ",", "expiry", "=", "expiry", ")", "...
Set a bunch of values in the cache at once from a dict of key/value pairs. For certain backends (memcached), this is much more efficient than calling set() multiple times. If timeout is given, use that timeout for the key; otherwise use the default cache timeout. On backends tha...
[ "Set", "a", "bunch", "of", "values", "in", "the", "cache", "at", "once", "from", "a", "dict", "of", "key", "/", "value", "pairs", ".", "For", "certain", "backends", "(", "memcached", ")", "this", "is", "much", "more", "efficient", "than", "calling", "s...
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/cache/base.py#L122-L134
tadashi-aikawa/jumeaux
jumeaux/logger.py
init_logger
def init_logger(v_num: int): """ Call when initialize Jumeaux !! :return: """ logging.addLevelName(LogLevel.INFO_LV1.value, 'INFO_LV1') # type: ignore # Prevent for enum problem logging.addLevelName(LogLevel.INFO_LV2.value, 'INFO_LV2') # type: ignore # Prevent for enum problem logging.addL...
python
def init_logger(v_num: int): """ Call when initialize Jumeaux !! :return: """ logging.addLevelName(LogLevel.INFO_LV1.value, 'INFO_LV1') # type: ignore # Prevent for enum problem logging.addLevelName(LogLevel.INFO_LV2.value, 'INFO_LV2') # type: ignore # Prevent for enum problem logging.addL...
[ "def", "init_logger", "(", "v_num", ":", "int", ")", ":", "logging", ".", "addLevelName", "(", "LogLevel", ".", "INFO_LV1", ".", "value", ",", "'INFO_LV1'", ")", "# type: ignore # Prevent for enum problem", "logging", ".", "addLevelName", "(", "LogLevel", ".", "...
Call when initialize Jumeaux !! :return:
[ "Call", "when", "initialize", "Jumeaux", "!!", ":", "return", ":" ]
train
https://github.com/tadashi-aikawa/jumeaux/blob/23389bde3e9b27b3a646d99289f8b5ced411f6f0/jumeaux/logger.py#L60-L74