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
facelessuser/pyspelling
pyspelling/filters/python.py
PythonFilter.process_strings
def process_strings(self, string, docstrings=False): """Process escapes.""" m = RE_STRING_TYPE.match(string) stype = self.get_string_type(m.group(1) if m.group(1) else '') if not self.match_string(stype) and not docstrings: return '', False is_bytes = 'b' in stype is_raw = 'r' in stype is_format = 'f' in stype content = m.group(3) if is_raw and (not is_format or not self.decode_escapes): string = self.norm_nl(content) elif is_raw and is_format: string = self.norm_nl(FE_RFESC.sub(self.replace_unicode, content)) elif is_bytes: string = self.norm_nl(RE_BESC.sub(self.replace_bytes, content)) elif is_format: string = self.norm_nl(RE_FESC.sub(self.replace_unicode, content)) else: string = self.norm_nl(RE_ESC.sub(self.replace_unicode, content)) return textwrap.dedent(RE_NON_PRINTABLE.sub('\n', string) if is_bytes else string), is_bytes
python
def process_strings(self, string, docstrings=False): """Process escapes.""" m = RE_STRING_TYPE.match(string) stype = self.get_string_type(m.group(1) if m.group(1) else '') if not self.match_string(stype) and not docstrings: return '', False is_bytes = 'b' in stype is_raw = 'r' in stype is_format = 'f' in stype content = m.group(3) if is_raw and (not is_format or not self.decode_escapes): string = self.norm_nl(content) elif is_raw and is_format: string = self.norm_nl(FE_RFESC.sub(self.replace_unicode, content)) elif is_bytes: string = self.norm_nl(RE_BESC.sub(self.replace_bytes, content)) elif is_format: string = self.norm_nl(RE_FESC.sub(self.replace_unicode, content)) else: string = self.norm_nl(RE_ESC.sub(self.replace_unicode, content)) return textwrap.dedent(RE_NON_PRINTABLE.sub('\n', string) if is_bytes else string), is_bytes
[ "def", "process_strings", "(", "self", ",", "string", ",", "docstrings", "=", "False", ")", ":", "m", "=", "RE_STRING_TYPE", ".", "match", "(", "string", ")", "stype", "=", "self", ".", "get_string_type", "(", "m", ".", "group", "(", "1", ")", "if", ...
Process escapes.
[ "Process", "escapes", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/python.py#L225-L247
facelessuser/pyspelling
pyspelling/filters/python.py
PythonFilter._filter
def _filter(self, text, context, encoding): """Retrieve the Python docstrings.""" docstrings = [] strings = [] comments = [] prev_token_type = tokenize.NEWLINE indent = '' name = None stack = [(context, 0, self.MODULE)] last_comment = False possible_fmt_str = None src = io.StringIO(text) for token in tokenizer(src.readline): token_type = token[0] value = token[1] line = str(token[2][0]) line_num = token[2][0] value = token[1] line = str(token[2][0]) # Track function and class ancestry if token_type == tokenize.NAME: possible_fmt_str = None if value in ('def', 'class'): name = value elif name: parent = stack[-1][2] prefix = '' if parent != self.MODULE: prefix = '.' if parent == self.CLASS else ', ' if name == 'class': stack.append(('%s%s' % (prefix, value), len(indent), self.CLASS)) elif name == 'def': stack.append(('%s%s()' % (prefix, value), len(indent), self.FUNCTION)) name = None elif not F_SUPPORT and value in FMT_STR: possible_fmt_str = (prev_token_type, value) elif token_type != tokenize.STRING: possible_fmt_str = None if token_type == tokenize.COMMENT and self.comments: # Capture comments if ( self.group_comments and last_comment and comments and (comments[-1][2] + 1) == line_num ): # Group multiple consecutive comments comments[-1][0] += '\n' + value[1:] comments[-1][2] = line_num else: if len(stack) > 1: loc = "%s(%s): %s" % (stack[0][0], line, ''.join([crumb[0] for crumb in stack[1:]])) else: loc = "%s(%s)" % (stack[0][0], line) comments.append([value[1:], loc, line_num]) if token_type == tokenize.STRING: # Capture docstrings. # If we captured an `INDENT` or `NEWLINE` previously we probably have a docstring. # `NL` means end of line, but not the end of the Python code line (line continuation). if ( (prev_token_type in PREV_DOC_TOKENS) or (possible_fmt_str and possible_fmt_str[0] in PREV_DOC_TOKENS) ): if self.docstrings: value = value.strip() if possible_fmt_str and value.startswith(("'", "\"")): value = possible_fmt_str[1] + value string, is_bytes = self.process_strings(value, docstrings=True) if string: loc = "%s(%s): %s" % (stack[0][0], line, ''.join([crumb[0] for crumb in stack[1:]])) docstrings.append( filters.SourceText(string, loc, 'utf-8', 'py-docstring') ) elif self.strings: value = value.strip() if possible_fmt_str and value.startswith(("'", "\"")): value = possible_fmt_str[1] + value string, is_bytes = self.process_strings(value) if string: loc = "%s(%s): %s" % (stack[0][0], line, ''.join([crumb[0] for crumb in stack[1:]])) strings.append(filters.SourceText(string, loc, 'utf-8', 'py-string')) if token_type == tokenize.INDENT: indent = value elif token_type == tokenize.DEDENT: indent = indent[:-4] if len(stack) > 1 and len(indent) <= stack[-1][1]: stack.pop() # We purposefully avoid storing comments as comments can come before docstrings, # and that can mess up our logic. So if the token is a comment we won't track it, # and comments are always followed with `NL` so we ignore that as well. # We only care that docstrings are preceded by `NEWLINE`. if token_type != tokenize.COMMENT and not (last_comment and token_type == tokenize.NL): prev_token_type = token_type last_comment = False else: last_comment = True final_comments = [] for comment in comments: final_comments.append(filters.SourceText(textwrap.dedent(comment[0]), comment[1], encoding, 'py-comment')) return docstrings + final_comments + strings
python
def _filter(self, text, context, encoding): """Retrieve the Python docstrings.""" docstrings = [] strings = [] comments = [] prev_token_type = tokenize.NEWLINE indent = '' name = None stack = [(context, 0, self.MODULE)] last_comment = False possible_fmt_str = None src = io.StringIO(text) for token in tokenizer(src.readline): token_type = token[0] value = token[1] line = str(token[2][0]) line_num = token[2][0] value = token[1] line = str(token[2][0]) # Track function and class ancestry if token_type == tokenize.NAME: possible_fmt_str = None if value in ('def', 'class'): name = value elif name: parent = stack[-1][2] prefix = '' if parent != self.MODULE: prefix = '.' if parent == self.CLASS else ', ' if name == 'class': stack.append(('%s%s' % (prefix, value), len(indent), self.CLASS)) elif name == 'def': stack.append(('%s%s()' % (prefix, value), len(indent), self.FUNCTION)) name = None elif not F_SUPPORT and value in FMT_STR: possible_fmt_str = (prev_token_type, value) elif token_type != tokenize.STRING: possible_fmt_str = None if token_type == tokenize.COMMENT and self.comments: # Capture comments if ( self.group_comments and last_comment and comments and (comments[-1][2] + 1) == line_num ): # Group multiple consecutive comments comments[-1][0] += '\n' + value[1:] comments[-1][2] = line_num else: if len(stack) > 1: loc = "%s(%s): %s" % (stack[0][0], line, ''.join([crumb[0] for crumb in stack[1:]])) else: loc = "%s(%s)" % (stack[0][0], line) comments.append([value[1:], loc, line_num]) if token_type == tokenize.STRING: # Capture docstrings. # If we captured an `INDENT` or `NEWLINE` previously we probably have a docstring. # `NL` means end of line, but not the end of the Python code line (line continuation). if ( (prev_token_type in PREV_DOC_TOKENS) or (possible_fmt_str and possible_fmt_str[0] in PREV_DOC_TOKENS) ): if self.docstrings: value = value.strip() if possible_fmt_str and value.startswith(("'", "\"")): value = possible_fmt_str[1] + value string, is_bytes = self.process_strings(value, docstrings=True) if string: loc = "%s(%s): %s" % (stack[0][0], line, ''.join([crumb[0] for crumb in stack[1:]])) docstrings.append( filters.SourceText(string, loc, 'utf-8', 'py-docstring') ) elif self.strings: value = value.strip() if possible_fmt_str and value.startswith(("'", "\"")): value = possible_fmt_str[1] + value string, is_bytes = self.process_strings(value) if string: loc = "%s(%s): %s" % (stack[0][0], line, ''.join([crumb[0] for crumb in stack[1:]])) strings.append(filters.SourceText(string, loc, 'utf-8', 'py-string')) if token_type == tokenize.INDENT: indent = value elif token_type == tokenize.DEDENT: indent = indent[:-4] if len(stack) > 1 and len(indent) <= stack[-1][1]: stack.pop() # We purposefully avoid storing comments as comments can come before docstrings, # and that can mess up our logic. So if the token is a comment we won't track it, # and comments are always followed with `NL` so we ignore that as well. # We only care that docstrings are preceded by `NEWLINE`. if token_type != tokenize.COMMENT and not (last_comment and token_type == tokenize.NL): prev_token_type = token_type last_comment = False else: last_comment = True final_comments = [] for comment in comments: final_comments.append(filters.SourceText(textwrap.dedent(comment[0]), comment[1], encoding, 'py-comment')) return docstrings + final_comments + strings
[ "def", "_filter", "(", "self", ",", "text", ",", "context", ",", "encoding", ")", ":", "docstrings", "=", "[", "]", "strings", "=", "[", "]", "comments", "=", "[", "]", "prev_token_type", "=", "tokenize", ".", "NEWLINE", "indent", "=", "''", "name", ...
Retrieve the Python docstrings.
[ "Retrieve", "the", "Python", "docstrings", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/python.py#L249-L357
runfalk/spans
spans/_utils.py
find_slots
def find_slots(cls): """Return a set of all slots for a given class and its parents""" slots = set() for c in cls.__mro__: cslots = getattr(c, "__slots__", tuple()) if not cslots: continue elif isinstance(cslots, (bstr, ustr)): cslots = (cslots,) slots.update(cslots) return slots
python
def find_slots(cls): """Return a set of all slots for a given class and its parents""" slots = set() for c in cls.__mro__: cslots = getattr(c, "__slots__", tuple()) if not cslots: continue elif isinstance(cslots, (bstr, ustr)): cslots = (cslots,) slots.update(cslots) return slots
[ "def", "find_slots", "(", "cls", ")", ":", "slots", "=", "set", "(", ")", "for", "c", "in", "cls", ".", "__mro__", ":", "cslots", "=", "getattr", "(", "c", ",", "\"__slots__\"", ",", "tuple", "(", ")", ")", "if", "not", "cslots", ":", "continue", ...
Return a set of all slots for a given class and its parents
[ "Return", "a", "set", "of", "all", "slots", "for", "a", "given", "class", "and", "its", "parents" ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/_utils.py#L33-L47
runfalk/spans
spans/types.py
_is_valid_date
def _is_valid_date(obj, accept_none=True): """ Check if an object is an instance of, or a subclass deriving from, a ``date``. However, it does not consider ``datetime`` or subclasses thereof as valid dates. :param obj: Object to test as date. :param accept_none: If True None is considered as a valid date object. """ if accept_none and obj is None: return True return isinstance(obj, date) and not isinstance(obj, datetime)
python
def _is_valid_date(obj, accept_none=True): """ Check if an object is an instance of, or a subclass deriving from, a ``date``. However, it does not consider ``datetime`` or subclasses thereof as valid dates. :param obj: Object to test as date. :param accept_none: If True None is considered as a valid date object. """ if accept_none and obj is None: return True return isinstance(obj, date) and not isinstance(obj, datetime)
[ "def", "_is_valid_date", "(", "obj", ",", "accept_none", "=", "True", ")", ":", "if", "accept_none", "and", "obj", "is", "None", ":", "return", "True", "return", "isinstance", "(", "obj", ",", "date", ")", "and", "not", "isinstance", "(", "obj", ",", "...
Check if an object is an instance of, or a subclass deriving from, a ``date``. However, it does not consider ``datetime`` or subclasses thereof as valid dates. :param obj: Object to test as date. :param accept_none: If True None is considered as a valid date object.
[ "Check", "if", "an", "object", "is", "an", "instance", "of", "or", "a", "subclass", "deriving", "from", "a", "date", ".", "However", "it", "does", "not", "consider", "datetime", "or", "subclasses", "thereof", "as", "valid", "dates", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1100-L1112
runfalk/spans
spans/types.py
Range.empty
def empty(cls): """ Returns an empty set. An empty set is unbounded and only contain the empty set. >>> intrange.empty() in intrange.empty() True It is unbounded but the boundaries are not infinite. Its boundaries are returned as ``None``. Every set contains the empty set. """ self = cls.__new__(cls) self._range = _empty_internal_range return self
python
def empty(cls): """ Returns an empty set. An empty set is unbounded and only contain the empty set. >>> intrange.empty() in intrange.empty() True It is unbounded but the boundaries are not infinite. Its boundaries are returned as ``None``. Every set contains the empty set. """ self = cls.__new__(cls) self._range = _empty_internal_range return self
[ "def", "empty", "(", "cls", ")", ":", "self", "=", "cls", ".", "__new__", "(", "cls", ")", "self", ".", "_range", "=", "_empty_internal_range", "return", "self" ]
Returns an empty set. An empty set is unbounded and only contain the empty set. >>> intrange.empty() in intrange.empty() True It is unbounded but the boundaries are not infinite. Its boundaries are returned as ``None``. Every set contains the empty set.
[ "Returns", "an", "empty", "set", ".", "An", "empty", "set", "is", "unbounded", "and", "only", "contain", "the", "empty", "set", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L92-L106
runfalk/spans
spans/types.py
Range.replace
def replace(self, *args, **kwargs): """ replace(lower=None, upper=None, lower_inc=None, upper_inc=None) Returns a new instance of self with the given arguments replaced. It takes the exact same arguments as the constructor. >>> intrange(1, 5).replace(upper=10) intrange([1,10)) >>> intrange(1, 10).replace(lower_inc=False) intrange([2,10)) >>> intrange(1, 10).replace(5) intrange([5,10)) Note that range objects are immutable and are never modified in place. """ replacements = { "lower" : self.lower, "upper" : self.upper, "lower_inc" : self.lower_inc, "upper_inc" : self.upper_inc } replacements.update( dict(zip(("lower", "upper", "lower_inc", "upper_inc"), args))) replacements.update(kwargs) return self.__class__(**replacements)
python
def replace(self, *args, **kwargs): """ replace(lower=None, upper=None, lower_inc=None, upper_inc=None) Returns a new instance of self with the given arguments replaced. It takes the exact same arguments as the constructor. >>> intrange(1, 5).replace(upper=10) intrange([1,10)) >>> intrange(1, 10).replace(lower_inc=False) intrange([2,10)) >>> intrange(1, 10).replace(5) intrange([5,10)) Note that range objects are immutable and are never modified in place. """ replacements = { "lower" : self.lower, "upper" : self.upper, "lower_inc" : self.lower_inc, "upper_inc" : self.upper_inc } replacements.update( dict(zip(("lower", "upper", "lower_inc", "upper_inc"), args))) replacements.update(kwargs) return self.__class__(**replacements)
[ "def", "replace", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "replacements", "=", "{", "\"lower\"", ":", "self", ".", "lower", ",", "\"upper\"", ":", "self", ".", "upper", ",", "\"lower_inc\"", ":", "self", ".", "lower_inc", ",...
replace(lower=None, upper=None, lower_inc=None, upper_inc=None) Returns a new instance of self with the given arguments replaced. It takes the exact same arguments as the constructor. >>> intrange(1, 5).replace(upper=10) intrange([1,10)) >>> intrange(1, 10).replace(lower_inc=False) intrange([2,10)) >>> intrange(1, 10).replace(5) intrange([5,10)) Note that range objects are immutable and are never modified in place.
[ "replace", "(", "lower", "=", "None", "upper", "=", "None", "lower_inc", "=", "None", "upper_inc", "=", "None", ")" ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L117-L144
runfalk/spans
spans/types.py
Range.contains
def contains(self, other): """ Return True if this contains other. Other may be either range of same type or scalar of same type as the boundaries. >>> intrange(1, 10).contains(intrange(1, 5)) True >>> intrange(1, 10).contains(intrange(5, 10)) True >>> intrange(1, 10).contains(intrange(5, 10, upper_inc=True)) False >>> intrange(1, 10).contains(1) True >>> intrange(1, 10).contains(10) False Contains can also be called using the ``in`` operator. >>> 1 in intrange(1, 10) True This is the same as the ``self @> other`` in PostgreSQL. :param other: Object to be checked whether it exists within this range or not. :return: ``True`` if `other` is completely within this range, otherwise ``False``. :raises TypeError: If `other` is not of the correct type. """ if self.is_valid_range(other): if not self: return not other elif not other or other.startsafter(self) and other.endsbefore(self): return True else: return False elif self.is_valid_scalar(other): # If the lower bounary is not unbound we can safely perform the # comparison. Otherwise we'll try to compare a scalar to None, which # is bad is_within_lower = True if not self.lower_inf: lower_cmp = operator.le if self.lower_inc else operator.lt is_within_lower = lower_cmp(self.lower, other) # If the upper bounary is not unbound we can safely perform the # comparison. Otherwise we'll try to compare a scalar to None, which # is bad is_within_upper = True if not self.upper_inf: upper_cmp = operator.ge if self.upper_inc else operator.gt is_within_upper = upper_cmp(self.upper, other) return is_within_lower and is_within_upper else: raise TypeError( "Unsupported type to test for inclusion '{0.__class__.__name__}'".format( other))
python
def contains(self, other): """ Return True if this contains other. Other may be either range of same type or scalar of same type as the boundaries. >>> intrange(1, 10).contains(intrange(1, 5)) True >>> intrange(1, 10).contains(intrange(5, 10)) True >>> intrange(1, 10).contains(intrange(5, 10, upper_inc=True)) False >>> intrange(1, 10).contains(1) True >>> intrange(1, 10).contains(10) False Contains can also be called using the ``in`` operator. >>> 1 in intrange(1, 10) True This is the same as the ``self @> other`` in PostgreSQL. :param other: Object to be checked whether it exists within this range or not. :return: ``True`` if `other` is completely within this range, otherwise ``False``. :raises TypeError: If `other` is not of the correct type. """ if self.is_valid_range(other): if not self: return not other elif not other or other.startsafter(self) and other.endsbefore(self): return True else: return False elif self.is_valid_scalar(other): # If the lower bounary is not unbound we can safely perform the # comparison. Otherwise we'll try to compare a scalar to None, which # is bad is_within_lower = True if not self.lower_inf: lower_cmp = operator.le if self.lower_inc else operator.lt is_within_lower = lower_cmp(self.lower, other) # If the upper bounary is not unbound we can safely perform the # comparison. Otherwise we'll try to compare a scalar to None, which # is bad is_within_upper = True if not self.upper_inf: upper_cmp = operator.ge if self.upper_inc else operator.gt is_within_upper = upper_cmp(self.upper, other) return is_within_lower and is_within_upper else: raise TypeError( "Unsupported type to test for inclusion '{0.__class__.__name__}'".format( other))
[ "def", "contains", "(", "self", ",", "other", ")", ":", "if", "self", ".", "is_valid_range", "(", "other", ")", ":", "if", "not", "self", ":", "return", "not", "other", "elif", "not", "other", "or", "other", ".", "startsafter", "(", "self", ")", "and...
Return True if this contains other. Other may be either range of same type or scalar of same type as the boundaries. >>> intrange(1, 10).contains(intrange(1, 5)) True >>> intrange(1, 10).contains(intrange(5, 10)) True >>> intrange(1, 10).contains(intrange(5, 10, upper_inc=True)) False >>> intrange(1, 10).contains(1) True >>> intrange(1, 10).contains(10) False Contains can also be called using the ``in`` operator. >>> 1 in intrange(1, 10) True This is the same as the ``self @> other`` in PostgreSQL. :param other: Object to be checked whether it exists within this range or not. :return: ``True`` if `other` is completely within this range, otherwise ``False``. :raises TypeError: If `other` is not of the correct type.
[ "Return", "True", "if", "this", "contains", "other", ".", "Other", "may", "be", "either", "range", "of", "same", "type", "or", "scalar", "of", "same", "type", "as", "the", "boundaries", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L289-L347
runfalk/spans
spans/types.py
Range.within
def within(self, other): """ Tests if this range is within `other`. >>> a = intrange(1, 10) >>> b = intrange(3, 8) >>> a.contains(b) True >>> b.within(a) True This is the same as the ``self <@ other`` in PostgreSQL. One difference however is that unlike PostgreSQL ``self`` in this can't be a scalar value. :param other: Range to test against. :return: ``True`` if this range is completely within the given range, otherwise ``False``. :raises TypeError: If given range is of the wrong type. .. seealso:: This method is the inverse of :meth:`~spans.types.Range.contains` """ if not self.is_valid_range(other): raise TypeError( "Unsupported type to test for inclusion '{0.__class__.__name__}'".format( other)) return other.contains(self)
python
def within(self, other): """ Tests if this range is within `other`. >>> a = intrange(1, 10) >>> b = intrange(3, 8) >>> a.contains(b) True >>> b.within(a) True This is the same as the ``self <@ other`` in PostgreSQL. One difference however is that unlike PostgreSQL ``self`` in this can't be a scalar value. :param other: Range to test against. :return: ``True`` if this range is completely within the given range, otherwise ``False``. :raises TypeError: If given range is of the wrong type. .. seealso:: This method is the inverse of :meth:`~spans.types.Range.contains` """ if not self.is_valid_range(other): raise TypeError( "Unsupported type to test for inclusion '{0.__class__.__name__}'".format( other)) return other.contains(self)
[ "def", "within", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "is_valid_range", "(", "other", ")", ":", "raise", "TypeError", "(", "\"Unsupported type to test for inclusion '{0.__class__.__name__}'\"", ".", "format", "(", "other", ")", ")", "re...
Tests if this range is within `other`. >>> a = intrange(1, 10) >>> b = intrange(3, 8) >>> a.contains(b) True >>> b.within(a) True This is the same as the ``self <@ other`` in PostgreSQL. One difference however is that unlike PostgreSQL ``self`` in this can't be a scalar value. :param other: Range to test against. :return: ``True`` if this range is completely within the given range, otherwise ``False``. :raises TypeError: If given range is of the wrong type. .. seealso:: This method is the inverse of :meth:`~spans.types.Range.contains`
[ "Tests", "if", "this", "range", "is", "within", "other", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L349-L377
runfalk/spans
spans/types.py
Range.overlap
def overlap(self, other): """ Returns True if both ranges share any points. >>> intrange(1, 10).overlap(intrange(5, 15)) True >>> intrange(1, 5).overlap(intrange(5, 10)) False This is the same as the ``&&`` operator for two ranges in PostgreSQL. :param other: Range to test against. :return: ``True`` if ranges overlap, otherwise ``False``. :raises TypeError: If `other` is of another type than this range. .. seealso:: If you need to know which part that overlapped, consider using :meth:`~spans.types.Range.intersection`. """ # Special case for empty ranges if not self or not other: return False if self < other: a, b = self, other else: a, b = other, self # We need to explicitly handle unbounded ranges since a.upper and b.lower # make the intervals seem adjacent even though they are not if a.upper_inf or b.lower_inf: return True return a.upper > b.lower or a.upper == b.lower and a.upper_inc and b.lower_inc
python
def overlap(self, other): """ Returns True if both ranges share any points. >>> intrange(1, 10).overlap(intrange(5, 15)) True >>> intrange(1, 5).overlap(intrange(5, 10)) False This is the same as the ``&&`` operator for two ranges in PostgreSQL. :param other: Range to test against. :return: ``True`` if ranges overlap, otherwise ``False``. :raises TypeError: If `other` is of another type than this range. .. seealso:: If you need to know which part that overlapped, consider using :meth:`~spans.types.Range.intersection`. """ # Special case for empty ranges if not self or not other: return False if self < other: a, b = self, other else: a, b = other, self # We need to explicitly handle unbounded ranges since a.upper and b.lower # make the intervals seem adjacent even though they are not if a.upper_inf or b.lower_inf: return True return a.upper > b.lower or a.upper == b.lower and a.upper_inc and b.lower_inc
[ "def", "overlap", "(", "self", ",", "other", ")", ":", "# Special case for empty ranges", "if", "not", "self", "or", "not", "other", ":", "return", "False", "if", "self", "<", "other", ":", "a", ",", "b", "=", "self", ",", "other", "else", ":", "a", ...
Returns True if both ranges share any points. >>> intrange(1, 10).overlap(intrange(5, 15)) True >>> intrange(1, 5).overlap(intrange(5, 10)) False This is the same as the ``&&`` operator for two ranges in PostgreSQL. :param other: Range to test against. :return: ``True`` if ranges overlap, otherwise ``False``. :raises TypeError: If `other` is of another type than this range. .. seealso:: If you need to know which part that overlapped, consider using :meth:`~spans.types.Range.intersection`.
[ "Returns", "True", "if", "both", "ranges", "share", "any", "points", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L379-L412
runfalk/spans
spans/types.py
Range.adjacent
def adjacent(self, other): """ Returns True if ranges are directly next to each other but does not overlap. >>> intrange(1, 5).adjacent(intrange(5, 10)) True >>> intrange(1, 5).adjacent(intrange(10, 15)) False The empty set is not adjacent to any set. This is the same as the ``-|-`` operator for two ranges in PostgreSQL. :param other: Range to test against. :return: ``True`` if this range is adjacent with `other`, otherwise ``False``. :raises TypeError: If given argument is of invalid type """ if not self.is_valid_range(other): raise TypeError( "Unsupported type to test for inclusion '{0.__class__.__name__}'".format( other)) # Must return False if either is an empty set elif not self or not other: return False return ( (self.lower == other.upper and self.lower_inc != other.upper_inc) or (self.upper == other.lower and self.upper_inc != other.lower_inc))
python
def adjacent(self, other): """ Returns True if ranges are directly next to each other but does not overlap. >>> intrange(1, 5).adjacent(intrange(5, 10)) True >>> intrange(1, 5).adjacent(intrange(10, 15)) False The empty set is not adjacent to any set. This is the same as the ``-|-`` operator for two ranges in PostgreSQL. :param other: Range to test against. :return: ``True`` if this range is adjacent with `other`, otherwise ``False``. :raises TypeError: If given argument is of invalid type """ if not self.is_valid_range(other): raise TypeError( "Unsupported type to test for inclusion '{0.__class__.__name__}'".format( other)) # Must return False if either is an empty set elif not self or not other: return False return ( (self.lower == other.upper and self.lower_inc != other.upper_inc) or (self.upper == other.lower and self.upper_inc != other.lower_inc))
[ "def", "adjacent", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "is_valid_range", "(", "other", ")", ":", "raise", "TypeError", "(", "\"Unsupported type to test for inclusion '{0.__class__.__name__}'\"", ".", "format", "(", "other", ")", ")", "...
Returns True if ranges are directly next to each other but does not overlap. >>> intrange(1, 5).adjacent(intrange(5, 10)) True >>> intrange(1, 5).adjacent(intrange(10, 15)) False The empty set is not adjacent to any set. This is the same as the ``-|-`` operator for two ranges in PostgreSQL. :param other: Range to test against. :return: ``True`` if this range is adjacent with `other`, otherwise ``False``. :raises TypeError: If given argument is of invalid type
[ "Returns", "True", "if", "ranges", "are", "directly", "next", "to", "each", "other", "but", "does", "not", "overlap", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L414-L443
runfalk/spans
spans/types.py
Range.union
def union(self, other): """ Merges this range with a given range. >>> intrange(1, 5).union(intrange(5, 10)) intrange([1,10)) >>> intrange(1, 10).union(intrange(5, 15)) intrange([1,15)) Two ranges can not be merged if the resulting range would be split in two. This happens when the two sets are neither adjacent nor overlaps. >>> intrange(1, 5).union(intrange(10, 15)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Ranges must be either adjacent or overlapping This does not modify the range in place. This is the same as the ``+`` operator for two ranges in PostgreSQL. :param other: Range to merge with. :return: A new range that is the union of this and `other`. :raises ValueError: If `other` can not be merged with this range. """ if not self.is_valid_range(other): msg = "Unsupported type to test for union '{.__class__.__name__}'" raise TypeError(msg.format(other)) # Optimize empty ranges if not self: return other elif not other: return self # Order ranges to simplify checks if self < other: a, b = self, other else: a, b = other, self if (a.upper < b.lower or a.upper == b.lower and not a.upper_inc and not b.lower_inc) and not a.adjacent(b): raise ValueError("Ranges must be either adjacent or overlapping") # a.lower is guaranteed to be the lower bound, but either a.upper or # b.upper can be the upper bound if a.upper == b.upper: upper = a.upper upper_inc = a.upper_inc or b.upper_inc elif a.upper < b.upper: upper = b.upper upper_inc = b.upper_inc else: upper = a.upper upper_inc = a.upper_inc return self.__class__(a.lower, upper, a.lower_inc, upper_inc)
python
def union(self, other): """ Merges this range with a given range. >>> intrange(1, 5).union(intrange(5, 10)) intrange([1,10)) >>> intrange(1, 10).union(intrange(5, 15)) intrange([1,15)) Two ranges can not be merged if the resulting range would be split in two. This happens when the two sets are neither adjacent nor overlaps. >>> intrange(1, 5).union(intrange(10, 15)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Ranges must be either adjacent or overlapping This does not modify the range in place. This is the same as the ``+`` operator for two ranges in PostgreSQL. :param other: Range to merge with. :return: A new range that is the union of this and `other`. :raises ValueError: If `other` can not be merged with this range. """ if not self.is_valid_range(other): msg = "Unsupported type to test for union '{.__class__.__name__}'" raise TypeError(msg.format(other)) # Optimize empty ranges if not self: return other elif not other: return self # Order ranges to simplify checks if self < other: a, b = self, other else: a, b = other, self if (a.upper < b.lower or a.upper == b.lower and not a.upper_inc and not b.lower_inc) and not a.adjacent(b): raise ValueError("Ranges must be either adjacent or overlapping") # a.lower is guaranteed to be the lower bound, but either a.upper or # b.upper can be the upper bound if a.upper == b.upper: upper = a.upper upper_inc = a.upper_inc or b.upper_inc elif a.upper < b.upper: upper = b.upper upper_inc = b.upper_inc else: upper = a.upper upper_inc = a.upper_inc return self.__class__(a.lower, upper, a.lower_inc, upper_inc)
[ "def", "union", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "is_valid_range", "(", "other", ")", ":", "msg", "=", "\"Unsupported type to test for union '{.__class__.__name__}'\"", "raise", "TypeError", "(", "msg", ".", "format", "(", "other", ...
Merges this range with a given range. >>> intrange(1, 5).union(intrange(5, 10)) intrange([1,10)) >>> intrange(1, 10).union(intrange(5, 15)) intrange([1,15)) Two ranges can not be merged if the resulting range would be split in two. This happens when the two sets are neither adjacent nor overlaps. >>> intrange(1, 5).union(intrange(10, 15)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Ranges must be either adjacent or overlapping This does not modify the range in place. This is the same as the ``+`` operator for two ranges in PostgreSQL. :param other: Range to merge with. :return: A new range that is the union of this and `other`. :raises ValueError: If `other` can not be merged with this range.
[ "Merges", "this", "range", "with", "a", "given", "range", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L445-L503
runfalk/spans
spans/types.py
Range.difference
def difference(self, other): """ Compute the difference between this and a given range. >>> intrange(1, 10).difference(intrange(10, 15)) intrange([1,10)) >>> intrange(1, 10).difference(intrange(5, 10)) intrange([1,5)) >>> intrange(1, 5).difference(intrange(5, 10)) intrange([1,5)) >>> intrange(1, 5).difference(intrange(1, 10)) intrange(empty) The difference can not be computed if the resulting range would be split in two separate ranges. This happens when the given range is completely within this range and does not start or end at the same value. >>> intrange(1, 15).difference(intrange(5, 10)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Other range must not be within this range This does not modify the range in place. This is the same as the ``-`` operator for two ranges in PostgreSQL. :param other: Range to difference against. :return: A new range that is the difference between this and `other`. :raises ValueError: If difference bethween this and `other` can not be computed. """ if not self.is_valid_range(other): msg = "Unsupported type to test for difference '{.__class__.__name__}'" raise TypeError(msg.format(other)) # Consider empty ranges or no overlap if not self or not other or not self.overlap(other): return self # If self is contained within other, the result is empty elif self in other: return self.empty() elif other in self and not (self.startswith(other) or self.endswith(other)): raise ValueError("Other range must not be within this range") elif self.endsbefore(other): return self.replace(upper=other.lower, upper_inc=not other.lower_inc) elif self.startsafter(other): return self.replace(lower=other.upper, lower_inc=not other.upper_inc) else: return self.empty()
python
def difference(self, other): """ Compute the difference between this and a given range. >>> intrange(1, 10).difference(intrange(10, 15)) intrange([1,10)) >>> intrange(1, 10).difference(intrange(5, 10)) intrange([1,5)) >>> intrange(1, 5).difference(intrange(5, 10)) intrange([1,5)) >>> intrange(1, 5).difference(intrange(1, 10)) intrange(empty) The difference can not be computed if the resulting range would be split in two separate ranges. This happens when the given range is completely within this range and does not start or end at the same value. >>> intrange(1, 15).difference(intrange(5, 10)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Other range must not be within this range This does not modify the range in place. This is the same as the ``-`` operator for two ranges in PostgreSQL. :param other: Range to difference against. :return: A new range that is the difference between this and `other`. :raises ValueError: If difference bethween this and `other` can not be computed. """ if not self.is_valid_range(other): msg = "Unsupported type to test for difference '{.__class__.__name__}'" raise TypeError(msg.format(other)) # Consider empty ranges or no overlap if not self or not other or not self.overlap(other): return self # If self is contained within other, the result is empty elif self in other: return self.empty() elif other in self and not (self.startswith(other) or self.endswith(other)): raise ValueError("Other range must not be within this range") elif self.endsbefore(other): return self.replace(upper=other.lower, upper_inc=not other.lower_inc) elif self.startsafter(other): return self.replace(lower=other.upper, lower_inc=not other.upper_inc) else: return self.empty()
[ "def", "difference", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "is_valid_range", "(", "other", ")", ":", "msg", "=", "\"Unsupported type to test for difference '{.__class__.__name__}'\"", "raise", "TypeError", "(", "msg", ".", "format", "(", ...
Compute the difference between this and a given range. >>> intrange(1, 10).difference(intrange(10, 15)) intrange([1,10)) >>> intrange(1, 10).difference(intrange(5, 10)) intrange([1,5)) >>> intrange(1, 5).difference(intrange(5, 10)) intrange([1,5)) >>> intrange(1, 5).difference(intrange(1, 10)) intrange(empty) The difference can not be computed if the resulting range would be split in two separate ranges. This happens when the given range is completely within this range and does not start or end at the same value. >>> intrange(1, 15).difference(intrange(5, 10)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Other range must not be within this range This does not modify the range in place. This is the same as the ``-`` operator for two ranges in PostgreSQL. :param other: Range to difference against. :return: A new range that is the difference between this and `other`. :raises ValueError: If difference bethween this and `other` can not be computed.
[ "Compute", "the", "difference", "between", "this", "and", "a", "given", "range", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L505-L554
runfalk/spans
spans/types.py
Range.intersection
def intersection(self, other): """ Returns a new range containing all points shared by both ranges. If no points are shared an empty range is returned. >>> intrange(1, 5).intersection(intrange(1, 10)) intrange([1,5)) >>> intrange(1, 5).intersection(intrange(5, 10)) intrange(empty) >>> intrange(1, 10).intersection(intrange(5, 10)) intrange([5,10)) This is the same as the ``+`` operator for two ranges in PostgreSQL. :param other: Range to interect with. :return: A new range that is the intersection between this and `other`. """ if not self.is_valid_range(other): msg = "Unsupported type to test for intersection '{.__class__.__name__}'" raise TypeError(msg.format(other)) # Handle ranges not intersecting if not self or not other or not self.overlap(other): return self.empty() lower_end_span = self if self.startsafter(other) else other upper_end_span = self if self.endsbefore(other) else other return lower_end_span.replace( upper=upper_end_span.upper, upper_inc=upper_end_span.upper_inc)
python
def intersection(self, other): """ Returns a new range containing all points shared by both ranges. If no points are shared an empty range is returned. >>> intrange(1, 5).intersection(intrange(1, 10)) intrange([1,5)) >>> intrange(1, 5).intersection(intrange(5, 10)) intrange(empty) >>> intrange(1, 10).intersection(intrange(5, 10)) intrange([5,10)) This is the same as the ``+`` operator for two ranges in PostgreSQL. :param other: Range to interect with. :return: A new range that is the intersection between this and `other`. """ if not self.is_valid_range(other): msg = "Unsupported type to test for intersection '{.__class__.__name__}'" raise TypeError(msg.format(other)) # Handle ranges not intersecting if not self or not other or not self.overlap(other): return self.empty() lower_end_span = self if self.startsafter(other) else other upper_end_span = self if self.endsbefore(other) else other return lower_end_span.replace( upper=upper_end_span.upper, upper_inc=upper_end_span.upper_inc)
[ "def", "intersection", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "is_valid_range", "(", "other", ")", ":", "msg", "=", "\"Unsupported type to test for intersection '{.__class__.__name__}'\"", "raise", "TypeError", "(", "msg", ".", "format", "(...
Returns a new range containing all points shared by both ranges. If no points are shared an empty range is returned. >>> intrange(1, 5).intersection(intrange(1, 10)) intrange([1,5)) >>> intrange(1, 5).intersection(intrange(5, 10)) intrange(empty) >>> intrange(1, 10).intersection(intrange(5, 10)) intrange([5,10)) This is the same as the ``+`` operator for two ranges in PostgreSQL. :param other: Range to interect with. :return: A new range that is the intersection between this and `other`.
[ "Returns", "a", "new", "range", "containing", "all", "points", "shared", "by", "both", "ranges", ".", "If", "no", "points", "are", "shared", "an", "empty", "range", "is", "returned", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L556-L587
runfalk/spans
spans/types.py
Range.startswith
def startswith(self, other): """ Test if this range starts with `other`. `other` may be either range or scalar. >>> intrange(1, 5).startswith(1) True >>> intrange(1, 5).startswith(intrange(1, 10)) True :param other: Range or scalar to test. :return: ``True`` if this range starts with `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type. """ if self.is_valid_range(other): if self.lower_inc == other.lower_inc: return self.lower == other.lower else: return False elif self.is_valid_scalar(other): if self.lower_inc: return self.lower == other else: return False else: raise TypeError( "Unsupported type to test for starts with '{}'".format( other.__class__.__name__))
python
def startswith(self, other): """ Test if this range starts with `other`. `other` may be either range or scalar. >>> intrange(1, 5).startswith(1) True >>> intrange(1, 5).startswith(intrange(1, 10)) True :param other: Range or scalar to test. :return: ``True`` if this range starts with `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type. """ if self.is_valid_range(other): if self.lower_inc == other.lower_inc: return self.lower == other.lower else: return False elif self.is_valid_scalar(other): if self.lower_inc: return self.lower == other else: return False else: raise TypeError( "Unsupported type to test for starts with '{}'".format( other.__class__.__name__))
[ "def", "startswith", "(", "self", ",", "other", ")", ":", "if", "self", ".", "is_valid_range", "(", "other", ")", ":", "if", "self", ".", "lower_inc", "==", "other", ".", "lower_inc", ":", "return", "self", ".", "lower", "==", "other", ".", "lower", ...
Test if this range starts with `other`. `other` may be either range or scalar. >>> intrange(1, 5).startswith(1) True >>> intrange(1, 5).startswith(intrange(1, 10)) True :param other: Range or scalar to test. :return: ``True`` if this range starts with `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type.
[ "Test", "if", "this", "range", "starts", "with", "other", ".", "other", "may", "be", "either", "range", "or", "scalar", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L589-L617
runfalk/spans
spans/types.py
Range.endswith
def endswith(self, other): """ Test if this range ends with `other`. `other` may be either range or scalar. >>> intrange(1, 5).endswith(4) True >>> intrange(1, 10).endswith(intrange(5, 10)) True :param other: Range or scalar to test. :return: ``True`` if this range ends with `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type. """ if self.is_valid_range(other): if self.upper_inc == other.upper_inc: return self.upper == other.upper else: return False elif self.is_valid_scalar(other): if self.upper_inc: return self.upper == other else: return False else: raise TypeError( "Unsupported type to test for ends with '{}'".format( other.__class__.__name__))
python
def endswith(self, other): """ Test if this range ends with `other`. `other` may be either range or scalar. >>> intrange(1, 5).endswith(4) True >>> intrange(1, 10).endswith(intrange(5, 10)) True :param other: Range or scalar to test. :return: ``True`` if this range ends with `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type. """ if self.is_valid_range(other): if self.upper_inc == other.upper_inc: return self.upper == other.upper else: return False elif self.is_valid_scalar(other): if self.upper_inc: return self.upper == other else: return False else: raise TypeError( "Unsupported type to test for ends with '{}'".format( other.__class__.__name__))
[ "def", "endswith", "(", "self", ",", "other", ")", ":", "if", "self", ".", "is_valid_range", "(", "other", ")", ":", "if", "self", ".", "upper_inc", "==", "other", ".", "upper_inc", ":", "return", "self", ".", "upper", "==", "other", ".", "upper", "e...
Test if this range ends with `other`. `other` may be either range or scalar. >>> intrange(1, 5).endswith(4) True >>> intrange(1, 10).endswith(intrange(5, 10)) True :param other: Range or scalar to test. :return: ``True`` if this range ends with `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type.
[ "Test", "if", "this", "range", "ends", "with", "other", ".", "other", "may", "be", "either", "range", "or", "scalar", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L619-L647
runfalk/spans
spans/types.py
Range.startsafter
def startsafter(self, other): """ Test if this range starts after `other`. `other` may be either range or scalar. This only takes the lower end of the ranges into consideration. If the scalar or the lower end of the given range is greater than or equal to this range's lower end, ``True`` is returned. >>> intrange(1, 5).startsafter(0) True >>> intrange(1, 5).startsafter(intrange(0, 5)) True If ``other`` has the same start as the given :param other: Range or scalar to test. :return: ``True`` if this range starts after `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type. """ if self.is_valid_range(other): if self.lower == other.lower: return other.lower_inc or not self.lower_inc elif self.lower_inf: return False elif other.lower_inf: return True else: return self.lower > other.lower elif self.is_valid_scalar(other): return self.lower >= other else: raise TypeError( "Unsupported type to test for starts after '{}'".format( other.__class__.__name__))
python
def startsafter(self, other): """ Test if this range starts after `other`. `other` may be either range or scalar. This only takes the lower end of the ranges into consideration. If the scalar or the lower end of the given range is greater than or equal to this range's lower end, ``True`` is returned. >>> intrange(1, 5).startsafter(0) True >>> intrange(1, 5).startsafter(intrange(0, 5)) True If ``other`` has the same start as the given :param other: Range or scalar to test. :return: ``True`` if this range starts after `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type. """ if self.is_valid_range(other): if self.lower == other.lower: return other.lower_inc or not self.lower_inc elif self.lower_inf: return False elif other.lower_inf: return True else: return self.lower > other.lower elif self.is_valid_scalar(other): return self.lower >= other else: raise TypeError( "Unsupported type to test for starts after '{}'".format( other.__class__.__name__))
[ "def", "startsafter", "(", "self", ",", "other", ")", ":", "if", "self", ".", "is_valid_range", "(", "other", ")", ":", "if", "self", ".", "lower", "==", "other", ".", "lower", ":", "return", "other", ".", "lower_inc", "or", "not", "self", ".", "lowe...
Test if this range starts after `other`. `other` may be either range or scalar. This only takes the lower end of the ranges into consideration. If the scalar or the lower end of the given range is greater than or equal to this range's lower end, ``True`` is returned. >>> intrange(1, 5).startsafter(0) True >>> intrange(1, 5).startsafter(intrange(0, 5)) True If ``other`` has the same start as the given :param other: Range or scalar to test. :return: ``True`` if this range starts after `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type.
[ "Test", "if", "this", "range", "starts", "after", "other", ".", "other", "may", "be", "either", "range", "or", "scalar", ".", "This", "only", "takes", "the", "lower", "end", "of", "the", "ranges", "into", "consideration", ".", "If", "the", "scalar", "or"...
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L649-L682
runfalk/spans
spans/types.py
Range.endsbefore
def endsbefore(self, other): """ Test if this range ends before `other`. `other` may be either range or scalar. This only takes the upper end of the ranges into consideration. If the scalar or the upper end of the given range is less than or equal to this range's upper end, ``True`` is returned. >>> intrange(1, 5).endsbefore(5) True >>> intrange(1, 5).endsbefore(intrange(1, 5)) True :param other: Range or scalar to test. :return: ``True`` if this range ends before `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type. """ if self.is_valid_range(other): if self.upper == other.upper: return not self.upper_inc or other.upper_inc elif self.upper_inf: return False elif other.upper_inf: return True else: return self.upper <= other.upper elif self.is_valid_scalar(other): return self.upper <= other else: raise TypeError( "Unsupported type to test for ends before '{}'".format( other.__class__.__name__))
python
def endsbefore(self, other): """ Test if this range ends before `other`. `other` may be either range or scalar. This only takes the upper end of the ranges into consideration. If the scalar or the upper end of the given range is less than or equal to this range's upper end, ``True`` is returned. >>> intrange(1, 5).endsbefore(5) True >>> intrange(1, 5).endsbefore(intrange(1, 5)) True :param other: Range or scalar to test. :return: ``True`` if this range ends before `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type. """ if self.is_valid_range(other): if self.upper == other.upper: return not self.upper_inc or other.upper_inc elif self.upper_inf: return False elif other.upper_inf: return True else: return self.upper <= other.upper elif self.is_valid_scalar(other): return self.upper <= other else: raise TypeError( "Unsupported type to test for ends before '{}'".format( other.__class__.__name__))
[ "def", "endsbefore", "(", "self", ",", "other", ")", ":", "if", "self", ".", "is_valid_range", "(", "other", ")", ":", "if", "self", ".", "upper", "==", "other", ".", "upper", ":", "return", "not", "self", ".", "upper_inc", "or", "other", ".", "upper...
Test if this range ends before `other`. `other` may be either range or scalar. This only takes the upper end of the ranges into consideration. If the scalar or the upper end of the given range is less than or equal to this range's upper end, ``True`` is returned. >>> intrange(1, 5).endsbefore(5) True >>> intrange(1, 5).endsbefore(intrange(1, 5)) True :param other: Range or scalar to test. :return: ``True`` if this range ends before `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type.
[ "Test", "if", "this", "range", "ends", "before", "other", ".", "other", "may", "be", "either", "range", "or", "scalar", ".", "This", "only", "takes", "the", "upper", "end", "of", "the", "ranges", "into", "consideration", ".", "If", "the", "scalar", "or",...
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L684-L715
runfalk/spans
spans/types.py
Range.left_of
def left_of(self, other): """ Test if this range `other` is strictly left of `other`. >>> intrange(1, 5).left_of(intrange(5, 10)) True >>> intrange(1, 10).left_of(intrange(5, 10)) False The bitwise right shift operator ``<<`` is overloaded for this operation too. >>> intrange(1, 5) << intrange(5, 10) True The choice of overloading ``<<`` might seem strange, but it is to mimick PostgreSQL's operators for ranges. As this is not obvious the use of ``<<`` is discouraged. :param other: Range to test against. :return: ``True`` if this range is completely to the left of ``other``. """ if not self.is_valid_range(other): msg = ( "Left of is not supported for '{}', provide a proper range " "class").format(other.__class__.__name__) raise TypeError(msg) return self < other and not self.overlap(other)
python
def left_of(self, other): """ Test if this range `other` is strictly left of `other`. >>> intrange(1, 5).left_of(intrange(5, 10)) True >>> intrange(1, 10).left_of(intrange(5, 10)) False The bitwise right shift operator ``<<`` is overloaded for this operation too. >>> intrange(1, 5) << intrange(5, 10) True The choice of overloading ``<<`` might seem strange, but it is to mimick PostgreSQL's operators for ranges. As this is not obvious the use of ``<<`` is discouraged. :param other: Range to test against. :return: ``True`` if this range is completely to the left of ``other``. """ if not self.is_valid_range(other): msg = ( "Left of is not supported for '{}', provide a proper range " "class").format(other.__class__.__name__) raise TypeError(msg) return self < other and not self.overlap(other)
[ "def", "left_of", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "is_valid_range", "(", "other", ")", ":", "msg", "=", "(", "\"Left of is not supported for '{}', provide a proper range \"", "\"class\"", ")", ".", "format", "(", "other", ".", "_...
Test if this range `other` is strictly left of `other`. >>> intrange(1, 5).left_of(intrange(5, 10)) True >>> intrange(1, 10).left_of(intrange(5, 10)) False The bitwise right shift operator ``<<`` is overloaded for this operation too. >>> intrange(1, 5) << intrange(5, 10) True The choice of overloading ``<<`` might seem strange, but it is to mimick PostgreSQL's operators for ranges. As this is not obvious the use of ``<<`` is discouraged. :param other: Range to test against. :return: ``True`` if this range is completely to the left of ``other``.
[ "Test", "if", "this", "range", "other", "is", "strictly", "left", "of", "other", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L717-L746
runfalk/spans
spans/types.py
OffsetableRangeMixin.offset
def offset(self, offset): """ Shift the range to the left or right with the given offset >>> intrange(0, 5).offset(5) intrange([5,10)) >>> intrange(5, 10).offset(-5) intrange([0,5)) >>> intrange.empty().offset(5) intrange(empty) Note that range objects are immutable and are never modified in place. :param offset: Scalar to offset by. .. versionadded:: 0.1.3 """ # If range is empty it can't be offset if not self: return self offset_type = self.type if self.offset_type is None else self.offset_type if offset is not None and not isinstance(offset, offset_type): raise TypeError(( "Invalid type for offset '{offset_type.__name__}'" " expected '{expected_type.__name__}'").format( expected_type=offset_type, offset_type=offset.__class__)) lower = None if self.lower is None else self.lower + offset upper = None if self.upper is None else self.upper + offset return self.replace(lower=lower, upper=upper)
python
def offset(self, offset): """ Shift the range to the left or right with the given offset >>> intrange(0, 5).offset(5) intrange([5,10)) >>> intrange(5, 10).offset(-5) intrange([0,5)) >>> intrange.empty().offset(5) intrange(empty) Note that range objects are immutable and are never modified in place. :param offset: Scalar to offset by. .. versionadded:: 0.1.3 """ # If range is empty it can't be offset if not self: return self offset_type = self.type if self.offset_type is None else self.offset_type if offset is not None and not isinstance(offset, offset_type): raise TypeError(( "Invalid type for offset '{offset_type.__name__}'" " expected '{expected_type.__name__}'").format( expected_type=offset_type, offset_type=offset.__class__)) lower = None if self.lower is None else self.lower + offset upper = None if self.upper is None else self.upper + offset return self.replace(lower=lower, upper=upper)
[ "def", "offset", "(", "self", ",", "offset", ")", ":", "# If range is empty it can't be offset", "if", "not", "self", ":", "return", "self", "offset_type", "=", "self", ".", "type", "if", "self", ".", "offset_type", "is", "None", "else", "self", ".", "offset...
Shift the range to the left or right with the given offset >>> intrange(0, 5).offset(5) intrange([5,10)) >>> intrange(5, 10).offset(-5) intrange([0,5)) >>> intrange.empty().offset(5) intrange(empty) Note that range objects are immutable and are never modified in place. :param offset: Scalar to offset by. .. versionadded:: 0.1.3
[ "Shift", "the", "range", "to", "the", "left", "or", "right", "with", "the", "given", "offset" ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L972-L1006
runfalk/spans
spans/types.py
daterange.from_date
def from_date(cls, date, period=None): """ Create a day long daterange from for the given date. >>> daterange.from_date(date(2000, 1, 1)) daterange([datetime.date(2000, 1, 1),datetime.date(2000, 1, 2))) :param date: A date to convert. :param period: The period to normalize date to. A period may be one of: ``day`` (default), ``week``, ``american_week``, ``month``, ``quarter`` or ``year``. :return: A new range that contains the given date. .. seealso:: There are convenience methods for most period types: :meth:`~spans.types.daterange.from_week`, :meth:`~spans.types.daterange.from_month`, :meth:`~spans.types.daterange.from_quarter` and :meth:`~spans.types.daterange.from_year`. :class:`~spans.types.PeriodRange` has the same interface but is period aware. This means it is possible to get things like next week or month. .. versionchanged:: 0.4.0 Added the period parameter. """ if period is None or period == "day": return cls(date, date, upper_inc=True) elif period == "week": start = date - timedelta(date.weekday()) return cls(start, start + timedelta(7)) elif period == "american_week": start = date - timedelta((date.weekday() + 1) % 7) return cls(start, start + timedelta(7)) elif period == "month": start = date.replace(day=1) return cls(start, (start + timedelta(31)).replace(day=1)) elif period == "quarter": start = date.replace(month=(date.month - 1) // 3 * 3 + 1, day=1) return cls(start, (start + timedelta(93)).replace(day=1)) elif period == "year": start = date.replace(month=1, day=1) return cls(start, (start + timedelta(366)).replace(day=1)) else: raise ValueError("Unexpected period, got {!r}".format(period))
python
def from_date(cls, date, period=None): """ Create a day long daterange from for the given date. >>> daterange.from_date(date(2000, 1, 1)) daterange([datetime.date(2000, 1, 1),datetime.date(2000, 1, 2))) :param date: A date to convert. :param period: The period to normalize date to. A period may be one of: ``day`` (default), ``week``, ``american_week``, ``month``, ``quarter`` or ``year``. :return: A new range that contains the given date. .. seealso:: There are convenience methods for most period types: :meth:`~spans.types.daterange.from_week`, :meth:`~spans.types.daterange.from_month`, :meth:`~spans.types.daterange.from_quarter` and :meth:`~spans.types.daterange.from_year`. :class:`~spans.types.PeriodRange` has the same interface but is period aware. This means it is possible to get things like next week or month. .. versionchanged:: 0.4.0 Added the period parameter. """ if period is None or period == "day": return cls(date, date, upper_inc=True) elif period == "week": start = date - timedelta(date.weekday()) return cls(start, start + timedelta(7)) elif period == "american_week": start = date - timedelta((date.weekday() + 1) % 7) return cls(start, start + timedelta(7)) elif period == "month": start = date.replace(day=1) return cls(start, (start + timedelta(31)).replace(day=1)) elif period == "quarter": start = date.replace(month=(date.month - 1) // 3 * 3 + 1, day=1) return cls(start, (start + timedelta(93)).replace(day=1)) elif period == "year": start = date.replace(month=1, day=1) return cls(start, (start + timedelta(366)).replace(day=1)) else: raise ValueError("Unexpected period, got {!r}".format(period))
[ "def", "from_date", "(", "cls", ",", "date", ",", "period", "=", "None", ")", ":", "if", "period", "is", "None", "or", "period", "==", "\"day\"", ":", "return", "cls", "(", "date", ",", "date", ",", "upper_inc", "=", "True", ")", "elif", "period", ...
Create a day long daterange from for the given date. >>> daterange.from_date(date(2000, 1, 1)) daterange([datetime.date(2000, 1, 1),datetime.date(2000, 1, 2))) :param date: A date to convert. :param period: The period to normalize date to. A period may be one of: ``day`` (default), ``week``, ``american_week``, ``month``, ``quarter`` or ``year``. :return: A new range that contains the given date. .. seealso:: There are convenience methods for most period types: :meth:`~spans.types.daterange.from_week`, :meth:`~spans.types.daterange.from_month`, :meth:`~spans.types.daterange.from_quarter` and :meth:`~spans.types.daterange.from_year`. :class:`~spans.types.PeriodRange` has the same interface but is period aware. This means it is possible to get things like next week or month. .. versionchanged:: 0.4.0 Added the period parameter.
[ "Create", "a", "day", "long", "daterange", "from", "for", "the", "given", "date", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1155-L1203
runfalk/spans
spans/types.py
daterange.from_week
def from_week(cls, year, iso_week): """ Create ``daterange`` based on a year and an ISO week :param year: Year as an integer :param iso_week: ISO week number :return: A new ``daterange`` for the given week .. versionadded:: 0.4.0 """ first_day = date_from_iso_week(year, iso_week) return cls.from_date(first_day, period="week")
python
def from_week(cls, year, iso_week): """ Create ``daterange`` based on a year and an ISO week :param year: Year as an integer :param iso_week: ISO week number :return: A new ``daterange`` for the given week .. versionadded:: 0.4.0 """ first_day = date_from_iso_week(year, iso_week) return cls.from_date(first_day, period="week")
[ "def", "from_week", "(", "cls", ",", "year", ",", "iso_week", ")", ":", "first_day", "=", "date_from_iso_week", "(", "year", ",", "iso_week", ")", "return", "cls", ".", "from_date", "(", "first_day", ",", "period", "=", "\"week\"", ")" ]
Create ``daterange`` based on a year and an ISO week :param year: Year as an integer :param iso_week: ISO week number :return: A new ``daterange`` for the given week .. versionadded:: 0.4.0
[ "Create", "daterange", "based", "on", "a", "year", "and", "an", "ISO", "week" ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1206-L1218
runfalk/spans
spans/types.py
daterange.from_month
def from_month(cls, year, month): """ Create ``daterange`` based on a year and amonth :param year: Year as an integer :param iso_week: Month as an integer between 1 and 12 :return: A new ``daterange`` for the given month .. versionadded:: 0.4.0 """ first_day = date(year, month, 1) return cls.from_date(first_day, period="month")
python
def from_month(cls, year, month): """ Create ``daterange`` based on a year and amonth :param year: Year as an integer :param iso_week: Month as an integer between 1 and 12 :return: A new ``daterange`` for the given month .. versionadded:: 0.4.0 """ first_day = date(year, month, 1) return cls.from_date(first_day, period="month")
[ "def", "from_month", "(", "cls", ",", "year", ",", "month", ")", ":", "first_day", "=", "date", "(", "year", ",", "month", ",", "1", ")", "return", "cls", ".", "from_date", "(", "first_day", ",", "period", "=", "\"month\"", ")" ]
Create ``daterange`` based on a year and amonth :param year: Year as an integer :param iso_week: Month as an integer between 1 and 12 :return: A new ``daterange`` for the given month .. versionadded:: 0.4.0
[ "Create", "daterange", "based", "on", "a", "year", "and", "amonth" ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1224-L1236
runfalk/spans
spans/types.py
daterange.from_quarter
def from_quarter(cls, year, quarter): """ Create ``daterange`` based on a year and quarter. A quarter is considered to be: - January through March (Q1), - April through June (Q2), - July through September (Q3) or, - October through December (Q4) :param year: Year as an integer :param quarter: Quarter as an integer between 1 and 4 :return: A new ``daterange`` for the given quarter .. versionadded:: 0.4.0 """ quarter_months = { 1: 1, 2: 4, 3: 7, 4: 10, } if quarter not in quarter_months: error_msg = ( "quarter is not a valid quarter. Expected a value between 1 " "and 4 got {!r}") raise ValueError(error_msg.format(quarter)) first_day = date(year, quarter_months[quarter], 1) return cls.from_date(first_day, period="quarter")
python
def from_quarter(cls, year, quarter): """ Create ``daterange`` based on a year and quarter. A quarter is considered to be: - January through March (Q1), - April through June (Q2), - July through September (Q3) or, - October through December (Q4) :param year: Year as an integer :param quarter: Quarter as an integer between 1 and 4 :return: A new ``daterange`` for the given quarter .. versionadded:: 0.4.0 """ quarter_months = { 1: 1, 2: 4, 3: 7, 4: 10, } if quarter not in quarter_months: error_msg = ( "quarter is not a valid quarter. Expected a value between 1 " "and 4 got {!r}") raise ValueError(error_msg.format(quarter)) first_day = date(year, quarter_months[quarter], 1) return cls.from_date(first_day, period="quarter")
[ "def", "from_quarter", "(", "cls", ",", "year", ",", "quarter", ")", ":", "quarter_months", "=", "{", "1", ":", "1", ",", "2", ":", "4", ",", "3", ":", "7", ",", "4", ":", "10", ",", "}", "if", "quarter", "not", "in", "quarter_months", ":", "er...
Create ``daterange`` based on a year and quarter. A quarter is considered to be: - January through March (Q1), - April through June (Q2), - July through September (Q3) or, - October through December (Q4) :param year: Year as an integer :param quarter: Quarter as an integer between 1 and 4 :return: A new ``daterange`` for the given quarter .. versionadded:: 0.4.0
[ "Create", "daterange", "based", "on", "a", "year", "and", "quarter", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1239-L1271
runfalk/spans
spans/types.py
daterange.from_year
def from_year(cls, year): """ Create ``daterange`` based on a year :param year: Year as an integer :return: A new ``daterange`` for the given year .. versionadded:: 0.4.0 """ first_day = date(year, 1, 1) return cls.from_date(first_day, period="year")
python
def from_year(cls, year): """ Create ``daterange`` based on a year :param year: Year as an integer :return: A new ``daterange`` for the given year .. versionadded:: 0.4.0 """ first_day = date(year, 1, 1) return cls.from_date(first_day, period="year")
[ "def", "from_year", "(", "cls", ",", "year", ")", ":", "first_day", "=", "date", "(", "year", ",", "1", ",", "1", ")", "return", "cls", ".", "from_date", "(", "first_day", ",", "period", "=", "\"year\"", ")" ]
Create ``daterange`` based on a year :param year: Year as an integer :return: A new ``daterange`` for the given year .. versionadded:: 0.4.0
[ "Create", "daterange", "based", "on", "a", "year" ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1274-L1285
runfalk/spans
spans/types.py
PeriodRange.daterange
def daterange(self): """ This ``PeriodRange`` represented as a naive :class:`~spans.types.daterange`. """ return daterange( lower=self.lower, upper=self.upper, lower_inc=self.lower_inc, upper_inc=self.upper_inc)
python
def daterange(self): """ This ``PeriodRange`` represented as a naive :class:`~spans.types.daterange`. """ return daterange( lower=self.lower, upper=self.upper, lower_inc=self.lower_inc, upper_inc=self.upper_inc)
[ "def", "daterange", "(", "self", ")", ":", "return", "daterange", "(", "lower", "=", "self", ".", "lower", ",", "upper", "=", "self", ".", "upper", ",", "lower_inc", "=", "self", ".", "lower_inc", ",", "upper_inc", "=", "self", ".", "upper_inc", ")" ]
This ``PeriodRange`` represented as a naive :class:`~spans.types.daterange`.
[ "This", "PeriodRange", "represented", "as", "a", "naive", ":", "class", ":", "~spans", ".", "types", ".", "daterange", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1394-L1404
runfalk/spans
spans/types.py
PeriodRange.offset
def offset(self, offset): """ Offset the date range by the given amount of periods. This differs from :meth:`~spans.types.OffsetableRangeMixin.offset` on :class:`spans.types.daterange` by not accepting a ``timedelta`` object. Instead it expects an integer to adjust the typed date range by. The given value may be negative as well. :param offset: Number of periods to offset this range by. A period is either a day, week, american week, month, quarter or year, depending on this range's period type. :return: New offset :class:`~spans.types.PeriodRange` """ span = self if offset > 0: for i in iter_range(offset): span = span.next_period() elif offset < 0: for i in iter_range(-offset): span = span.prev_period() return span
python
def offset(self, offset): """ Offset the date range by the given amount of periods. This differs from :meth:`~spans.types.OffsetableRangeMixin.offset` on :class:`spans.types.daterange` by not accepting a ``timedelta`` object. Instead it expects an integer to adjust the typed date range by. The given value may be negative as well. :param offset: Number of periods to offset this range by. A period is either a day, week, american week, month, quarter or year, depending on this range's period type. :return: New offset :class:`~spans.types.PeriodRange` """ span = self if offset > 0: for i in iter_range(offset): span = span.next_period() elif offset < 0: for i in iter_range(-offset): span = span.prev_period() return span
[ "def", "offset", "(", "self", ",", "offset", ")", ":", "span", "=", "self", "if", "offset", ">", "0", ":", "for", "i", "in", "iter_range", "(", "offset", ")", ":", "span", "=", "span", ".", "next_period", "(", ")", "elif", "offset", "<", "0", ":"...
Offset the date range by the given amount of periods. This differs from :meth:`~spans.types.OffsetableRangeMixin.offset` on :class:`spans.types.daterange` by not accepting a ``timedelta`` object. Instead it expects an integer to adjust the typed date range by. The given value may be negative as well. :param offset: Number of periods to offset this range by. A period is either a day, week, american week, month, quarter or year, depending on this range's period type. :return: New offset :class:`~spans.types.PeriodRange`
[ "Offset", "the", "date", "range", "by", "the", "given", "amount", "of", "periods", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1406-L1428
runfalk/spans
spans/types.py
PeriodRange.prev_period
def prev_period(self): """ The period before this range. >>> span = PeriodRange.from_date(date(2000, 1, 1), period="month") >>> span.prev_period() PeriodRange([datetime.date(1999, 12, 1),datetime.date(2000, 1, 1))) :return: A new :class:`~spans.types.PeriodRange` for the period before this period """ return self.from_date(self.prev(self.lower), period=self.period)
python
def prev_period(self): """ The period before this range. >>> span = PeriodRange.from_date(date(2000, 1, 1), period="month") >>> span.prev_period() PeriodRange([datetime.date(1999, 12, 1),datetime.date(2000, 1, 1))) :return: A new :class:`~spans.types.PeriodRange` for the period before this period """ return self.from_date(self.prev(self.lower), period=self.period)
[ "def", "prev_period", "(", "self", ")", ":", "return", "self", ".", "from_date", "(", "self", ".", "prev", "(", "self", ".", "lower", ")", ",", "period", "=", "self", ".", "period", ")" ]
The period before this range. >>> span = PeriodRange.from_date(date(2000, 1, 1), period="month") >>> span.prev_period() PeriodRange([datetime.date(1999, 12, 1),datetime.date(2000, 1, 1))) :return: A new :class:`~spans.types.PeriodRange` for the period before this period
[ "The", "period", "before", "this", "range", "." ]
train
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1430-L1442
JMSwag/dsdev-utils
dsdev_utils/crypto.py
get_package_hashes
def get_package_hashes(filename): """Provides hash of given filename. Args: filename (str): Name of file to hash Returns: (str): sha256 hash """ log.debug('Getting package hashes') filename = os.path.abspath(filename) with open(filename, 'rb') as f: data = f.read() _hash = hashlib.sha256(data).hexdigest() log.debug('Hash for file %s: %s', filename, _hash) return _hash
python
def get_package_hashes(filename): """Provides hash of given filename. Args: filename (str): Name of file to hash Returns: (str): sha256 hash """ log.debug('Getting package hashes') filename = os.path.abspath(filename) with open(filename, 'rb') as f: data = f.read() _hash = hashlib.sha256(data).hexdigest() log.debug('Hash for file %s: %s', filename, _hash) return _hash
[ "def", "get_package_hashes", "(", "filename", ")", ":", "log", ".", "debug", "(", "'Getting package hashes'", ")", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":"...
Provides hash of given filename. Args: filename (str): Name of file to hash Returns: (str): sha256 hash
[ "Provides", "hash", "of", "given", "filename", "." ]
train
https://github.com/JMSwag/dsdev-utils/blob/5adbf9b3fd9fff92d1dd714423b08e26a5038e14/dsdev_utils/crypto.py#L31-L49
facelessuser/pyspelling
pyspelling/filters/stylesheets.py
StylesheetsFilter.setup
def setup(self): """Setup.""" self.blocks = self.config['block_comments'] self.lines = self.config['line_comments'] self.group_comments = self.config['group_comments'] # If the style isn't found, just go with CSS, then use the appropriate prefix. self.stylesheets = STYLESHEET_TYPE.get(self.config['stylesheets'].lower(), CSS) self.prefix = [k for k, v in STYLESHEET_TYPE.items() if v == SASS][0] self.pattern = RE_CSS if self.stylesheets == CSS else RE_SCSS
python
def setup(self): """Setup.""" self.blocks = self.config['block_comments'] self.lines = self.config['line_comments'] self.group_comments = self.config['group_comments'] # If the style isn't found, just go with CSS, then use the appropriate prefix. self.stylesheets = STYLESHEET_TYPE.get(self.config['stylesheets'].lower(), CSS) self.prefix = [k for k, v in STYLESHEET_TYPE.items() if v == SASS][0] self.pattern = RE_CSS if self.stylesheets == CSS else RE_SCSS
[ "def", "setup", "(", "self", ")", ":", "self", ".", "blocks", "=", "self", ".", "config", "[", "'block_comments'", "]", "self", ".", "lines", "=", "self", ".", "config", "[", "'line_comments'", "]", "self", ".", "group_comments", "=", "self", ".", "con...
Setup.
[ "Setup", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/stylesheets.py#L62-L71
facelessuser/pyspelling
pyspelling/filters/stylesheets.py
StylesheetsFilter.evaluate
def evaluate(self, m): """Search for comments.""" g = m.groupdict() if g["strings"]: self.line_num += g['strings'].count('\n') elif g["code"]: self.line_num += g["code"].count('\n') else: if g['block']: self.evaluate_block(g) elif self.stylesheets != CSS: if g['start'] is None: self.evaluate_inline_tail(g) else: self.evaluate_inline(g) self.line_num += g['comments'].count('\n')
python
def evaluate(self, m): """Search for comments.""" g = m.groupdict() if g["strings"]: self.line_num += g['strings'].count('\n') elif g["code"]: self.line_num += g["code"].count('\n') else: if g['block']: self.evaluate_block(g) elif self.stylesheets != CSS: if g['start'] is None: self.evaluate_inline_tail(g) else: self.evaluate_inline(g) self.line_num += g['comments'].count('\n')
[ "def", "evaluate", "(", "self", ",", "m", ")", ":", "g", "=", "m", ".", "groupdict", "(", ")", "if", "g", "[", "\"strings\"", "]", ":", "self", ".", "line_num", "+=", "g", "[", "'strings'", "]", ".", "count", "(", "'\\n'", ")", "elif", "g", "["...
Search for comments.
[ "Search", "for", "comments", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/stylesheets.py#L104-L120
facelessuser/pyspelling
pyspelling/filters/stylesheets.py
StylesheetsFilter.extend_src
def extend_src(self, content, context): """Extend source list.""" self.extend_src_text(content, context, self.block_comments, 'block-comment') self.extend_src_text(content, context, self.line_comments, 'line-comment')
python
def extend_src(self, content, context): """Extend source list.""" self.extend_src_text(content, context, self.block_comments, 'block-comment') self.extend_src_text(content, context, self.line_comments, 'line-comment')
[ "def", "extend_src", "(", "self", ",", "content", ",", "context", ")", ":", "self", ".", "extend_src_text", "(", "content", ",", "context", ",", "self", ".", "block_comments", ",", "'block-comment'", ")", "self", ".", "extend_src_text", "(", "content", ",", ...
Extend source list.
[ "Extend", "source", "list", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/stylesheets.py#L137-L141
facelessuser/pyspelling
pyspelling/filters/stylesheets.py
StylesheetsFilter.find_content
def find_content(self, text): """Find content.""" for m in self.pattern.finditer(self.norm_nl(text)): self.evaluate(m)
python
def find_content(self, text): """Find content.""" for m in self.pattern.finditer(self.norm_nl(text)): self.evaluate(m)
[ "def", "find_content", "(", "self", ",", "text", ")", ":", "for", "m", "in", "self", ".", "pattern", ".", "finditer", "(", "self", ".", "norm_nl", "(", "text", ")", ")", ":", "self", ".", "evaluate", "(", "m", ")" ]
Find content.
[ "Find", "content", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/stylesheets.py#L143-L147
facelessuser/pyspelling
pyspelling/filters/stylesheets.py
StylesheetsFilter._filter
def _filter(self, text, context, encoding): """Filter JavaScript comments.""" content = [] self.current_encoding = encoding self.line_num = 1 self.prev_line = -1 self.leading = '' self.block_comments = [] self.line_comments = [] self.find_content(text) self.extend_src(content, context) return content
python
def _filter(self, text, context, encoding): """Filter JavaScript comments.""" content = [] self.current_encoding = encoding self.line_num = 1 self.prev_line = -1 self.leading = '' self.block_comments = [] self.line_comments = [] self.find_content(text) self.extend_src(content, context) return content
[ "def", "_filter", "(", "self", ",", "text", ",", "context", ",", "encoding", ")", ":", "content", "=", "[", "]", "self", ".", "current_encoding", "=", "encoding", "self", ".", "line_num", "=", "1", "self", ".", "prev_line", "=", "-", "1", "self", "."...
Filter JavaScript comments.
[ "Filter", "JavaScript", "comments", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/stylesheets.py#L149-L163
deshima-dev/decode
decode/io/functions.py
loaddfits
def loaddfits(fitsname, coordtype='azel', loadtype='temperature', starttime=None, endtime=None, pixelids=None, scantypes=None, mode=0, **kwargs): """Load a decode array from a DFITS file. Args: fitsname (str): Name of DFITS file. coordtype (str): Coordinate type included into a decode array. 'azel': Azimuth / elevation. 'radec': Right ascension / declination. loadtype (str): Data unit of xarray. 'Tsignal': Temperature [K]. 'Psignal': Power [W]. 'amplitude': Amplitude. 'phase': Phase. 'linphase': Linear phase. starttime (int, str or numpy.datetime64): Start time of loaded data. It can be specified by the start index (int), the time compatible with numpy.datetime64 (str), or numpy.datetime64 (numpy.datetime64). Default is None and it means the data will be loaded from the first record. endtime (int, str or numpy.datetime64): End time of loaded data. It can be specified by the end index (int), the time compatible with numpy.datetime64 (str), or numpy.datetime64 (numpy.datetime64). Default is None and it means the data will be loaded until the last record. pixelids (int or list): Under development. scantypes (list(str)): Scan types, such as 'GRAD', 'SCAN', 'OFF', 'R', and so on. mode (int): Loading mode. 0: Relative coordinates with cosine projection (RECOMMENDED). 1: Relative coordinates without cosine projection. 2: Absolute coordinates. kwargs (optional): findR (bool): Automatically find R positions. ch (int): Representative channel id used for finding R. Rth (float): Threshold of R. skyth (flaot): Threshold of sky. cutnum (int): The number of points of unused data at the edge. still (bool): When it is true, scantypes of on/off are manually assigned. period (float): On/off period in second for still data. shuttle (bool): For shuttle observations. xmin_off (float): Minimum x of off-point data. xmax_off (float): Maximum x of off-point data. xmin_on (float): Minimum x of on-point data. xmax_on (float): Maximum x of on-point data. Returns: decode array (decode.array): Loaded decode array. """ if mode not in [0, 1, 2]: raise KeyError(mode) logger.info('coordtype starttime endtime mode loadtype') logger.info('{} {} {} {} {}'.format(coordtype, starttime, endtime, mode, loadtype)) ### pick up kwargs # for findR findR = kwargs.pop('findR', False) ch = kwargs.pop('ch', 0) Rth = kwargs.pop('Rth', 280) skyth = kwargs.pop('skyth', 150) cutnum = kwargs.pop('cutnum', 1) # for still still = kwargs.pop('still', False) period = kwargs.pop('period', 2) # for shuttle shuttle = kwargs.pop('shuttle', False) xmin_off = kwargs.pop('xmin_off', 0) xmax_off = kwargs.pop('xmax_off', 0) xmin_on = kwargs.pop('xmin_on', 0) xmax_on = kwargs.pop('xmax_on', 0) ### load data fitsname = str(Path(fitsname).expanduser()) with fits.open(fitsname) as hdulist: obsinfo = hdulist['OBSINFO'].data obshdr = hdulist['OBSINFO'].header antlog = hdulist['ANTENNA'].data readout = hdulist['READOUT'].data wealog = hdulist['WEATHER'].data ### obsinfo masterids = obsinfo['masterids'][0].astype(np.int64) kidids = obsinfo['kidids'][0].astype(np.int64) kidfreqs = obsinfo['kidfreqs'][0].astype(np.float64) kidtypes = obsinfo['kidtypes'][0].astype(np.int64) ### parse start/end time t_ant = np.array(antlog['time']).astype(np.datetime64) t_out = np.array(readout['starttime']).astype(np.datetime64) t_wea = np.array(wealog['time']).astype(np.datetime64) if starttime is None: startindex = 0 elif isinstance(starttime, int): startindex = starttime elif isinstance(starttime, str): startindex = np.searchsorted(t_out, np.datetime64(starttime)) elif isinstance(starttime, np.datetime64): startindex = np.searchsorted(t_out, starttime) else: raise ValueError(starttime) if endtime is None: endindex = t_out.shape[0] elif isinstance(endtime, int): endindex = endtime elif isinstance(endtime, str): endindex = np.searchsorted(t_out, np.datetime64(endtime), 'right') elif isinstance(endtime, np.datetime64): endindex = np.searchsorted(t_out, endtime, 'right') else: raise ValueError(starttime) if t_out[endindex-1] > t_ant[-1]: logger.warning('Endtime of readout is adjusted to that of ANTENNA HDU.') endindex = np.searchsorted(t_out, t_ant[-1], 'right') t_out = t_out[startindex:endindex] ### readout pixelid = readout['pixelid'][startindex:endindex] if loadtype == 'temperature': response = readout['Tsignal'][startindex:endindex].astype(np.float64) elif loadtype == 'power': response = readout['Psignal'][startindex:endindex].astype(np.float64) elif loadtype == 'amplitude': response = readout['amplitude'][startindex:endindex].astype(np.float64) elif loadtype == 'phase': response = readout['phase'][startindex:endindex].astype(np.float64) elif loadtype == 'linphase': response = readout['line_phase'][startindex:endindex].astype(np.float64) else: raise KeyError(loadtype) ### antenna if coordtype == 'azel': x = antlog['az'].copy() y = antlog['el'].copy() xref = np.median(antlog['az_center']) yref = np.median(antlog['el_center']) if mode in [0, 1]: x -= antlog['az_center'] y -= antlog['el_center'] if mode == 0: x *= np.cos(np.deg2rad(antlog['el'])) elif coordtype == 'radec': x = antlog['ra'].copy() y = antlog['dec'].copy() xref = obshdr['RA'] yref = obshdr['DEC'] if mode in [0, 1]: x -= xref y -= yref if mode == 0: x *= np.cos(np.deg2rad(antlog['dec'])) else: raise KeyError(coordtype) scantype = antlog['scantype'] ### weatherlog temp = wealog['temperature'] pressure = wealog['pressure'] vpressure = wealog['vapor-pressure'] windspd = wealog['windspd'] winddir = wealog['winddir'] ### interpolation dt_out = (t_out - t_out[0]) / np.timedelta64(1, 's') dt_ant = (t_ant - t_out[0]) / np.timedelta64(1, 's') dt_wea = (t_wea - t_out[0]) / np.timedelta64(1, 's') x_i = np.interp(dt_out, dt_ant, x) y_i = np.interp(dt_out, dt_ant, y) temp_i = np.interp(dt_out, dt_wea, temp) pressure_i = np.interp(dt_out, dt_wea, pressure) vpressure_i = np.interp(dt_out, dt_wea, vpressure) windspd_i = np.interp(dt_out, dt_wea, windspd) winddir_i = np.interp(dt_out, dt_wea, winddir) scandict = {t: n for n, t in enumerate(np.unique(scantype))} scantype_v = np.zeros(scantype.shape[0], dtype=int) for k, v in scandict.items(): scantype_v[scantype == k] = v scantype_vi = interp1d(dt_ant, scantype_v, kind='nearest', bounds_error=False, fill_value=(scantype_v[0], scantype_v[-1]))(dt_out) scantype_i = np.full_like(scantype_vi, 'GRAD', dtype='<U8') for k, v in scandict.items(): scantype_i[scantype_vi == v] = k ### for still data if still: for n in range(int(dt_out[-1]) // period + 1): offmask = (period*2*n <= dt_out) & (dt_out < period*(2*n+1)) onmask = (period*(2*n+1) <= dt_out) & (dt_out < period*(2*n+2)) scantype_i[offmask] = 'OFF' scantype_i[onmask] = 'SCAN' if shuttle: offmask = (xmin_off < x_i) & (x_i < xmax_off) onmask = (xmin_on < x_i) & (x_i < xmax_on) scantype_i[offmask] = 'OFF' scantype_i[onmask] = 'SCAN' scantype_i[(~offmask) & (~onmask)] = 'JUNK' if findR: Rindex = np.where(response[:, ch] >= Rth) scantype_i[Rindex] = 'R' movemask = np.hstack([[False] * cutnum, scantype_i[cutnum:] != scantype_i[:-cutnum]]) | \ np.hstack([scantype_i[:-cutnum] != scantype_i[cutnum:], [False] * cutnum]) & (scantype_i == 'R') scantype_i[movemask] = 'JUNK' scantype_i[(response[:, ch] > skyth) & (scantype_i != 'R')] = 'JUNK' scantype_i[(response[:, ch] <= skyth) & (scantype_i == 'R')] = 'JUNK' skyindex = np.where(response[:, ch] <= skyth) scantype_i_temp = scantype_i.copy() scantype_i_temp[skyindex] = 'SKY' movemask = np.hstack([[False] * cutnum, scantype_i_temp[cutnum:] != scantype_i_temp[:-cutnum]]) | \ np.hstack([scantype_i_temp[:-cutnum] != scantype_i_temp[cutnum:], [False] * cutnum]) & (scantype_i_temp == 'SKY') scantype_i[movemask] = 'JUNK' ### scanid scanid_i = np.cumsum(np.hstack([False, scantype_i[1:] != scantype_i[:-1]])) ### coordinates tcoords = {'x': x_i, 'y': y_i, 'time': t_out, 'temp': temp_i, 'pressure': pressure_i, 'vapor-pressure': vpressure_i, 'windspd': windspd_i, 'winddir': winddir_i, 'scantype': scantype_i, 'scanid': scanid_i} chcoords = {'masterid': masterids, 'kidid': kidids, 'kidfq': kidfreqs, 'kidtp': kidtypes} scalarcoords = {'coordsys': coordtype.upper(), 'datatype': loadtype, 'xref': xref, 'yref': yref} ### make array array = dc.array(response, tcoords=tcoords, chcoords=chcoords, scalarcoords=scalarcoords) if scantypes is not None: mask = np.full(array.shape[0], False) for scantype in scantypes: mask |= (array.scantype == scantype) array = array[mask] return array
python
def loaddfits(fitsname, coordtype='azel', loadtype='temperature', starttime=None, endtime=None, pixelids=None, scantypes=None, mode=0, **kwargs): """Load a decode array from a DFITS file. Args: fitsname (str): Name of DFITS file. coordtype (str): Coordinate type included into a decode array. 'azel': Azimuth / elevation. 'radec': Right ascension / declination. loadtype (str): Data unit of xarray. 'Tsignal': Temperature [K]. 'Psignal': Power [W]. 'amplitude': Amplitude. 'phase': Phase. 'linphase': Linear phase. starttime (int, str or numpy.datetime64): Start time of loaded data. It can be specified by the start index (int), the time compatible with numpy.datetime64 (str), or numpy.datetime64 (numpy.datetime64). Default is None and it means the data will be loaded from the first record. endtime (int, str or numpy.datetime64): End time of loaded data. It can be specified by the end index (int), the time compatible with numpy.datetime64 (str), or numpy.datetime64 (numpy.datetime64). Default is None and it means the data will be loaded until the last record. pixelids (int or list): Under development. scantypes (list(str)): Scan types, such as 'GRAD', 'SCAN', 'OFF', 'R', and so on. mode (int): Loading mode. 0: Relative coordinates with cosine projection (RECOMMENDED). 1: Relative coordinates without cosine projection. 2: Absolute coordinates. kwargs (optional): findR (bool): Automatically find R positions. ch (int): Representative channel id used for finding R. Rth (float): Threshold of R. skyth (flaot): Threshold of sky. cutnum (int): The number of points of unused data at the edge. still (bool): When it is true, scantypes of on/off are manually assigned. period (float): On/off period in second for still data. shuttle (bool): For shuttle observations. xmin_off (float): Minimum x of off-point data. xmax_off (float): Maximum x of off-point data. xmin_on (float): Minimum x of on-point data. xmax_on (float): Maximum x of on-point data. Returns: decode array (decode.array): Loaded decode array. """ if mode not in [0, 1, 2]: raise KeyError(mode) logger.info('coordtype starttime endtime mode loadtype') logger.info('{} {} {} {} {}'.format(coordtype, starttime, endtime, mode, loadtype)) ### pick up kwargs # for findR findR = kwargs.pop('findR', False) ch = kwargs.pop('ch', 0) Rth = kwargs.pop('Rth', 280) skyth = kwargs.pop('skyth', 150) cutnum = kwargs.pop('cutnum', 1) # for still still = kwargs.pop('still', False) period = kwargs.pop('period', 2) # for shuttle shuttle = kwargs.pop('shuttle', False) xmin_off = kwargs.pop('xmin_off', 0) xmax_off = kwargs.pop('xmax_off', 0) xmin_on = kwargs.pop('xmin_on', 0) xmax_on = kwargs.pop('xmax_on', 0) ### load data fitsname = str(Path(fitsname).expanduser()) with fits.open(fitsname) as hdulist: obsinfo = hdulist['OBSINFO'].data obshdr = hdulist['OBSINFO'].header antlog = hdulist['ANTENNA'].data readout = hdulist['READOUT'].data wealog = hdulist['WEATHER'].data ### obsinfo masterids = obsinfo['masterids'][0].astype(np.int64) kidids = obsinfo['kidids'][0].astype(np.int64) kidfreqs = obsinfo['kidfreqs'][0].astype(np.float64) kidtypes = obsinfo['kidtypes'][0].astype(np.int64) ### parse start/end time t_ant = np.array(antlog['time']).astype(np.datetime64) t_out = np.array(readout['starttime']).astype(np.datetime64) t_wea = np.array(wealog['time']).astype(np.datetime64) if starttime is None: startindex = 0 elif isinstance(starttime, int): startindex = starttime elif isinstance(starttime, str): startindex = np.searchsorted(t_out, np.datetime64(starttime)) elif isinstance(starttime, np.datetime64): startindex = np.searchsorted(t_out, starttime) else: raise ValueError(starttime) if endtime is None: endindex = t_out.shape[0] elif isinstance(endtime, int): endindex = endtime elif isinstance(endtime, str): endindex = np.searchsorted(t_out, np.datetime64(endtime), 'right') elif isinstance(endtime, np.datetime64): endindex = np.searchsorted(t_out, endtime, 'right') else: raise ValueError(starttime) if t_out[endindex-1] > t_ant[-1]: logger.warning('Endtime of readout is adjusted to that of ANTENNA HDU.') endindex = np.searchsorted(t_out, t_ant[-1], 'right') t_out = t_out[startindex:endindex] ### readout pixelid = readout['pixelid'][startindex:endindex] if loadtype == 'temperature': response = readout['Tsignal'][startindex:endindex].astype(np.float64) elif loadtype == 'power': response = readout['Psignal'][startindex:endindex].astype(np.float64) elif loadtype == 'amplitude': response = readout['amplitude'][startindex:endindex].astype(np.float64) elif loadtype == 'phase': response = readout['phase'][startindex:endindex].astype(np.float64) elif loadtype == 'linphase': response = readout['line_phase'][startindex:endindex].astype(np.float64) else: raise KeyError(loadtype) ### antenna if coordtype == 'azel': x = antlog['az'].copy() y = antlog['el'].copy() xref = np.median(antlog['az_center']) yref = np.median(antlog['el_center']) if mode in [0, 1]: x -= antlog['az_center'] y -= antlog['el_center'] if mode == 0: x *= np.cos(np.deg2rad(antlog['el'])) elif coordtype == 'radec': x = antlog['ra'].copy() y = antlog['dec'].copy() xref = obshdr['RA'] yref = obshdr['DEC'] if mode in [0, 1]: x -= xref y -= yref if mode == 0: x *= np.cos(np.deg2rad(antlog['dec'])) else: raise KeyError(coordtype) scantype = antlog['scantype'] ### weatherlog temp = wealog['temperature'] pressure = wealog['pressure'] vpressure = wealog['vapor-pressure'] windspd = wealog['windspd'] winddir = wealog['winddir'] ### interpolation dt_out = (t_out - t_out[0]) / np.timedelta64(1, 's') dt_ant = (t_ant - t_out[0]) / np.timedelta64(1, 's') dt_wea = (t_wea - t_out[0]) / np.timedelta64(1, 's') x_i = np.interp(dt_out, dt_ant, x) y_i = np.interp(dt_out, dt_ant, y) temp_i = np.interp(dt_out, dt_wea, temp) pressure_i = np.interp(dt_out, dt_wea, pressure) vpressure_i = np.interp(dt_out, dt_wea, vpressure) windspd_i = np.interp(dt_out, dt_wea, windspd) winddir_i = np.interp(dt_out, dt_wea, winddir) scandict = {t: n for n, t in enumerate(np.unique(scantype))} scantype_v = np.zeros(scantype.shape[0], dtype=int) for k, v in scandict.items(): scantype_v[scantype == k] = v scantype_vi = interp1d(dt_ant, scantype_v, kind='nearest', bounds_error=False, fill_value=(scantype_v[0], scantype_v[-1]))(dt_out) scantype_i = np.full_like(scantype_vi, 'GRAD', dtype='<U8') for k, v in scandict.items(): scantype_i[scantype_vi == v] = k ### for still data if still: for n in range(int(dt_out[-1]) // period + 1): offmask = (period*2*n <= dt_out) & (dt_out < period*(2*n+1)) onmask = (period*(2*n+1) <= dt_out) & (dt_out < period*(2*n+2)) scantype_i[offmask] = 'OFF' scantype_i[onmask] = 'SCAN' if shuttle: offmask = (xmin_off < x_i) & (x_i < xmax_off) onmask = (xmin_on < x_i) & (x_i < xmax_on) scantype_i[offmask] = 'OFF' scantype_i[onmask] = 'SCAN' scantype_i[(~offmask) & (~onmask)] = 'JUNK' if findR: Rindex = np.where(response[:, ch] >= Rth) scantype_i[Rindex] = 'R' movemask = np.hstack([[False] * cutnum, scantype_i[cutnum:] != scantype_i[:-cutnum]]) | \ np.hstack([scantype_i[:-cutnum] != scantype_i[cutnum:], [False] * cutnum]) & (scantype_i == 'R') scantype_i[movemask] = 'JUNK' scantype_i[(response[:, ch] > skyth) & (scantype_i != 'R')] = 'JUNK' scantype_i[(response[:, ch] <= skyth) & (scantype_i == 'R')] = 'JUNK' skyindex = np.where(response[:, ch] <= skyth) scantype_i_temp = scantype_i.copy() scantype_i_temp[skyindex] = 'SKY' movemask = np.hstack([[False] * cutnum, scantype_i_temp[cutnum:] != scantype_i_temp[:-cutnum]]) | \ np.hstack([scantype_i_temp[:-cutnum] != scantype_i_temp[cutnum:], [False] * cutnum]) & (scantype_i_temp == 'SKY') scantype_i[movemask] = 'JUNK' ### scanid scanid_i = np.cumsum(np.hstack([False, scantype_i[1:] != scantype_i[:-1]])) ### coordinates tcoords = {'x': x_i, 'y': y_i, 'time': t_out, 'temp': temp_i, 'pressure': pressure_i, 'vapor-pressure': vpressure_i, 'windspd': windspd_i, 'winddir': winddir_i, 'scantype': scantype_i, 'scanid': scanid_i} chcoords = {'masterid': masterids, 'kidid': kidids, 'kidfq': kidfreqs, 'kidtp': kidtypes} scalarcoords = {'coordsys': coordtype.upper(), 'datatype': loadtype, 'xref': xref, 'yref': yref} ### make array array = dc.array(response, tcoords=tcoords, chcoords=chcoords, scalarcoords=scalarcoords) if scantypes is not None: mask = np.full(array.shape[0], False) for scantype in scantypes: mask |= (array.scantype == scantype) array = array[mask] return array
[ "def", "loaddfits", "(", "fitsname", ",", "coordtype", "=", "'azel'", ",", "loadtype", "=", "'temperature'", ",", "starttime", "=", "None", ",", "endtime", "=", "None", ",", "pixelids", "=", "None", ",", "scantypes", "=", "None", ",", "mode", "=", "0", ...
Load a decode array from a DFITS file. Args: fitsname (str): Name of DFITS file. coordtype (str): Coordinate type included into a decode array. 'azel': Azimuth / elevation. 'radec': Right ascension / declination. loadtype (str): Data unit of xarray. 'Tsignal': Temperature [K]. 'Psignal': Power [W]. 'amplitude': Amplitude. 'phase': Phase. 'linphase': Linear phase. starttime (int, str or numpy.datetime64): Start time of loaded data. It can be specified by the start index (int), the time compatible with numpy.datetime64 (str), or numpy.datetime64 (numpy.datetime64). Default is None and it means the data will be loaded from the first record. endtime (int, str or numpy.datetime64): End time of loaded data. It can be specified by the end index (int), the time compatible with numpy.datetime64 (str), or numpy.datetime64 (numpy.datetime64). Default is None and it means the data will be loaded until the last record. pixelids (int or list): Under development. scantypes (list(str)): Scan types, such as 'GRAD', 'SCAN', 'OFF', 'R', and so on. mode (int): Loading mode. 0: Relative coordinates with cosine projection (RECOMMENDED). 1: Relative coordinates without cosine projection. 2: Absolute coordinates. kwargs (optional): findR (bool): Automatically find R positions. ch (int): Representative channel id used for finding R. Rth (float): Threshold of R. skyth (flaot): Threshold of sky. cutnum (int): The number of points of unused data at the edge. still (bool): When it is true, scantypes of on/off are manually assigned. period (float): On/off period in second for still data. shuttle (bool): For shuttle observations. xmin_off (float): Minimum x of off-point data. xmax_off (float): Maximum x of off-point data. xmin_on (float): Minimum x of on-point data. xmax_on (float): Maximum x of on-point data. Returns: decode array (decode.array): Loaded decode array.
[ "Load", "a", "decode", "array", "from", "a", "DFITS", "file", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/io/functions.py#L29-L265
deshima-dev/decode
decode/io/functions.py
savefits
def savefits(cube, fitsname, **kwargs): """Save a cube to a 3D-cube FITS file. Args: cube (xarray.DataArray): Cube to be saved. fitsname (str): Name of output FITS file. kwargs (optional): Other arguments common with astropy.io.fits.writeto(). """ ### pick up kwargs dropdeg = kwargs.pop('dropdeg', False) ndim = len(cube.dims) ### load yaml FITSINFO = get_data('decode', 'data/fitsinfo.yaml') hdrdata = yaml.load(FITSINFO, dc.utils.OrderedLoader) ### default header if ndim == 2: header = fits.Header(hdrdata['dcube_2d']) data = cube.values.T elif ndim == 3: if dropdeg: header = fits.Header(hdrdata['dcube_2d']) data = cube.values[:, :, 0].T else: header = fits.Header(hdrdata['dcube_3d']) kidfq = cube.kidfq.values freqrange = ~np.isnan(kidfq) orderedfq = np.argsort(kidfq[freqrange]) newcube = cube[:, :, orderedfq] data = newcube.values.T else: raise TypeError(ndim) ### update Header if cube.coordsys == 'AZEL': header.update({'CTYPE1': 'dAZ', 'CTYPE2': 'dEL'}) elif cube.coordsys == 'RADEC': header.update({'OBSRA': float(cube.xref), 'OBSDEC': float(cube.yref)}) else: pass header.update({'CRVAL1': float(cube.x[0]), 'CDELT1': float(cube.x[1] - cube.x[0]), 'CRVAL2': float(cube.y[0]), 'CDELT2': float(cube.y[1] - cube.y[0]), 'DATE': datetime.now(timezone('UTC')).isoformat()}) if (ndim == 3) and (not dropdeg): header.update({'CRVAL3': float(newcube.kidfq[0]), 'CDELT3': float(newcube.kidfq[1] - newcube.kidfq[0])}) fitsname = str(Path(fitsname).expanduser()) fits.writeto(fitsname, data, header, **kwargs) logger.info('{} has been created.'.format(fitsname))
python
def savefits(cube, fitsname, **kwargs): """Save a cube to a 3D-cube FITS file. Args: cube (xarray.DataArray): Cube to be saved. fitsname (str): Name of output FITS file. kwargs (optional): Other arguments common with astropy.io.fits.writeto(). """ ### pick up kwargs dropdeg = kwargs.pop('dropdeg', False) ndim = len(cube.dims) ### load yaml FITSINFO = get_data('decode', 'data/fitsinfo.yaml') hdrdata = yaml.load(FITSINFO, dc.utils.OrderedLoader) ### default header if ndim == 2: header = fits.Header(hdrdata['dcube_2d']) data = cube.values.T elif ndim == 3: if dropdeg: header = fits.Header(hdrdata['dcube_2d']) data = cube.values[:, :, 0].T else: header = fits.Header(hdrdata['dcube_3d']) kidfq = cube.kidfq.values freqrange = ~np.isnan(kidfq) orderedfq = np.argsort(kidfq[freqrange]) newcube = cube[:, :, orderedfq] data = newcube.values.T else: raise TypeError(ndim) ### update Header if cube.coordsys == 'AZEL': header.update({'CTYPE1': 'dAZ', 'CTYPE2': 'dEL'}) elif cube.coordsys == 'RADEC': header.update({'OBSRA': float(cube.xref), 'OBSDEC': float(cube.yref)}) else: pass header.update({'CRVAL1': float(cube.x[0]), 'CDELT1': float(cube.x[1] - cube.x[0]), 'CRVAL2': float(cube.y[0]), 'CDELT2': float(cube.y[1] - cube.y[0]), 'DATE': datetime.now(timezone('UTC')).isoformat()}) if (ndim == 3) and (not dropdeg): header.update({'CRVAL3': float(newcube.kidfq[0]), 'CDELT3': float(newcube.kidfq[1] - newcube.kidfq[0])}) fitsname = str(Path(fitsname).expanduser()) fits.writeto(fitsname, data, header, **kwargs) logger.info('{} has been created.'.format(fitsname))
[ "def", "savefits", "(", "cube", ",", "fitsname", ",", "*", "*", "kwargs", ")", ":", "### pick up kwargs", "dropdeg", "=", "kwargs", ".", "pop", "(", "'dropdeg'", ",", "False", ")", "ndim", "=", "len", "(", "cube", ".", "dims", ")", "### load yaml", "FI...
Save a cube to a 3D-cube FITS file. Args: cube (xarray.DataArray): Cube to be saved. fitsname (str): Name of output FITS file. kwargs (optional): Other arguments common with astropy.io.fits.writeto().
[ "Save", "a", "cube", "to", "a", "3D", "-", "cube", "FITS", "file", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/io/functions.py#L268-L321
deshima-dev/decode
decode/io/functions.py
loadnetcdf
def loadnetcdf(filename, copy=True): """Load a dataarray from a NetCDF file. Args: filename (str): Filename (*.nc). copy (bool): If True, dataarray is copied in memory. Default is True. Returns: dataarray (xarray.DataArray): Loaded dataarray. """ filename = str(Path(filename).expanduser()) if copy: dataarray = xr.open_dataarray(filename).copy() else: dataarray = xr.open_dataarray(filename, chunks={}) if dataarray.name is None: dataarray.name = filename.rstrip('.nc') for key, val in dataarray.coords.items(): if val.dtype.kind == 'S': dataarray[key] = val.astype('U') elif val.dtype == np.int32: dataarray[key] = val.astype('i8') return dataarray
python
def loadnetcdf(filename, copy=True): """Load a dataarray from a NetCDF file. Args: filename (str): Filename (*.nc). copy (bool): If True, dataarray is copied in memory. Default is True. Returns: dataarray (xarray.DataArray): Loaded dataarray. """ filename = str(Path(filename).expanduser()) if copy: dataarray = xr.open_dataarray(filename).copy() else: dataarray = xr.open_dataarray(filename, chunks={}) if dataarray.name is None: dataarray.name = filename.rstrip('.nc') for key, val in dataarray.coords.items(): if val.dtype.kind == 'S': dataarray[key] = val.astype('U') elif val.dtype == np.int32: dataarray[key] = val.astype('i8') return dataarray
[ "def", "loadnetcdf", "(", "filename", ",", "copy", "=", "True", ")", ":", "filename", "=", "str", "(", "Path", "(", "filename", ")", ".", "expanduser", "(", ")", ")", "if", "copy", ":", "dataarray", "=", "xr", ".", "open_dataarray", "(", "filename", ...
Load a dataarray from a NetCDF file. Args: filename (str): Filename (*.nc). copy (bool): If True, dataarray is copied in memory. Default is True. Returns: dataarray (xarray.DataArray): Loaded dataarray.
[ "Load", "a", "dataarray", "from", "a", "NetCDF", "file", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/io/functions.py#L324-L350
deshima-dev/decode
decode/io/functions.py
savenetcdf
def savenetcdf(dataarray, filename=None): """Save a dataarray to a NetCDF file. Args: dataarray (xarray.DataArray): Dataarray to be saved. filename (str): Filename (used as <filename>.nc). If not spacified, random 8-character name will be used. """ if filename is None: if dataarray.name is not None: filename = dataarray.name else: filename = uuid4().hex[:8] else: filename = str(Path(filename).expanduser()) if not filename.endswith('.nc'): filename += '.nc' dataarray.to_netcdf(filename) logger.info('{} has been created.'.format(filename))
python
def savenetcdf(dataarray, filename=None): """Save a dataarray to a NetCDF file. Args: dataarray (xarray.DataArray): Dataarray to be saved. filename (str): Filename (used as <filename>.nc). If not spacified, random 8-character name will be used. """ if filename is None: if dataarray.name is not None: filename = dataarray.name else: filename = uuid4().hex[:8] else: filename = str(Path(filename).expanduser()) if not filename.endswith('.nc'): filename += '.nc' dataarray.to_netcdf(filename) logger.info('{} has been created.'.format(filename))
[ "def", "savenetcdf", "(", "dataarray", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "if", "dataarray", ".", "name", "is", "not", "None", ":", "filename", "=", "dataarray", ".", "name", "else", ":", "filename", "=", "uuid...
Save a dataarray to a NetCDF file. Args: dataarray (xarray.DataArray): Dataarray to be saved. filename (str): Filename (used as <filename>.nc). If not spacified, random 8-character name will be used.
[ "Save", "a", "dataarray", "to", "a", "NetCDF", "file", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/io/functions.py#L353-L373
facelessuser/pyspelling
pyspelling/filters/text.py
TextFilter.validate_options
def validate_options(self, k, v): """Validate options.""" super().validate_options(k, v) if k == 'errors' and v.lower() not in ('strict', 'replace', 'ignore', 'backslashreplace'): raise ValueError("{}: '{}' is not a valid value for '{}'".format(self.__class__.__name, v, k)) if k == 'normalize' and v.upper() not in ('NFC', 'NFKC', 'NFD', 'NFKD'): raise ValueError("{}: '{}' is not a valid value for '{}'".format(self.__class__.__name, v, k))
python
def validate_options(self, k, v): """Validate options.""" super().validate_options(k, v) if k == 'errors' and v.lower() not in ('strict', 'replace', 'ignore', 'backslashreplace'): raise ValueError("{}: '{}' is not a valid value for '{}'".format(self.__class__.__name, v, k)) if k == 'normalize' and v.upper() not in ('NFC', 'NFKC', 'NFD', 'NFKD'): raise ValueError("{}: '{}' is not a valid value for '{}'".format(self.__class__.__name, v, k))
[ "def", "validate_options", "(", "self", ",", "k", ",", "v", ")", ":", "super", "(", ")", ".", "validate_options", "(", "k", ",", "v", ")", "if", "k", "==", "'errors'", "and", "v", ".", "lower", "(", ")", "not", "in", "(", "'strict'", ",", "'repla...
Validate options.
[ "Validate", "options", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/text.py#L25-L32
facelessuser/pyspelling
pyspelling/filters/text.py
TextFilter.setup
def setup(self): """Setup.""" self.normalize = self.config['normalize'].upper() self.convert_encoding = self.config['convert_encoding'].lower() self.errors = self.config['errors'].lower() if self.convert_encoding: self.convert_encoding = codecs.lookup( filters.PYTHON_ENCODING_NAMES.get(self.default_encoding, self.default_encoding).lower() ).name # Don't generate content with BOMs if ( self.convert_encoding.startswith(('utf-32', 'utf-16')) and not self.convert_encoding.endswith(('le', 'be')) ): self.convert_encoding += '-le' if self.convert_encoding == 'utf-8-sig': self.convert_encoding = 'utf-8'
python
def setup(self): """Setup.""" self.normalize = self.config['normalize'].upper() self.convert_encoding = self.config['convert_encoding'].lower() self.errors = self.config['errors'].lower() if self.convert_encoding: self.convert_encoding = codecs.lookup( filters.PYTHON_ENCODING_NAMES.get(self.default_encoding, self.default_encoding).lower() ).name # Don't generate content with BOMs if ( self.convert_encoding.startswith(('utf-32', 'utf-16')) and not self.convert_encoding.endswith(('le', 'be')) ): self.convert_encoding += '-le' if self.convert_encoding == 'utf-8-sig': self.convert_encoding = 'utf-8'
[ "def", "setup", "(", "self", ")", ":", "self", ".", "normalize", "=", "self", ".", "config", "[", "'normalize'", "]", ".", "upper", "(", ")", "self", ".", "convert_encoding", "=", "self", ".", "config", "[", "'convert_encoding'", "]", ".", "lower", "("...
Setup.
[ "Setup", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/text.py#L34-L54
facelessuser/pyspelling
pyspelling/filters/text.py
TextFilter.convert
def convert(self, text, encoding): """Convert the text.""" if self.normalize in ('NFC', 'NFKC', 'NFD', 'NFKD'): text = unicodedata.normalize(self.normalize, text) if self.convert_encoding: text = text.encode(self.convert_encoding, self.errors).decode(self.convert_encoding) encoding = self.convert_encoding return text, encoding
python
def convert(self, text, encoding): """Convert the text.""" if self.normalize in ('NFC', 'NFKC', 'NFD', 'NFKD'): text = unicodedata.normalize(self.normalize, text) if self.convert_encoding: text = text.encode(self.convert_encoding, self.errors).decode(self.convert_encoding) encoding = self.convert_encoding return text, encoding
[ "def", "convert", "(", "self", ",", "text", ",", "encoding", ")", ":", "if", "self", ".", "normalize", "in", "(", "'NFC'", ",", "'NFKC'", ",", "'NFD'", ",", "'NFKD'", ")", ":", "text", "=", "unicodedata", ".", "normalize", "(", "self", ".", "normaliz...
Convert the text.
[ "Convert", "the", "text", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/text.py#L56-L64
facelessuser/pyspelling
pyspelling/filters/text.py
TextFilter.sfilter
def sfilter(self, source): """Execute filter.""" text, encoding = self.convert(source.text, source.encoding) return [filters.SourceText(text, source.context, encoding, 'text')]
python
def sfilter(self, source): """Execute filter.""" text, encoding = self.convert(source.text, source.encoding) return [filters.SourceText(text, source.context, encoding, 'text')]
[ "def", "sfilter", "(", "self", ",", "source", ")", ":", "text", ",", "encoding", "=", "self", ".", "convert", "(", "source", ".", "text", ",", "source", ".", "encoding", ")", "return", "[", "filters", ".", "SourceText", "(", "text", ",", "source", "....
Execute filter.
[ "Execute", "filter", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/text.py#L76-L81
KeithSSmith/switcheo-python
switcheo/ethereum/signatures.py
sign_create_cancellation
def sign_create_cancellation(cancellation_params, private_key): """ Function to sign the parameters required to create a cancellation request from the Switcheo Exchange. Execution of this function is as follows:: sign_create_cancellation(cancellation_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: { 'order_id': '3125550a-04f9-4475-808b-42b5f89d6693', 'timestamp': 1542088842108, 'address': '0x32c46323b51c977814e05ef5e258ee4da0e4c3c3', 'signature': 'dac70ca711bcfbeefbdead2158ef8b15fab1a1....' } :param cancellation_params: Dictionary with Order ID and timestamp to sign for creating the cancellation. :type cancellation_params: dict :param private_key: The Ethereum private key to sign the deposit parameters. :type private_key: str :return: Dictionary of signed message to send to the Switcheo API. """ hash_message = defunct_hash_message(text=stringify_message(cancellation_params)) hex_message = binascii.hexlify(hash_message).decode() signed_message = binascii.hexlify(Account.signHash(hex_message, private_key=private_key)['signature']).decode() create_params = cancellation_params.copy() create_params['address'] = to_normalized_address(Account.privateKeyToAccount(private_key=private_key).address) create_params['signature'] = signed_message return create_params
python
def sign_create_cancellation(cancellation_params, private_key): """ Function to sign the parameters required to create a cancellation request from the Switcheo Exchange. Execution of this function is as follows:: sign_create_cancellation(cancellation_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: { 'order_id': '3125550a-04f9-4475-808b-42b5f89d6693', 'timestamp': 1542088842108, 'address': '0x32c46323b51c977814e05ef5e258ee4da0e4c3c3', 'signature': 'dac70ca711bcfbeefbdead2158ef8b15fab1a1....' } :param cancellation_params: Dictionary with Order ID and timestamp to sign for creating the cancellation. :type cancellation_params: dict :param private_key: The Ethereum private key to sign the deposit parameters. :type private_key: str :return: Dictionary of signed message to send to the Switcheo API. """ hash_message = defunct_hash_message(text=stringify_message(cancellation_params)) hex_message = binascii.hexlify(hash_message).decode() signed_message = binascii.hexlify(Account.signHash(hex_message, private_key=private_key)['signature']).decode() create_params = cancellation_params.copy() create_params['address'] = to_normalized_address(Account.privateKeyToAccount(private_key=private_key).address) create_params['signature'] = signed_message return create_params
[ "def", "sign_create_cancellation", "(", "cancellation_params", ",", "private_key", ")", ":", "hash_message", "=", "defunct_hash_message", "(", "text", "=", "stringify_message", "(", "cancellation_params", ")", ")", "hex_message", "=", "binascii", ".", "hexlify", "(", ...
Function to sign the parameters required to create a cancellation request from the Switcheo Exchange. Execution of this function is as follows:: sign_create_cancellation(cancellation_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: { 'order_id': '3125550a-04f9-4475-808b-42b5f89d6693', 'timestamp': 1542088842108, 'address': '0x32c46323b51c977814e05ef5e258ee4da0e4c3c3', 'signature': 'dac70ca711bcfbeefbdead2158ef8b15fab1a1....' } :param cancellation_params: Dictionary with Order ID and timestamp to sign for creating the cancellation. :type cancellation_params: dict :param private_key: The Ethereum private key to sign the deposit parameters. :type private_key: str :return: Dictionary of signed message to send to the Switcheo API.
[ "Function", "to", "sign", "the", "parameters", "required", "to", "create", "a", "cancellation", "request", "from", "the", "Switcheo", "Exchange", ".", "Execution", "of", "this", "function", "is", "as", "follows", "::" ]
train
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/ethereum/signatures.py#L19-L47
KeithSSmith/switcheo-python
switcheo/ethereum/signatures.py
sign_execute_cancellation
def sign_execute_cancellation(cancellation_params, private_key): """ Function to sign the parameters required to execute a cancellation request on the Switcheo Exchange. Execution of this function is as follows:: sign_execute_cancellation(cancellation_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: { 'signature': '0x65986ed2cb631d4999ce8b9c895a43f....' } :param cancellation_params: Parameters the Switcheo Exchange returns from the create cancellation. :type cancellation_params: dict :param private_key: The Ethereum private key to sign the deposit parameters. :type private_key: str :return: Dictionary of signed message to send to the Switcheo API. """ cancellation_sha256 = cancellation_params['transaction']['sha256'] signed_sha256 = binascii.hexlify( Account.signHash(cancellation_sha256, private_key=private_key)['signature']).decode() return {'signature': '0x' + signed_sha256}
python
def sign_execute_cancellation(cancellation_params, private_key): """ Function to sign the parameters required to execute a cancellation request on the Switcheo Exchange. Execution of this function is as follows:: sign_execute_cancellation(cancellation_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: { 'signature': '0x65986ed2cb631d4999ce8b9c895a43f....' } :param cancellation_params: Parameters the Switcheo Exchange returns from the create cancellation. :type cancellation_params: dict :param private_key: The Ethereum private key to sign the deposit parameters. :type private_key: str :return: Dictionary of signed message to send to the Switcheo API. """ cancellation_sha256 = cancellation_params['transaction']['sha256'] signed_sha256 = binascii.hexlify( Account.signHash(cancellation_sha256, private_key=private_key)['signature']).decode() return {'signature': '0x' + signed_sha256}
[ "def", "sign_execute_cancellation", "(", "cancellation_params", ",", "private_key", ")", ":", "cancellation_sha256", "=", "cancellation_params", "[", "'transaction'", "]", "[", "'sha256'", "]", "signed_sha256", "=", "binascii", ".", "hexlify", "(", "Account", ".", "...
Function to sign the parameters required to execute a cancellation request on the Switcheo Exchange. Execution of this function is as follows:: sign_execute_cancellation(cancellation_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: { 'signature': '0x65986ed2cb631d4999ce8b9c895a43f....' } :param cancellation_params: Parameters the Switcheo Exchange returns from the create cancellation. :type cancellation_params: dict :param private_key: The Ethereum private key to sign the deposit parameters. :type private_key: str :return: Dictionary of signed message to send to the Switcheo API.
[ "Function", "to", "sign", "the", "parameters", "required", "to", "execute", "a", "cancellation", "request", "on", "the", "Switcheo", "Exchange", ".", "Execution", "of", "this", "function", "is", "as", "follows", "::" ]
train
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/ethereum/signatures.py#L50-L72
KeithSSmith/switcheo-python
switcheo/ethereum/signatures.py
sign_execute_deposit
def sign_execute_deposit(deposit_params, private_key, infura_url): """ Function to execute the deposit request by signing the transaction generated from the create deposit function. Execution of this function is as follows:: sign_execute_deposit(deposit_params=create_deposit, private_key=eth_private_key) The expected return result for this function is as follows:: { 'transaction_hash': '0xcf3ea5d1821544e1686fbcb1f49d423b9ea9f42772ff9ecdaf615616d780fa75' } :param deposit_params: The parameters generated by the create function that now requires a signature. :type deposit_params: dict :param private_key: The Ethereum private key to sign the deposit parameters. :type private_key: str :param infura_url: The URL used to broadcast the deposit transaction to the Ethereum network. :type infura_url: str :return: Dictionary of the signed transaction to initiate the deposit of ETH via the Switcheo API. """ create_deposit_upper = deposit_params.copy() create_deposit_upper['transaction']['from'] = to_checksum_address(create_deposit_upper['transaction']['from']) create_deposit_upper['transaction']['to'] = to_checksum_address(create_deposit_upper['transaction']['to']) create_deposit_upper['transaction'].pop('sha256') signed_create_txn = Account.signTransaction(create_deposit_upper['transaction'], private_key=private_key) execute_signed_txn = binascii.hexlify(signed_create_txn['hash']).decode() # Broadcast transaction to Ethereum Network. Web3(HTTPProvider(infura_url)).eth.sendRawTransaction(signed_create_txn.rawTransaction) return {'transaction_hash': '0x' + execute_signed_txn}
python
def sign_execute_deposit(deposit_params, private_key, infura_url): """ Function to execute the deposit request by signing the transaction generated from the create deposit function. Execution of this function is as follows:: sign_execute_deposit(deposit_params=create_deposit, private_key=eth_private_key) The expected return result for this function is as follows:: { 'transaction_hash': '0xcf3ea5d1821544e1686fbcb1f49d423b9ea9f42772ff9ecdaf615616d780fa75' } :param deposit_params: The parameters generated by the create function that now requires a signature. :type deposit_params: dict :param private_key: The Ethereum private key to sign the deposit parameters. :type private_key: str :param infura_url: The URL used to broadcast the deposit transaction to the Ethereum network. :type infura_url: str :return: Dictionary of the signed transaction to initiate the deposit of ETH via the Switcheo API. """ create_deposit_upper = deposit_params.copy() create_deposit_upper['transaction']['from'] = to_checksum_address(create_deposit_upper['transaction']['from']) create_deposit_upper['transaction']['to'] = to_checksum_address(create_deposit_upper['transaction']['to']) create_deposit_upper['transaction'].pop('sha256') signed_create_txn = Account.signTransaction(create_deposit_upper['transaction'], private_key=private_key) execute_signed_txn = binascii.hexlify(signed_create_txn['hash']).decode() # Broadcast transaction to Ethereum Network. Web3(HTTPProvider(infura_url)).eth.sendRawTransaction(signed_create_txn.rawTransaction) return {'transaction_hash': '0x' + execute_signed_txn}
[ "def", "sign_execute_deposit", "(", "deposit_params", ",", "private_key", ",", "infura_url", ")", ":", "create_deposit_upper", "=", "deposit_params", ".", "copy", "(", ")", "create_deposit_upper", "[", "'transaction'", "]", "[", "'from'", "]", "=", "to_checksum_addr...
Function to execute the deposit request by signing the transaction generated from the create deposit function. Execution of this function is as follows:: sign_execute_deposit(deposit_params=create_deposit, private_key=eth_private_key) The expected return result for this function is as follows:: { 'transaction_hash': '0xcf3ea5d1821544e1686fbcb1f49d423b9ea9f42772ff9ecdaf615616d780fa75' } :param deposit_params: The parameters generated by the create function that now requires a signature. :type deposit_params: dict :param private_key: The Ethereum private key to sign the deposit parameters. :type private_key: str :param infura_url: The URL used to broadcast the deposit transaction to the Ethereum network. :type infura_url: str :return: Dictionary of the signed transaction to initiate the deposit of ETH via the Switcheo API.
[ "Function", "to", "execute", "the", "deposit", "request", "by", "signing", "the", "transaction", "generated", "from", "the", "create", "deposit", "function", ".", "Execution", "of", "this", "function", "is", "as", "follows", "::" ]
train
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/ethereum/signatures.py#L109-L140
KeithSSmith/switcheo-python
switcheo/ethereum/signatures.py
sign_execute_order
def sign_execute_order(order_params, private_key): """ Function to execute the order request by signing the transaction generated from the create order function. Execution of this function is as follows:: sign_execute_order(order_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: { 'signatures': { 'fill_groups': {}, 'fills': {}, 'makes': { '392cd607-27ed-4702-880d-eab8d67a4201': '0x5f62c585e0978454cc89aa3b86d3ea6afbd80fc521....' } } } :param order_params: The parameters generated by the create function that now require signing. :type order_params: dict :param private_key: The Ethereum private key to sign the deposit parameters. :type private_key: str :return: Dictionary of the signed transaction to place an order on the Switcheo Order Book. """ execute_params = { 'signatures': { 'fill_groups': sign_txn_array(messages=order_params['fill_groups'], private_key=private_key), 'fills': {}, 'makes': sign_txn_array(messages=order_params['makes'], private_key=private_key), } } return execute_params
python
def sign_execute_order(order_params, private_key): """ Function to execute the order request by signing the transaction generated from the create order function. Execution of this function is as follows:: sign_execute_order(order_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: { 'signatures': { 'fill_groups': {}, 'fills': {}, 'makes': { '392cd607-27ed-4702-880d-eab8d67a4201': '0x5f62c585e0978454cc89aa3b86d3ea6afbd80fc521....' } } } :param order_params: The parameters generated by the create function that now require signing. :type order_params: dict :param private_key: The Ethereum private key to sign the deposit parameters. :type private_key: str :return: Dictionary of the signed transaction to place an order on the Switcheo Order Book. """ execute_params = { 'signatures': { 'fill_groups': sign_txn_array(messages=order_params['fill_groups'], private_key=private_key), 'fills': {}, 'makes': sign_txn_array(messages=order_params['makes'], private_key=private_key), } } return execute_params
[ "def", "sign_execute_order", "(", "order_params", ",", "private_key", ")", ":", "execute_params", "=", "{", "'signatures'", ":", "{", "'fill_groups'", ":", "sign_txn_array", "(", "messages", "=", "order_params", "[", "'fill_groups'", "]", ",", "private_key", "=", ...
Function to execute the order request by signing the transaction generated from the create order function. Execution of this function is as follows:: sign_execute_order(order_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: { 'signatures': { 'fill_groups': {}, 'fills': {}, 'makes': { '392cd607-27ed-4702-880d-eab8d67a4201': '0x5f62c585e0978454cc89aa3b86d3ea6afbd80fc521....' } } } :param order_params: The parameters generated by the create function that now require signing. :type order_params: dict :param private_key: The Ethereum private key to sign the deposit parameters. :type private_key: str :return: Dictionary of the signed transaction to place an order on the Switcheo Order Book.
[ "Function", "to", "execute", "the", "order", "request", "by", "signing", "the", "transaction", "generated", "from", "the", "create", "order", "function", ".", "Execution", "of", "this", "function", "is", "as", "follows", "::" ]
train
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/ethereum/signatures.py#L181-L213
KeithSSmith/switcheo-python
switcheo/ethereum/signatures.py
sign_execute_withdrawal
def sign_execute_withdrawal(withdrawal_params, private_key): """ Function to execute the withdrawal request by signing the transaction generated from the create withdrawal function. Execution of this function is as follows:: sign_execute_withdrawal(withdrawal_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: { 'signature': '0x33656f88b364d344e5b04f6aead01cdd3ac084489c39a9efe88c9873249bf1954525b1....' } :param withdrawal_params: The parameters generated by the create function that now require signing. :type withdrawal_params: dict :param private_key: The Ethereum private key to sign the deposit parameters. :type private_key: str :return: Dictionary of the signed transaction hash and initiate the withdrawal of ETH via the Switcheo API. """ withdrawal_sha256 = withdrawal_params['transaction']['sha256'] signed_sha256 = binascii.hexlify(Account.signHash(withdrawal_sha256, private_key=private_key)['signature']).decode() return {'signature': '0x' + signed_sha256}
python
def sign_execute_withdrawal(withdrawal_params, private_key): """ Function to execute the withdrawal request by signing the transaction generated from the create withdrawal function. Execution of this function is as follows:: sign_execute_withdrawal(withdrawal_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: { 'signature': '0x33656f88b364d344e5b04f6aead01cdd3ac084489c39a9efe88c9873249bf1954525b1....' } :param withdrawal_params: The parameters generated by the create function that now require signing. :type withdrawal_params: dict :param private_key: The Ethereum private key to sign the deposit parameters. :type private_key: str :return: Dictionary of the signed transaction hash and initiate the withdrawal of ETH via the Switcheo API. """ withdrawal_sha256 = withdrawal_params['transaction']['sha256'] signed_sha256 = binascii.hexlify(Account.signHash(withdrawal_sha256, private_key=private_key)['signature']).decode() return {'signature': '0x' + signed_sha256}
[ "def", "sign_execute_withdrawal", "(", "withdrawal_params", ",", "private_key", ")", ":", "withdrawal_sha256", "=", "withdrawal_params", "[", "'transaction'", "]", "[", "'sha256'", "]", "signed_sha256", "=", "binascii", ".", "hexlify", "(", "Account", ".", "signHash...
Function to execute the withdrawal request by signing the transaction generated from the create withdrawal function. Execution of this function is as follows:: sign_execute_withdrawal(withdrawal_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: { 'signature': '0x33656f88b364d344e5b04f6aead01cdd3ac084489c39a9efe88c9873249bf1954525b1....' } :param withdrawal_params: The parameters generated by the create function that now require signing. :type withdrawal_params: dict :param private_key: The Ethereum private key to sign the deposit parameters. :type private_key: str :return: Dictionary of the signed transaction hash and initiate the withdrawal of ETH via the Switcheo API.
[ "Function", "to", "execute", "the", "withdrawal", "request", "by", "signing", "the", "transaction", "generated", "from", "the", "create", "withdrawal", "function", ".", "Execution", "of", "this", "function", "is", "as", "follows", "::" ]
train
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/ethereum/signatures.py#L250-L271
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.setup
def setup(self): """Setup.""" self.additional_context = '' self.comments = False self.attributes = [] self.parser = 'xml' self.type = None self.filepattern = 'content.xml' self.namespaces = { 'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0', 'draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0' } self.ignores = None self.captures = sv.compile(','.join(self.default_capture), self.namespaces)
python
def setup(self): """Setup.""" self.additional_context = '' self.comments = False self.attributes = [] self.parser = 'xml' self.type = None self.filepattern = 'content.xml' self.namespaces = { 'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0', 'draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0' } self.ignores = None self.captures = sv.compile(','.join(self.default_capture), self.namespaces)
[ "def", "setup", "(", "self", ")", ":", "self", ".", "additional_context", "=", "''", "self", ".", "comments", "=", "False", "self", ".", "attributes", "=", "[", "]", "self", ".", "parser", "=", "'xml'", "self", ".", "type", "=", "None", "self", ".", ...
Setup.
[ "Setup", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L41-L55
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.determine_file_type
def determine_file_type(self, z): """Determine file type.""" mimetype = z.read('mimetype').decode('utf-8').strip() self.type = MIMEMAP[mimetype]
python
def determine_file_type(self, z): """Determine file type.""" mimetype = z.read('mimetype').decode('utf-8').strip() self.type = MIMEMAP[mimetype]
[ "def", "determine_file_type", "(", "self", ",", "z", ")", ":", "mimetype", "=", "z", ".", "read", "(", "'mimetype'", ")", ".", "decode", "(", "'utf-8'", ")", ".", "strip", "(", ")", "self", ".", "type", "=", "MIMEMAP", "[", "mimetype", "]" ]
Determine file type.
[ "Determine", "file", "type", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L69-L73
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.get_zip_content
def get_zip_content(self, filename): """Get zip content.""" with zipfile.ZipFile(filename, 'r') as z: self.determine_file_type(z) for item in z.infolist(): if glob.globmatch(item.filename, self.filepattern, flags=self.FLAGS): yield z.read(item.filename), item.filename
python
def get_zip_content(self, filename): """Get zip content.""" with zipfile.ZipFile(filename, 'r') as z: self.determine_file_type(z) for item in z.infolist(): if glob.globmatch(item.filename, self.filepattern, flags=self.FLAGS): yield z.read(item.filename), item.filename
[ "def", "get_zip_content", "(", "self", ",", "filename", ")", ":", "with", "zipfile", ".", "ZipFile", "(", "filename", ",", "'r'", ")", "as", "z", ":", "self", ".", "determine_file_type", "(", "z", ")", "for", "item", "in", "z", ".", "infolist", "(", ...
Get zip content.
[ "Get", "zip", "content", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L75-L82
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.get_content
def get_content(self, zipbundle): """Get content.""" for content, filename in self.get_zip_content(zipbundle): with io.BytesIO(content) as b: encoding = self._analyze_file(b) if encoding is None: encoding = self.default_encoding b.seek(0) text = b.read().decode(encoding) yield text, filename, encoding
python
def get_content(self, zipbundle): """Get content.""" for content, filename in self.get_zip_content(zipbundle): with io.BytesIO(content) as b: encoding = self._analyze_file(b) if encoding is None: encoding = self.default_encoding b.seek(0) text = b.read().decode(encoding) yield text, filename, encoding
[ "def", "get_content", "(", "self", ",", "zipbundle", ")", ":", "for", "content", ",", "filename", "in", "self", ".", "get_zip_content", "(", "zipbundle", ")", ":", "with", "io", ".", "BytesIO", "(", "content", ")", "as", "b", ":", "encoding", "=", "sel...
Get content.
[ "Get", "content", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L84-L94
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.content_break
def content_break(self, el): """Break on specified boundaries.""" should_break = False if self.type == 'odp': if el.name == 'page' and el.namespace and el.namespace == self.namespaces['draw']: should_break = True return should_break
python
def content_break(self, el): """Break on specified boundaries.""" should_break = False if self.type == 'odp': if el.name == 'page' and el.namespace and el.namespace == self.namespaces['draw']: should_break = True return should_break
[ "def", "content_break", "(", "self", ",", "el", ")", ":", "should_break", "=", "False", "if", "self", ".", "type", "==", "'odp'", ":", "if", "el", ".", "name", "==", "'page'", "and", "el", ".", "namespace", "and", "el", ".", "namespace", "==", "self"...
Break on specified boundaries.
[ "Break", "on", "specified", "boundaries", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L96-L103
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.soft_break
def soft_break(self, el, text): """Apply soft break if needed.""" if el.name == 'p' and el.namespace and el.namespace == self.namespaces["text"]: text.append('\n')
python
def soft_break(self, el, text): """Apply soft break if needed.""" if el.name == 'p' and el.namespace and el.namespace == self.namespaces["text"]: text.append('\n')
[ "def", "soft_break", "(", "self", ",", "el", ",", "text", ")", ":", "if", "el", ".", "name", "==", "'p'", "and", "el", ".", "namespace", "and", "el", ".", "namespace", "==", "self", ".", "namespaces", "[", "\"text\"", "]", ":", "text", ".", "append...
Apply soft break if needed.
[ "Apply", "soft", "break", "if", "needed", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L105-L109
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.store_blocks
def store_blocks(self, el, blocks, text, force_root): """Store the text as desired.""" self.soft_break(el, text) if force_root or el.parent is None or self.content_break(el): content = html.unescape(''.join(text)) if content: blocks.append((content, self.additional_context + self.construct_selector(el))) text = [] return text
python
def store_blocks(self, el, blocks, text, force_root): """Store the text as desired.""" self.soft_break(el, text) if force_root or el.parent is None or self.content_break(el): content = html.unescape(''.join(text)) if content: blocks.append((content, self.additional_context + self.construct_selector(el))) text = [] return text
[ "def", "store_blocks", "(", "self", ",", "el", ",", "blocks", ",", "text", ",", "force_root", ")", ":", "self", ".", "soft_break", "(", "el", ",", "text", ")", "if", "force_root", "or", "el", ".", "parent", "is", "None", "or", "self", ".", "content_b...
Store the text as desired.
[ "Store", "the", "text", "as", "desired", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L111-L121
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.extract_tag_metadata
def extract_tag_metadata(self, el): """Extract meta data.""" if self.type == 'odp': if el.namespace and el.namespace == self.namespaces['draw'] and el.name == 'page-thumbnail': name = el.attrs.get('draw:page-number', '') self.additional_context = 'slide{}:'.format(name) super().extract_tag_metadata(el)
python
def extract_tag_metadata(self, el): """Extract meta data.""" if self.type == 'odp': if el.namespace and el.namespace == self.namespaces['draw'] and el.name == 'page-thumbnail': name = el.attrs.get('draw:page-number', '') self.additional_context = 'slide{}:'.format(name) super().extract_tag_metadata(el)
[ "def", "extract_tag_metadata", "(", "self", ",", "el", ")", ":", "if", "self", ".", "type", "==", "'odp'", ":", "if", "el", ".", "namespace", "and", "el", ".", "namespace", "==", "self", ".", "namespaces", "[", "'draw'", "]", "and", "el", ".", "name"...
Extract meta data.
[ "Extract", "meta", "data", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L123-L130
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.get_sub_node
def get_sub_node(self, node): """Extract node from document if desired.""" subnode = node.find('office:document') if subnode: mimetype = subnode.attrs['office:mimetype'] self.type = MIMEMAP[mimetype] node = node.find('office:body') return node
python
def get_sub_node(self, node): """Extract node from document if desired.""" subnode = node.find('office:document') if subnode: mimetype = subnode.attrs['office:mimetype'] self.type = MIMEMAP[mimetype] node = node.find('office:body') return node
[ "def", "get_sub_node", "(", "self", ",", "node", ")", ":", "subnode", "=", "node", ".", "find", "(", "'office:document'", ")", "if", "subnode", ":", "mimetype", "=", "subnode", ".", "attrs", "[", "'office:mimetype'", "]", "self", ".", "type", "=", "MIMEM...
Extract node from document if desired.
[ "Extract", "node", "from", "document", "if", "desired", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L139-L147
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.filter
def filter(self, source_file, encoding): # noqa A001 """Parse XML file.""" sources = [] if encoding: with codecs.open(source_file, 'r', encoding=encoding) as f: src = f.read() sources.extend(self._filter(src, source_file, encoding)) else: for content, filename, enc in self.get_content(source_file): sources.extend(self._filter(content, source_file, enc)) return sources
python
def filter(self, source_file, encoding): # noqa A001 """Parse XML file.""" sources = [] if encoding: with codecs.open(source_file, 'r', encoding=encoding) as f: src = f.read() sources.extend(self._filter(src, source_file, encoding)) else: for content, filename, enc in self.get_content(source_file): sources.extend(self._filter(content, source_file, enc)) return sources
[ "def", "filter", "(", "self", ",", "source_file", ",", "encoding", ")", ":", "# noqa A001", "sources", "=", "[", "]", "if", "encoding", ":", "with", "codecs", ".", "open", "(", "source_file", ",", "'r'", ",", "encoding", "=", "encoding", ")", "as", "f"...
Parse XML file.
[ "Parse", "XML", "file", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L166-L177
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.sfilter
def sfilter(self, source): """Filter.""" sources = [] if source.text[:4].encode(source.encoding) != b'PK\x03\x04': sources.extend(self._filter(source.text, source.context, source.encoding)) else: for content, filename, enc in self.get_content(io.BytesIO(source.text.encode(source.encoding))): sources.extend(self._filter(content, source.context, enc)) return sources
python
def sfilter(self, source): """Filter.""" sources = [] if source.text[:4].encode(source.encoding) != b'PK\x03\x04': sources.extend(self._filter(source.text, source.context, source.encoding)) else: for content, filename, enc in self.get_content(io.BytesIO(source.text.encode(source.encoding))): sources.extend(self._filter(content, source.context, enc)) return sources
[ "def", "sfilter", "(", "self", ",", "source", ")", ":", "sources", "=", "[", "]", "if", "source", ".", "text", "[", ":", "4", "]", ".", "encode", "(", "source", ".", "encoding", ")", "!=", "b'PK\\x03\\x04'", ":", "sources", ".", "extend", "(", "sel...
Filter.
[ "Filter", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L179-L188
deshima-dev/decode
decode/core/array/functions.py
array
def array(data, tcoords=None, chcoords=None, scalarcoords=None, datacoords=None, attrs=None, name=None): """Create an array as an instance of xarray.DataArray with Decode accessor. Args: data (numpy.ndarray): 2D (time x channel) array. tcoords (dict, optional): Dictionary of arrays that label time axis. chcoords (dict, optional): Dictionary of arrays that label channel axis. scalarcoords (dict, optional): Dictionary of values that don't label any axes (point-like). datacoords (dict, optional): Dictionary of arrays that label time and channel axes. attrs (dict, optional): Dictionary of attributes to add to the instance. name (str, optional): String that names the instance. Returns: array (decode.array): Deode array. """ # initialize coords with default values array = xr.DataArray(data, dims=('t', 'ch'), attrs=attrs, name=name) array.dca._initcoords() # update coords with input values (if any) if tcoords is not None: array.coords.update({key: ('t', tcoords[key]) for key in tcoords}) if chcoords is not None: array.coords.update({key: ('ch', chcoords[key]) for key in chcoords}) if scalarcoords is not None: array.coords.update(scalarcoords) if datacoords is not None: array.coords.update({key: (('t', 'ch'), datacoords[key]) for key in datacoords}) return array
python
def array(data, tcoords=None, chcoords=None, scalarcoords=None, datacoords=None, attrs=None, name=None): """Create an array as an instance of xarray.DataArray with Decode accessor. Args: data (numpy.ndarray): 2D (time x channel) array. tcoords (dict, optional): Dictionary of arrays that label time axis. chcoords (dict, optional): Dictionary of arrays that label channel axis. scalarcoords (dict, optional): Dictionary of values that don't label any axes (point-like). datacoords (dict, optional): Dictionary of arrays that label time and channel axes. attrs (dict, optional): Dictionary of attributes to add to the instance. name (str, optional): String that names the instance. Returns: array (decode.array): Deode array. """ # initialize coords with default values array = xr.DataArray(data, dims=('t', 'ch'), attrs=attrs, name=name) array.dca._initcoords() # update coords with input values (if any) if tcoords is not None: array.coords.update({key: ('t', tcoords[key]) for key in tcoords}) if chcoords is not None: array.coords.update({key: ('ch', chcoords[key]) for key in chcoords}) if scalarcoords is not None: array.coords.update(scalarcoords) if datacoords is not None: array.coords.update({key: (('t', 'ch'), datacoords[key]) for key in datacoords}) return array
[ "def", "array", "(", "data", ",", "tcoords", "=", "None", ",", "chcoords", "=", "None", ",", "scalarcoords", "=", "None", ",", "datacoords", "=", "None", ",", "attrs", "=", "None", ",", "name", "=", "None", ")", ":", "# initialize coords with default value...
Create an array as an instance of xarray.DataArray with Decode accessor. Args: data (numpy.ndarray): 2D (time x channel) array. tcoords (dict, optional): Dictionary of arrays that label time axis. chcoords (dict, optional): Dictionary of arrays that label channel axis. scalarcoords (dict, optional): Dictionary of values that don't label any axes (point-like). datacoords (dict, optional): Dictionary of arrays that label time and channel axes. attrs (dict, optional): Dictionary of attributes to add to the instance. name (str, optional): String that names the instance. Returns: array (decode.array): Deode array.
[ "Create", "an", "array", "as", "an", "instance", "of", "xarray", ".", "DataArray", "with", "Decode", "accessor", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L29-L61
deshima-dev/decode
decode/core/array/functions.py
zeros
def zeros(shape, dtype=None, **kwargs): """Create an array of given shape and type, filled with zeros. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with zeros. """ data = np.zeros(shape, dtype) return dc.array(data, **kwargs)
python
def zeros(shape, dtype=None, **kwargs): """Create an array of given shape and type, filled with zeros. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with zeros. """ data = np.zeros(shape, dtype) return dc.array(data, **kwargs)
[ "def", "zeros", "(", "shape", ",", "dtype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "data", "=", "np", ".", "zeros", "(", "shape", ",", "dtype", ")", "return", "dc", ".", "array", "(", "data", ",", "*", "*", "kwargs", ")" ]
Create an array of given shape and type, filled with zeros. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with zeros.
[ "Create", "an", "array", "of", "given", "shape", "and", "type", "filled", "with", "zeros", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L64-L76
deshima-dev/decode
decode/core/array/functions.py
ones
def ones(shape, dtype=None, **kwargs): """Create an array of given shape and type, filled with ones. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with ones. """ data = np.ones(shape, dtype) return dc.array(data, **kwargs)
python
def ones(shape, dtype=None, **kwargs): """Create an array of given shape and type, filled with ones. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with ones. """ data = np.ones(shape, dtype) return dc.array(data, **kwargs)
[ "def", "ones", "(", "shape", ",", "dtype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "data", "=", "np", ".", "ones", "(", "shape", ",", "dtype", ")", "return", "dc", ".", "array", "(", "data", ",", "*", "*", "kwargs", ")" ]
Create an array of given shape and type, filled with ones. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with ones.
[ "Create", "an", "array", "of", "given", "shape", "and", "type", "filled", "with", "ones", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L79-L91
deshima-dev/decode
decode/core/array/functions.py
full
def full(shape, fill_value, dtype=None, **kwargs): """Create an array of given shape and type, filled with `fill_value`. Args: shape (sequence of ints): 2D shape of the array. fill_value (scalar or numpy.ndarray): Fill value or array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with `fill_value`. """ return (dc.zeros(shape, **kwargs) + fill_value).astype(dtype)
python
def full(shape, fill_value, dtype=None, **kwargs): """Create an array of given shape and type, filled with `fill_value`. Args: shape (sequence of ints): 2D shape of the array. fill_value (scalar or numpy.ndarray): Fill value or array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with `fill_value`. """ return (dc.zeros(shape, **kwargs) + fill_value).astype(dtype)
[ "def", "full", "(", "shape", ",", "fill_value", ",", "dtype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "(", "dc", ".", "zeros", "(", "shape", ",", "*", "*", "kwargs", ")", "+", "fill_value", ")", ".", "astype", "(", "dtype", ")" ...
Create an array of given shape and type, filled with `fill_value`. Args: shape (sequence of ints): 2D shape of the array. fill_value (scalar or numpy.ndarray): Fill value or array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with `fill_value`.
[ "Create", "an", "array", "of", "given", "shape", "and", "type", "filled", "with", "fill_value", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L94-L106
deshima-dev/decode
decode/core/array/functions.py
empty
def empty(shape, dtype=None, **kwargs): """Create an array of given shape and type, without initializing entries. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array without initializing entries. """ data = np.empty(shape, dtype) return dc.array(data, **kwargs)
python
def empty(shape, dtype=None, **kwargs): """Create an array of given shape and type, without initializing entries. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array without initializing entries. """ data = np.empty(shape, dtype) return dc.array(data, **kwargs)
[ "def", "empty", "(", "shape", ",", "dtype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "data", "=", "np", ".", "empty", "(", "shape", ",", "dtype", ")", "return", "dc", ".", "array", "(", "data", ",", "*", "*", "kwargs", ")" ]
Create an array of given shape and type, without initializing entries. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array without initializing entries.
[ "Create", "an", "array", "of", "given", "shape", "and", "type", "without", "initializing", "entries", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L109-L121
deshima-dev/decode
decode/core/array/functions.py
zeros_like
def zeros_like(array, dtype=None, keepmeta=True): """Create an array of zeros with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If specified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with zeros. """ if keepmeta: return xr.zeros_like(array, dtype) else: return dc.zeros(array.shape, dtype)
python
def zeros_like(array, dtype=None, keepmeta=True): """Create an array of zeros with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If specified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with zeros. """ if keepmeta: return xr.zeros_like(array, dtype) else: return dc.zeros(array.shape, dtype)
[ "def", "zeros_like", "(", "array", ",", "dtype", "=", "None", ",", "keepmeta", "=", "True", ")", ":", "if", "keepmeta", ":", "return", "xr", ".", "zeros_like", "(", "array", ",", "dtype", ")", "else", ":", "return", "dc", ".", "zeros", "(", "array", ...
Create an array of zeros with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If specified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with zeros.
[ "Create", "an", "array", "of", "zeros", "with", "the", "same", "shape", "and", "type", "as", "the", "input", "array", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L124-L141
deshima-dev/decode
decode/core/array/functions.py
ones_like
def ones_like(array, dtype=None, keepmeta=True): """Create an array of ones with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with ones. """ if keepmeta: return xr.ones_like(array, dtype) else: return dc.ones(array.shape, dtype)
python
def ones_like(array, dtype=None, keepmeta=True): """Create an array of ones with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with ones. """ if keepmeta: return xr.ones_like(array, dtype) else: return dc.ones(array.shape, dtype)
[ "def", "ones_like", "(", "array", ",", "dtype", "=", "None", ",", "keepmeta", "=", "True", ")", ":", "if", "keepmeta", ":", "return", "xr", ".", "ones_like", "(", "array", ",", "dtype", ")", "else", ":", "return", "dc", ".", "ones", "(", "array", "...
Create an array of ones with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with ones.
[ "Create", "an", "array", "of", "ones", "with", "the", "same", "shape", "and", "type", "as", "the", "input", "array", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L144-L161
deshima-dev/decode
decode/core/array/functions.py
full_like
def full_like(array, fill_value, reverse=False, dtype=None, keepmeta=True): """Create an array of `fill_value` with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. fill_value (scalar or numpy.ndarray): Fill value or array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with `fill_value`. """ if keepmeta: return (dc.zeros_like(array) + fill_value).astype(dtype) else: return dc.full(array.shape, fill_value, dtype)
python
def full_like(array, fill_value, reverse=False, dtype=None, keepmeta=True): """Create an array of `fill_value` with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. fill_value (scalar or numpy.ndarray): Fill value or array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with `fill_value`. """ if keepmeta: return (dc.zeros_like(array) + fill_value).astype(dtype) else: return dc.full(array.shape, fill_value, dtype)
[ "def", "full_like", "(", "array", ",", "fill_value", ",", "reverse", "=", "False", ",", "dtype", "=", "None", ",", "keepmeta", "=", "True", ")", ":", "if", "keepmeta", ":", "return", "(", "dc", ".", "zeros_like", "(", "array", ")", "+", "fill_value", ...
Create an array of `fill_value` with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. fill_value (scalar or numpy.ndarray): Fill value or array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with `fill_value`.
[ "Create", "an", "array", "of", "fill_value", "with", "the", "same", "shape", "and", "type", "as", "the", "input", "array", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L164-L182
deshima-dev/decode
decode/core/array/functions.py
empty_like
def empty_like(array, dtype=None, keepmeta=True): """Create an array of empty with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array without initializing entries. """ if keepmeta: return dc.empty(array.shape, dtype, tcoords=array.dca.tcoords, chcoords=array.dca.chcoords, scalarcoords=array.dca.scalarcoords, attrs=array.attrs, name=array.name ) else: return dc.empty(array.shape, dtype)
python
def empty_like(array, dtype=None, keepmeta=True): """Create an array of empty with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array without initializing entries. """ if keepmeta: return dc.empty(array.shape, dtype, tcoords=array.dca.tcoords, chcoords=array.dca.chcoords, scalarcoords=array.dca.scalarcoords, attrs=array.attrs, name=array.name ) else: return dc.empty(array.shape, dtype)
[ "def", "empty_like", "(", "array", ",", "dtype", "=", "None", ",", "keepmeta", "=", "True", ")", ":", "if", "keepmeta", ":", "return", "dc", ".", "empty", "(", "array", ".", "shape", ",", "dtype", ",", "tcoords", "=", "array", ".", "dca", ".", "tco...
Create an array of empty with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array without initializing entries.
[ "Create", "an", "array", "of", "empty", "with", "the", "same", "shape", "and", "type", "as", "the", "input", "array", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L185-L205
facelessuser/pyspelling
pyspelling/__init__.py
iter_tasks
def iter_tasks(matrix, names, groups): """Iterate tasks.""" # Build name index name_index = dict([(task.get('name', ''), index) for index, task in enumerate(matrix)]) for index, task in enumerate(matrix): name = task.get('name', '') group = task.get('group', '') hidden = task.get('hidden', False) if names and name in names and index == name_index[name]: yield task elif groups and group in groups and not hidden: yield task elif not names and not groups and not hidden: yield task
python
def iter_tasks(matrix, names, groups): """Iterate tasks.""" # Build name index name_index = dict([(task.get('name', ''), index) for index, task in enumerate(matrix)]) for index, task in enumerate(matrix): name = task.get('name', '') group = task.get('group', '') hidden = task.get('hidden', False) if names and name in names and index == name_index[name]: yield task elif groups and group in groups and not hidden: yield task elif not names and not groups and not hidden: yield task
[ "def", "iter_tasks", "(", "matrix", ",", "names", ",", "groups", ")", ":", "# Build name index", "name_index", "=", "dict", "(", "[", "(", "task", ".", "get", "(", "'name'", ",", "''", ")", ",", "index", ")", "for", "index", ",", "task", "in", "enume...
Iterate tasks.
[ "Iterate", "tasks", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L570-L585
facelessuser/pyspelling
pyspelling/__init__.py
spellcheck
def spellcheck(config_file, names=None, groups=None, binary='', checker='', sources=None, verbose=0, debug=False): """Spell check.""" hunspell = None aspell = None spellchecker = None config = util.read_config(config_file) if sources is None: sources = [] matrix = config.get('matrix', []) preferred_checker = config.get('spellchecker', 'aspell') if not matrix: matrix = config.get('documents', []) if matrix: util.warn_deprecated("'documents' key in config is deprecated. 'matrix' should be used going forward.") groups = set() if groups is None else set(groups) names = set() if names is None else set(names) # Sources are only recognized when requesting a single name. if (len(names) != 1 and len(sources)): sources = [] for task in iter_tasks(matrix, names, groups): if not checker: checker = preferred_checker if checker == "hunspell": # pragma: no cover if hunspell is None: hunspell = Hunspell(config, binary, verbose, debug) spellchecker = hunspell elif checker == "aspell": if aspell is None: aspell = Aspell(config, binary, verbose, debug) spellchecker = aspell else: raise ValueError('%s is not a valid spellchecker!' % checker) spellchecker.log('Using %s to spellcheck %s' % (checker, task.get('name', '')), 1) for result in spellchecker.run_task(task, source_patterns=sources): spellchecker.log('Context: %s' % result.context, 2) yield result spellchecker.log("", 1)
python
def spellcheck(config_file, names=None, groups=None, binary='', checker='', sources=None, verbose=0, debug=False): """Spell check.""" hunspell = None aspell = None spellchecker = None config = util.read_config(config_file) if sources is None: sources = [] matrix = config.get('matrix', []) preferred_checker = config.get('spellchecker', 'aspell') if not matrix: matrix = config.get('documents', []) if matrix: util.warn_deprecated("'documents' key in config is deprecated. 'matrix' should be used going forward.") groups = set() if groups is None else set(groups) names = set() if names is None else set(names) # Sources are only recognized when requesting a single name. if (len(names) != 1 and len(sources)): sources = [] for task in iter_tasks(matrix, names, groups): if not checker: checker = preferred_checker if checker == "hunspell": # pragma: no cover if hunspell is None: hunspell = Hunspell(config, binary, verbose, debug) spellchecker = hunspell elif checker == "aspell": if aspell is None: aspell = Aspell(config, binary, verbose, debug) spellchecker = aspell else: raise ValueError('%s is not a valid spellchecker!' % checker) spellchecker.log('Using %s to spellcheck %s' % (checker, task.get('name', '')), 1) for result in spellchecker.run_task(task, source_patterns=sources): spellchecker.log('Context: %s' % result.context, 2) yield result spellchecker.log("", 1)
[ "def", "spellcheck", "(", "config_file", ",", "names", "=", "None", ",", "groups", "=", "None", ",", "binary", "=", "''", ",", "checker", "=", "''", ",", "sources", "=", "None", ",", "verbose", "=", "0", ",", "debug", "=", "False", ")", ":", "hunsp...
Spell check.
[ "Spell", "check", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L588-L633
facelessuser/pyspelling
pyspelling/__init__.py
SpellChecker.get_error
def get_error(self, e): """Get the error.""" import traceback return traceback.format_exc() if self.debug else str(e)
python
def get_error(self, e): """Get the error.""" import traceback return traceback.format_exc() if self.debug else str(e)
[ "def", "get_error", "(", "self", ",", "e", ")", ":", "import", "traceback", "return", "traceback", ".", "format_exc", "(", ")", "if", "self", ".", "debug", "else", "str", "(", "e", ")" ]
Get the error.
[ "Get", "the", "error", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L68-L73
facelessuser/pyspelling
pyspelling/__init__.py
SpellChecker._pipeline_step
def _pipeline_step(self, sources, options, personal_dict, filter_index=1, flow_status=flow_control.ALLOW): """Recursively run text objects through the pipeline steps.""" for source in sources: if source._has_error(): yield source elif not source._is_bytes() and filter_index < len(self.pipeline_steps): f = self.pipeline_steps[filter_index] if isinstance(f, flow_control.FlowControl): err = '' try: status = f._run(source.category) except Exception as e: err = self.get_error(e) yield filters.SourceText('', source.context, '', '', err) if not err: if filter_index < len(self.pipeline_steps): yield from self._pipeline_step( [source], options, personal_dict, filter_index + 1, status ) else: if flow_status == flow_control.ALLOW: err = '' try: srcs = f._run(source) except Exception as e: err = self.get_error(e) yield filters.SourceText('', source.context, '', '', err) if not err: yield from self._pipeline_step( srcs, options, personal_dict, filter_index + 1 ) elif flow_status == flow_control.SKIP: yield from self._pipeline_step( [source], options, personal_dict, filter_index + 1 ) else: # Halted tasks yield source else: # Binary content yield source
python
def _pipeline_step(self, sources, options, personal_dict, filter_index=1, flow_status=flow_control.ALLOW): """Recursively run text objects through the pipeline steps.""" for source in sources: if source._has_error(): yield source elif not source._is_bytes() and filter_index < len(self.pipeline_steps): f = self.pipeline_steps[filter_index] if isinstance(f, flow_control.FlowControl): err = '' try: status = f._run(source.category) except Exception as e: err = self.get_error(e) yield filters.SourceText('', source.context, '', '', err) if not err: if filter_index < len(self.pipeline_steps): yield from self._pipeline_step( [source], options, personal_dict, filter_index + 1, status ) else: if flow_status == flow_control.ALLOW: err = '' try: srcs = f._run(source) except Exception as e: err = self.get_error(e) yield filters.SourceText('', source.context, '', '', err) if not err: yield from self._pipeline_step( srcs, options, personal_dict, filter_index + 1 ) elif flow_status == flow_control.SKIP: yield from self._pipeline_step( [source], options, personal_dict, filter_index + 1 ) else: # Halted tasks yield source else: # Binary content yield source
[ "def", "_pipeline_step", "(", "self", ",", "sources", ",", "options", ",", "personal_dict", ",", "filter_index", "=", "1", ",", "flow_status", "=", "flow_control", ".", "ALLOW", ")", ":", "for", "source", "in", "sources", ":", "if", "source", ".", "_has_er...
Recursively run text objects through the pipeline steps.
[ "Recursively", "run", "text", "objects", "through", "the", "pipeline", "steps", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L80-L121
facelessuser/pyspelling
pyspelling/__init__.py
SpellChecker._spelling_pipeline
def _spelling_pipeline(self, sources, options, personal_dict): """Check spelling pipeline.""" for source in self._pipeline_step(sources, options, personal_dict): # Don't waste time on empty strings if source._has_error(): yield Results([], source.context, source.category, source.error) elif not source.text or source.text.isspace(): continue else: encoding = source.encoding if source._is_bytes(): text = source.text else: # UTF-16 and UTF-32 don't work well with Aspell and Hunspell, # so encode with the compatible UTF-8 instead. if encoding.startswith(('utf-16', 'utf-32')): encoding = 'utf-8' text = source.text.encode(encoding) self.log('', 3) self.log(text, 3) cmd = self.setup_command(encoding, options, personal_dict) self.log("Command: " + str(cmd), 4) try: wordlist = util.call_spellchecker(cmd, input_text=text, encoding=encoding) yield Results( [w for w in sorted(set(wordlist.replace('\r', '').split('\n'))) if w], source.context, source.category ) except Exception as e: # pragma: no cover err = self.get_error(e) yield Results([], source.context, source.category, err)
python
def _spelling_pipeline(self, sources, options, personal_dict): """Check spelling pipeline.""" for source in self._pipeline_step(sources, options, personal_dict): # Don't waste time on empty strings if source._has_error(): yield Results([], source.context, source.category, source.error) elif not source.text or source.text.isspace(): continue else: encoding = source.encoding if source._is_bytes(): text = source.text else: # UTF-16 and UTF-32 don't work well with Aspell and Hunspell, # so encode with the compatible UTF-8 instead. if encoding.startswith(('utf-16', 'utf-32')): encoding = 'utf-8' text = source.text.encode(encoding) self.log('', 3) self.log(text, 3) cmd = self.setup_command(encoding, options, personal_dict) self.log("Command: " + str(cmd), 4) try: wordlist = util.call_spellchecker(cmd, input_text=text, encoding=encoding) yield Results( [w for w in sorted(set(wordlist.replace('\r', '').split('\n'))) if w], source.context, source.category ) except Exception as e: # pragma: no cover err = self.get_error(e) yield Results([], source.context, source.category, err)
[ "def", "_spelling_pipeline", "(", "self", ",", "sources", ",", "options", ",", "personal_dict", ")", ":", "for", "source", "in", "self", ".", "_pipeline_step", "(", "sources", ",", "options", ",", "personal_dict", ")", ":", "# Don't waste time on empty strings", ...
Check spelling pipeline.
[ "Check", "spelling", "pipeline", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L123-L156
facelessuser/pyspelling
pyspelling/__init__.py
SpellChecker._walk_src
def _walk_src(self, targets, flags, pipeline): """Walk source and parse files.""" for target in targets: for f in glob.iglob(target, flags=flags | glob.S): if not os.path.isdir(f): self.log('', 2) self.log('> Processing: %s' % f, 1) if pipeline: try: yield pipeline[0]._run_first(f) except Exception as e: err = self.get_error(e) yield [filters.SourceText('', f, '', '', err)] else: try: if self.default_encoding: encoding = filters.PYTHON_ENCODING_NAMES.get( self.default_encoding, self.default_encoding ).lower() encoding = codecs.lookup(encoding).name else: encoding = self.default_encoding yield [filters.SourceText('', f, encoding, 'file')] except Exception as e: err = self.get_error(e) yield [filters.SourceText('', f, '', '', err)]
python
def _walk_src(self, targets, flags, pipeline): """Walk source and parse files.""" for target in targets: for f in glob.iglob(target, flags=flags | glob.S): if not os.path.isdir(f): self.log('', 2) self.log('> Processing: %s' % f, 1) if pipeline: try: yield pipeline[0]._run_first(f) except Exception as e: err = self.get_error(e) yield [filters.SourceText('', f, '', '', err)] else: try: if self.default_encoding: encoding = filters.PYTHON_ENCODING_NAMES.get( self.default_encoding, self.default_encoding ).lower() encoding = codecs.lookup(encoding).name else: encoding = self.default_encoding yield [filters.SourceText('', f, encoding, 'file')] except Exception as e: err = self.get_error(e) yield [filters.SourceText('', f, '', '', err)]
[ "def", "_walk_src", "(", "self", ",", "targets", ",", "flags", ",", "pipeline", ")", ":", "for", "target", "in", "targets", ":", "for", "f", "in", "glob", ".", "iglob", "(", "target", ",", "flags", "=", "flags", "|", "glob", ".", "S", ")", ":", "...
Walk source and parse files.
[ "Walk", "source", "and", "parse", "files", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L164-L190
facelessuser/pyspelling
pyspelling/__init__.py
SpellChecker._build_pipeline
def _build_pipeline(self, task): """Build up the pipeline.""" self.pipeline_steps = [] kwargs = {} if self.default_encoding: kwargs["default_encoding"] = self.default_encoding steps = task.get('pipeline', []) if steps is None: self.pipeline_steps = None else: if not steps: steps = task.get('filters', []) if steps: util.warn_deprecated( "'filters' key in config is deprecated. 'pipeline' should be used going forward." ) if not steps: steps.append('pyspelling.filters.text') for step in steps: # Retrieve module and module options if isinstance(step, dict): name, options = list(step.items())[0] else: name = step options = {} if options is None: options = {} module = self._get_module(name) if issubclass(module, filters.Filter): self.pipeline_steps.append(module(options, **kwargs)) elif issubclass(module, flow_control.FlowControl): if self.pipeline_steps: self.pipeline_steps.append(module(options)) else: raise ValueError("Pipeline cannot start with a 'Flow Control' plugin!") else: raise ValueError("'%s' is not a valid plugin!" % name)
python
def _build_pipeline(self, task): """Build up the pipeline.""" self.pipeline_steps = [] kwargs = {} if self.default_encoding: kwargs["default_encoding"] = self.default_encoding steps = task.get('pipeline', []) if steps is None: self.pipeline_steps = None else: if not steps: steps = task.get('filters', []) if steps: util.warn_deprecated( "'filters' key in config is deprecated. 'pipeline' should be used going forward." ) if not steps: steps.append('pyspelling.filters.text') for step in steps: # Retrieve module and module options if isinstance(step, dict): name, options = list(step.items())[0] else: name = step options = {} if options is None: options = {} module = self._get_module(name) if issubclass(module, filters.Filter): self.pipeline_steps.append(module(options, **kwargs)) elif issubclass(module, flow_control.FlowControl): if self.pipeline_steps: self.pipeline_steps.append(module(options)) else: raise ValueError("Pipeline cannot start with a 'Flow Control' plugin!") else: raise ValueError("'%s' is not a valid plugin!" % name)
[ "def", "_build_pipeline", "(", "self", ",", "task", ")", ":", "self", ".", "pipeline_steps", "=", "[", "]", "kwargs", "=", "{", "}", "if", "self", ".", "default_encoding", ":", "kwargs", "[", "\"default_encoding\"", "]", "=", "self", ".", "default_encoding...
Build up the pipeline.
[ "Build", "up", "the", "pipeline", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L202-L243
facelessuser/pyspelling
pyspelling/__init__.py
SpellChecker._get_module
def _get_module(self, module): """Get module.""" if isinstance(module, str): mod = importlib.import_module(module) for name in ('get_plugin', 'get_filter'): attr = getattr(mod, name, None) if attr is not None: break if name == 'get_filter': util.warn_deprecated("'get_filter' is deprecated. Plugins should use 'get_plugin'.") if not attr: raise ValueError("Could not find the 'get_plugin' function in module '%s'!" % module) return attr()
python
def _get_module(self, module): """Get module.""" if isinstance(module, str): mod = importlib.import_module(module) for name in ('get_plugin', 'get_filter'): attr = getattr(mod, name, None) if attr is not None: break if name == 'get_filter': util.warn_deprecated("'get_filter' is deprecated. Plugins should use 'get_plugin'.") if not attr: raise ValueError("Could not find the 'get_plugin' function in module '%s'!" % module) return attr()
[ "def", "_get_module", "(", "self", ",", "module", ")", ":", "if", "isinstance", "(", "module", ",", "str", ")", ":", "mod", "=", "importlib", ".", "import_module", "(", "module", ")", "for", "name", "in", "(", "'get_plugin'", ",", "'get_filter'", ")", ...
Get module.
[ "Get", "module", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L245-L258
facelessuser/pyspelling
pyspelling/__init__.py
SpellChecker._to_flags
def _to_flags(self, text): """Convert text representation of flags to actual flags.""" flags = 0 for x in text.split('|'): value = x.strip().upper() if value: flags |= self.GLOB_FLAG_MAP.get(value, 0) return flags
python
def _to_flags(self, text): """Convert text representation of flags to actual flags.""" flags = 0 for x in text.split('|'): value = x.strip().upper() if value: flags |= self.GLOB_FLAG_MAP.get(value, 0) return flags
[ "def", "_to_flags", "(", "self", ",", "text", ")", ":", "flags", "=", "0", "for", "x", "in", "text", ".", "split", "(", "'|'", ")", ":", "value", "=", "x", ".", "strip", "(", ")", ".", "upper", "(", ")", "if", "value", ":", "flags", "|=", "se...
Convert text representation of flags to actual flags.
[ "Convert", "text", "representation", "of", "flags", "to", "actual", "flags", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L260-L268
facelessuser/pyspelling
pyspelling/__init__.py
SpellChecker.run_task
def run_task(self, task, source_patterns=None): """Walk source and initiate spell check.""" # Perform spell check self.log('Running Task: %s...' % task.get('name', ''), 1) # Setup filters and variables for the spell check self.default_encoding = task.get('default_encoding', '') options = self.setup_spellchecker(task) personal_dict = self.setup_dictionary(task) glob_flags = self._to_flags(task.get('glob_flags', "N|B|G")) self._build_pipeline(task) if not source_patterns: source_patterns = task.get('sources', []) for sources in self._walk_src(source_patterns, glob_flags, self.pipeline_steps): if self.pipeline_steps is not None: yield from self._spelling_pipeline(sources, options, personal_dict) else: yield from self.spell_check_no_pipeline(sources, options, personal_dict)
python
def run_task(self, task, source_patterns=None): """Walk source and initiate spell check.""" # Perform spell check self.log('Running Task: %s...' % task.get('name', ''), 1) # Setup filters and variables for the spell check self.default_encoding = task.get('default_encoding', '') options = self.setup_spellchecker(task) personal_dict = self.setup_dictionary(task) glob_flags = self._to_flags(task.get('glob_flags', "N|B|G")) self._build_pipeline(task) if not source_patterns: source_patterns = task.get('sources', []) for sources in self._walk_src(source_patterns, glob_flags, self.pipeline_steps): if self.pipeline_steps is not None: yield from self._spelling_pipeline(sources, options, personal_dict) else: yield from self.spell_check_no_pipeline(sources, options, personal_dict)
[ "def", "run_task", "(", "self", ",", "task", ",", "source_patterns", "=", "None", ")", ":", "# Perform spell check", "self", ".", "log", "(", "'Running Task: %s...'", "%", "task", ".", "get", "(", "'name'", ",", "''", ")", ",", "1", ")", "# Setup filters a...
Walk source and initiate spell check.
[ "Walk", "source", "and", "initiate", "spell", "check", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L270-L291
facelessuser/pyspelling
pyspelling/__init__.py
Aspell.compile_dictionary
def compile_dictionary(self, lang, wordlists, encoding, output): """Compile user dictionary.""" cmd = [ self.binary, '--lang', lang, '--encoding', codecs.lookup(filters.PYTHON_ENCODING_NAMES.get(encoding, encoding).lower()).name, 'create', 'master', output ] wordlist = '' try: output_location = os.path.dirname(output) if not os.path.exists(output_location): os.makedirs(output_location) if os.path.exists(output): os.remove(output) self.log("Compiling Dictionary...", 1) # Read word lists and create a unique set of words words = set() for wordlist in wordlists: with open(wordlist, 'rb') as src: for word in src.read().split(b'\n'): words.add(word.replace(b'\r', b'')) # Compile wordlist against language util.call( [ self.binary, '--lang', lang, '--encoding=utf-8', 'create', 'master', output ], input_text=b'\n'.join(sorted(words)) + b'\n' ) except Exception: self.log(cmd, 0) self.log("Current wordlist: '%s'" % wordlist, 0) self.log("Problem compiling dictionary. Check the binary path and options.", 0) raise
python
def compile_dictionary(self, lang, wordlists, encoding, output): """Compile user dictionary.""" cmd = [ self.binary, '--lang', lang, '--encoding', codecs.lookup(filters.PYTHON_ENCODING_NAMES.get(encoding, encoding).lower()).name, 'create', 'master', output ] wordlist = '' try: output_location = os.path.dirname(output) if not os.path.exists(output_location): os.makedirs(output_location) if os.path.exists(output): os.remove(output) self.log("Compiling Dictionary...", 1) # Read word lists and create a unique set of words words = set() for wordlist in wordlists: with open(wordlist, 'rb') as src: for word in src.read().split(b'\n'): words.add(word.replace(b'\r', b'')) # Compile wordlist against language util.call( [ self.binary, '--lang', lang, '--encoding=utf-8', 'create', 'master', output ], input_text=b'\n'.join(sorted(words)) + b'\n' ) except Exception: self.log(cmd, 0) self.log("Current wordlist: '%s'" % wordlist, 0) self.log("Problem compiling dictionary. Check the binary path and options.", 0) raise
[ "def", "compile_dictionary", "(", "self", ",", "lang", ",", "wordlists", ",", "encoding", ",", "output", ")", ":", "cmd", "=", "[", "self", ".", "binary", ",", "'--lang'", ",", "lang", ",", "'--encoding'", ",", "codecs", ".", "lookup", "(", "filters", ...
Compile user dictionary.
[ "Compile", "user", "dictionary", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L327-L370
facelessuser/pyspelling
pyspelling/__init__.py
Hunspell.setup_dictionary
def setup_dictionary(self, task): """Setup dictionary.""" dictionary_options = task.get('dictionary', {}) output = os.path.abspath(dictionary_options.get('output', self.dict_bin)) lang = dictionary_options.get('lang', 'en_US') wordlists = dictionary_options.get('wordlists', []) if lang and wordlists: self.compile_dictionary(lang, dictionary_options.get('wordlists', []), None, output) else: output = None return output
python
def setup_dictionary(self, task): """Setup dictionary.""" dictionary_options = task.get('dictionary', {}) output = os.path.abspath(dictionary_options.get('output', self.dict_bin)) lang = dictionary_options.get('lang', 'en_US') wordlists = dictionary_options.get('wordlists', []) if lang and wordlists: self.compile_dictionary(lang, dictionary_options.get('wordlists', []), None, output) else: output = None return output
[ "def", "setup_dictionary", "(", "self", ",", "task", ")", ":", "dictionary_options", "=", "task", ".", "get", "(", "'dictionary'", ",", "{", "}", ")", "output", "=", "os", ".", "path", ".", "abspath", "(", "dictionary_options", ".", "get", "(", "'output'...
Setup dictionary.
[ "Setup", "dictionary", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L471-L482
facelessuser/pyspelling
pyspelling/__init__.py
Hunspell.compile_dictionary
def compile_dictionary(self, lang, wordlists, encoding, output): """Compile user dictionary.""" wordlist = '' try: output_location = os.path.dirname(output) if not os.path.exists(output_location): os.makedirs(output_location) if os.path.exists(output): os.remove(output) self.log("Compiling Dictionary...", 1) # Read word lists and create a unique set of words words = set() for wordlist in wordlists: with open(wordlist, 'rb') as src: for word in src.read().split(b'\n'): words.add(word.replace(b'\r', b'')) # Sort and create wordlist with open(output, 'wb') as dest: dest.write(b'\n'.join(sorted(words)) + b'\n') except Exception: self.log('Problem compiling dictionary.', 0) self.log("Current wordlist '%s'" % wordlist) raise
python
def compile_dictionary(self, lang, wordlists, encoding, output): """Compile user dictionary.""" wordlist = '' try: output_location = os.path.dirname(output) if not os.path.exists(output_location): os.makedirs(output_location) if os.path.exists(output): os.remove(output) self.log("Compiling Dictionary...", 1) # Read word lists and create a unique set of words words = set() for wordlist in wordlists: with open(wordlist, 'rb') as src: for word in src.read().split(b'\n'): words.add(word.replace(b'\r', b'')) # Sort and create wordlist with open(output, 'wb') as dest: dest.write(b'\n'.join(sorted(words)) + b'\n') except Exception: self.log('Problem compiling dictionary.', 0) self.log("Current wordlist '%s'" % wordlist) raise
[ "def", "compile_dictionary", "(", "self", ",", "lang", ",", "wordlists", ",", "encoding", ",", "output", ")", ":", "wordlist", "=", "''", "try", ":", "output_location", "=", "os", ".", "path", ".", "dirname", "(", "output", ")", "if", "not", "os", ".",...
Compile user dictionary.
[ "Compile", "user", "dictionary", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L484-L509
facelessuser/pyspelling
pyspelling/__init__.py
Hunspell.spell_check_no_pipeline
def spell_check_no_pipeline(self, sources, options, personal_dict): """Spell check without the pipeline.""" for source in sources: if source._has_error(): # pragma: no cover yield Results([], source.context, source.category, source.error) cmd = self.setup_command(source.encoding, options, personal_dict, source.context) self.log('', 3) self.log("Command: " + str(cmd), 4) try: wordlist = util.call_spellchecker(cmd, input_text=None, encoding=source.encoding) yield Results( [w for w in sorted(set(wordlist.replace('\r', '').split('\n'))) if w], source.context, source.category ) except Exception as e: # pragma: no cover err = self.get_error(e) yield Results([], source.context, source.category, err)
python
def spell_check_no_pipeline(self, sources, options, personal_dict): """Spell check without the pipeline.""" for source in sources: if source._has_error(): # pragma: no cover yield Results([], source.context, source.category, source.error) cmd = self.setup_command(source.encoding, options, personal_dict, source.context) self.log('', 3) self.log("Command: " + str(cmd), 4) try: wordlist = util.call_spellchecker(cmd, input_text=None, encoding=source.encoding) yield Results( [w for w in sorted(set(wordlist.replace('\r', '').split('\n'))) if w], source.context, source.category ) except Exception as e: # pragma: no cover err = self.get_error(e) yield Results([], source.context, source.category, err)
[ "def", "spell_check_no_pipeline", "(", "self", ",", "sources", ",", "options", ",", "personal_dict", ")", ":", "for", "source", "in", "sources", ":", "if", "source", ".", "_has_error", "(", ")", ":", "# pragma: no cover", "yield", "Results", "(", "[", "]", ...
Spell check without the pipeline.
[ "Spell", "check", "without", "the", "pipeline", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L511-L530
facelessuser/pyspelling
pyspelling/__init__.py
Hunspell.setup_command
def setup_command(self, encoding, options, personal_dict, file_name=None): """Setup command.""" cmd = [ self.binary, '-l' ] if encoding: cmd.extend(['-i', encoding]) if personal_dict: cmd.extend(['-p', personal_dict]) allowed = { 'check-apostrophe', 'check-url', 'd', 'H', 'i', 'n', 'O', 'r', 't', 'X' } for k, v in options.items(): if k in allowed: key = ('-%s' if len(k) == 1 else '--%s') % k if isinstance(v, bool) and v is True: cmd.append(key) elif isinstance(v, str): cmd.extend([key, v]) elif isinstance(v, int): cmd.extend([key, str(v)]) elif isinstance(v, list): for value in v: cmd.extend([key, str(value)]) if file_name is not None: cmd.append(file_name) return cmd
python
def setup_command(self, encoding, options, personal_dict, file_name=None): """Setup command.""" cmd = [ self.binary, '-l' ] if encoding: cmd.extend(['-i', encoding]) if personal_dict: cmd.extend(['-p', personal_dict]) allowed = { 'check-apostrophe', 'check-url', 'd', 'H', 'i', 'n', 'O', 'r', 't', 'X' } for k, v in options.items(): if k in allowed: key = ('-%s' if len(k) == 1 else '--%s') % k if isinstance(v, bool) and v is True: cmd.append(key) elif isinstance(v, str): cmd.extend([key, v]) elif isinstance(v, int): cmd.extend([key, str(v)]) elif isinstance(v, list): for value in v: cmd.extend([key, str(value)]) if file_name is not None: cmd.append(file_name) return cmd
[ "def", "setup_command", "(", "self", ",", "encoding", ",", "options", ",", "personal_dict", ",", "file_name", "=", "None", ")", ":", "cmd", "=", "[", "self", ".", "binary", ",", "'-l'", "]", "if", "encoding", ":", "cmd", ".", "extend", "(", "[", "'-i...
Setup command.
[ "Setup", "command", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L532-L567
BBVA/data-refinery
datarefinery/TupleOperations.py
fusion
def fusion(fields, target_field, etl_func): """ TODO: dict based better than list based please :param fields: :param target_field: :param etl_func: :return: """ return compose(read_fields(fields), etl_func, write_field(target_field))
python
def fusion(fields, target_field, etl_func): """ TODO: dict based better than list based please :param fields: :param target_field: :param etl_func: :return: """ return compose(read_fields(fields), etl_func, write_field(target_field))
[ "def", "fusion", "(", "fields", ",", "target_field", ",", "etl_func", ")", ":", "return", "compose", "(", "read_fields", "(", "fields", ")", ",", "etl_func", ",", "write_field", "(", "target_field", ")", ")" ]
TODO: dict based better than list based please :param fields: :param target_field: :param etl_func: :return:
[ "TODO", ":", "dict", "based", "better", "than", "list", "based", "please" ]
train
https://github.com/BBVA/data-refinery/blob/4ff19186ac570269f64a245ad6297cf882c70aa4/datarefinery/TupleOperations.py#L34-L43
BBVA/data-refinery
datarefinery/TupleOperations.py
fusion_append
def fusion_append(fields, error_field, etl_func): """ TODO: dict based better than list based please :param fields: :param error_field: :param etl_func: :return: """ return compose(read_fields(fields), etl_func, dict_enforcer, write_error_field(error_field))
python
def fusion_append(fields, error_field, etl_func): """ TODO: dict based better than list based please :param fields: :param error_field: :param etl_func: :return: """ return compose(read_fields(fields), etl_func, dict_enforcer, write_error_field(error_field))
[ "def", "fusion_append", "(", "fields", ",", "error_field", ",", "etl_func", ")", ":", "return", "compose", "(", "read_fields", "(", "fields", ")", ",", "etl_func", ",", "dict_enforcer", ",", "write_error_field", "(", "error_field", ")", ")" ]
TODO: dict based better than list based please :param fields: :param error_field: :param etl_func: :return:
[ "TODO", ":", "dict", "based", "better", "than", "list", "based", "please" ]
train
https://github.com/BBVA/data-refinery/blob/4ff19186ac570269f64a245ad6297cf882c70aa4/datarefinery/TupleOperations.py#L46-L56
facelessuser/pyspelling
pyspelling/flow_control/wildcard.py
WildcardFlowControl.setup
def setup(self): """Get default configuration.""" self.allow = self.config['allow'] self.halt = self.config['halt'] self.skip = self.config['skip']
python
def setup(self): """Get default configuration.""" self.allow = self.config['allow'] self.halt = self.config['halt'] self.skip = self.config['skip']
[ "def", "setup", "(", "self", ")", ":", "self", ".", "allow", "=", "self", ".", "config", "[", "'allow'", "]", "self", ".", "halt", "=", "self", ".", "config", "[", "'halt'", "]", "self", ".", "skip", "=", "self", ".", "config", "[", "'skip'", "]"...
Get default configuration.
[ "Get", "default", "configuration", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/flow_control/wildcard.py#L26-L31
facelessuser/pyspelling
pyspelling/flow_control/wildcard.py
WildcardFlowControl.match
def match(self, category, pattern): """Match the category.""" return fnmatch.fnmatch(category, pattern, flags=self.FNMATCH_FLAGS)
python
def match(self, category, pattern): """Match the category.""" return fnmatch.fnmatch(category, pattern, flags=self.FNMATCH_FLAGS)
[ "def", "match", "(", "self", ",", "category", ",", "pattern", ")", ":", "return", "fnmatch", ".", "fnmatch", "(", "category", ",", "pattern", ",", "flags", "=", "self", ".", "FNMATCH_FLAGS", ")" ]
Match the category.
[ "Match", "the", "category", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/flow_control/wildcard.py#L33-L36
facelessuser/pyspelling
pyspelling/flow_control/wildcard.py
WildcardFlowControl.adjust_flow
def adjust_flow(self, category): """Adjust the flow of source control objects.""" status = flow_control.SKIP for allow in self.allow: if self.match(category, allow): status = flow_control.ALLOW for skip in self.skip: if self.match(category, skip): status = flow_control.SKIP for halt in self.halt: if self.match(category, halt): status = flow_control.HALT if status != flow_control.ALLOW: break return status
python
def adjust_flow(self, category): """Adjust the flow of source control objects.""" status = flow_control.SKIP for allow in self.allow: if self.match(category, allow): status = flow_control.ALLOW for skip in self.skip: if self.match(category, skip): status = flow_control.SKIP for halt in self.halt: if self.match(category, halt): status = flow_control.HALT if status != flow_control.ALLOW: break return status
[ "def", "adjust_flow", "(", "self", ",", "category", ")", ":", "status", "=", "flow_control", ".", "SKIP", "for", "allow", "in", "self", ".", "allow", ":", "if", "self", ".", "match", "(", "category", ",", "allow", ")", ":", "status", "=", "flow_control...
Adjust the flow of source control objects.
[ "Adjust", "the", "flow", "of", "source", "control", "objects", "." ]
train
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/flow_control/wildcard.py#L38-L53
deshima-dev/decode
decode/plot/functions.py
plot_tcoords
def plot_tcoords(array, coords, scantypes=None, ax=None, **kwargs): """Plot coordinates related to the time axis. Args: array (xarray.DataArray): Array which the coodinate information is included. coords (list): Name of x axis and y axis. scantypes (list): Scantypes. If None, all scantypes are used. ax (matplotlib.axes): Axis you want to plot on. kwargs (optional): Plot options passed to ax.plot(). """ if ax is None: ax = plt.gca() if scantypes is None: ax.plot(array[coords[0]], array[coords[1]], label='ALL', **kwargs) else: for scantype in scantypes: ax.plot(array[coords[0]][array.scantype == scantype], array[coords[1]][array.scantype == scantype], label=scantype, **kwargs) ax.set_xlabel(coords[0]) ax.set_ylabel(coords[1]) ax.set_title('{} vs {}'.format(coords[1], coords[0])) ax.legend() logger.info('{} vs {} has been plotted.'.format(coords[1], coords[0]))
python
def plot_tcoords(array, coords, scantypes=None, ax=None, **kwargs): """Plot coordinates related to the time axis. Args: array (xarray.DataArray): Array which the coodinate information is included. coords (list): Name of x axis and y axis. scantypes (list): Scantypes. If None, all scantypes are used. ax (matplotlib.axes): Axis you want to plot on. kwargs (optional): Plot options passed to ax.plot(). """ if ax is None: ax = plt.gca() if scantypes is None: ax.plot(array[coords[0]], array[coords[1]], label='ALL', **kwargs) else: for scantype in scantypes: ax.plot(array[coords[0]][array.scantype == scantype], array[coords[1]][array.scantype == scantype], label=scantype, **kwargs) ax.set_xlabel(coords[0]) ax.set_ylabel(coords[1]) ax.set_title('{} vs {}'.format(coords[1], coords[0])) ax.legend() logger.info('{} vs {} has been plotted.'.format(coords[1], coords[0]))
[ "def", "plot_tcoords", "(", "array", ",", "coords", ",", "scantypes", "=", "None", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "if", "scantypes", "is", "None", ...
Plot coordinates related to the time axis. Args: array (xarray.DataArray): Array which the coodinate information is included. coords (list): Name of x axis and y axis. scantypes (list): Scantypes. If None, all scantypes are used. ax (matplotlib.axes): Axis you want to plot on. kwargs (optional): Plot options passed to ax.plot().
[ "Plot", "coordinates", "related", "to", "the", "time", "axis", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/plot/functions.py#L29-L53
deshima-dev/decode
decode/plot/functions.py
plot_timestream
def plot_timestream(array, kidid, xtick='time', scantypes=None, ax=None, **kwargs): """Plot timestream data. Args: array (xarray.DataArray): Array which the timestream data are included. kidid (int): Kidid. xtick (str): Type of x axis. 'time': Time. 'index': Time index. scantypes (list): Scantypes. If None, all scantypes are used. ax (matplotlib.axes): Axis you want to plot on. kwargs (optional): Plot options passed to ax.plot(). """ if ax is None: ax = plt.gca() index = np.where(array.kidid == kidid)[0] if len(index) == 0: raise KeyError('Such a kidid does not exist.') index = int(index) if scantypes is None: if xtick == 'time': ax.plot(array.time, array[:, index], label='ALL', **kwargs) elif xtick == 'index': ax.plot(np.ogrid[:len(array.time)], array[:, index], label='ALL', **kwargs) else: for scantype in scantypes: if xtick == 'time': ax.plot(array.time[array.scantype == scantype], array[:, index][array.scantype == scantype], label=scantype, **kwargs) elif xtick == 'index': ax.plot(np.ogrid[:len(array.time[array.scantype == scantype])], array[:, index][array.scantype == scantype], label=scantype, **kwargs) ax.set_xlabel('{}'.format(xtick)) ax.set_ylabel(str(array.datatype.values)) ax.legend() kidtpdict = {0: 'wideband', 1: 'filter', 2: 'blind'} try: kidtp = kidtpdict[int(array.kidtp[index])] except KeyError: kidtp = 'filter' ax.set_title('ch #{} ({})'.format(kidid, kidtp)) logger.info('timestream data (ch={}) has been plotted.'.format(kidid))
python
def plot_timestream(array, kidid, xtick='time', scantypes=None, ax=None, **kwargs): """Plot timestream data. Args: array (xarray.DataArray): Array which the timestream data are included. kidid (int): Kidid. xtick (str): Type of x axis. 'time': Time. 'index': Time index. scantypes (list): Scantypes. If None, all scantypes are used. ax (matplotlib.axes): Axis you want to plot on. kwargs (optional): Plot options passed to ax.plot(). """ if ax is None: ax = plt.gca() index = np.where(array.kidid == kidid)[0] if len(index) == 0: raise KeyError('Such a kidid does not exist.') index = int(index) if scantypes is None: if xtick == 'time': ax.plot(array.time, array[:, index], label='ALL', **kwargs) elif xtick == 'index': ax.plot(np.ogrid[:len(array.time)], array[:, index], label='ALL', **kwargs) else: for scantype in scantypes: if xtick == 'time': ax.plot(array.time[array.scantype == scantype], array[:, index][array.scantype == scantype], label=scantype, **kwargs) elif xtick == 'index': ax.plot(np.ogrid[:len(array.time[array.scantype == scantype])], array[:, index][array.scantype == scantype], label=scantype, **kwargs) ax.set_xlabel('{}'.format(xtick)) ax.set_ylabel(str(array.datatype.values)) ax.legend() kidtpdict = {0: 'wideband', 1: 'filter', 2: 'blind'} try: kidtp = kidtpdict[int(array.kidtp[index])] except KeyError: kidtp = 'filter' ax.set_title('ch #{} ({})'.format(kidid, kidtp)) logger.info('timestream data (ch={}) has been plotted.'.format(kidid))
[ "def", "plot_timestream", "(", "array", ",", "kidid", ",", "xtick", "=", "'time'", ",", "scantypes", "=", "None", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", ...
Plot timestream data. Args: array (xarray.DataArray): Array which the timestream data are included. kidid (int): Kidid. xtick (str): Type of x axis. 'time': Time. 'index': Time index. scantypes (list): Scantypes. If None, all scantypes are used. ax (matplotlib.axes): Axis you want to plot on. kwargs (optional): Plot options passed to ax.plot().
[ "Plot", "timestream", "data", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/plot/functions.py#L56-L101
deshima-dev/decode
decode/plot/functions.py
plot_spectrum
def plot_spectrum(cube, xtick, ytick, aperture, ax=None, **kwargs): """Plot a spectrum. Args: cube (xarray.DataArray): Cube which the spectrum information is included. xtick (str): Type of x axis. 'freq': Frequency [GHz]. 'id': Kid id. ytick (str): Type of y axis. 'max': Maximum. 'sum': Summation. 'mean': Mean. aperture (str): The shape of aperture. 'box': Box. 'circle': Circle. ax (matplotlib.axes): Axis you want to plot on. kwargs (optional): When 'box' is specified as shape, xc: Center of x. yc: Center of y. width: Width. height: Height. xmin: Minimum of x. xmax: Maximum of x. ymin: Minimum of y. ymax: Maximum of y. When 'circle' is specified as shape, xc: Center of x. yc: Center of y. radius: Radius. Remaining kwargs are passed to ax.step(). Notes: All kwargs should be specified as pixel coordinates. """ if ax is None: ax = plt.gca() ### pick up kwargs xc = kwargs.pop('xc', None) yc = kwargs.pop('yc', None) width = kwargs.pop('width', None) height = kwargs.pop('height', None) xmin = kwargs.pop('xmin', None) xmax = kwargs.pop('xmax', None) ymin = kwargs.pop('ymin', None) ymax = kwargs.pop('ymax', None) radius = kwargs.pop('radius', None) exchs = kwargs.pop('exchs', None) ### labels xlabeldict = {'freq': 'frequency [GHz]', 'id': 'kidid'} cube = cube.copy() datatype = cube.datatype if aperture == 'box': if None not in [xc, yc, width, height]: xmin, xmax = int(xc - width / 2), int(xc + width / 2) ymin, ymax = int(yc - width / 2), int(yc + width / 2) elif None not in [xmin, xmax, ymin, ymax]: pass else: raise KeyError('Invalid arguments.') value = getattr(cube[xmin:xmax, ymin:ymax, :], ytick)(dim=('x', 'y')) elif aperture == 'circle': if None not in [xc, yc, radius]: pass else: raise KeyError('Invalid arguments.') x, y = np.ogrid[0:len(cube.x), 0:len(cube.y)] mask = ((x - xc)**2 + (y - yc)**2 < radius**2) mask = np.broadcast_to(mask[:, :, np.newaxis], cube.shape) masked = np.ma.array(cube.values, mask=~mask) value = getattr(np, 'nan'+ytick)(masked, axis=(0, 1)) else: raise KeyError(aperture) if xtick == 'freq': kidfq = cube.kidfq.values freqrange = ~np.isnan(kidfq) if exchs is not None: freqrange[exchs] = False x = kidfq[freqrange] y = value[freqrange] ax.step(x[np.argsort(x)], y[np.argsort(x)], where='mid', **kwargs) elif xtick == 'id': ax.step(cube.kidid.values, value, where='mid', **kwargs) else: raise KeyError(xtick) ax.set_xlabel('{}'.format(xlabeldict[xtick])) ax.set_ylabel('{} ({})'.format(datatype.values, ytick)) ax.set_title('spectrum')
python
def plot_spectrum(cube, xtick, ytick, aperture, ax=None, **kwargs): """Plot a spectrum. Args: cube (xarray.DataArray): Cube which the spectrum information is included. xtick (str): Type of x axis. 'freq': Frequency [GHz]. 'id': Kid id. ytick (str): Type of y axis. 'max': Maximum. 'sum': Summation. 'mean': Mean. aperture (str): The shape of aperture. 'box': Box. 'circle': Circle. ax (matplotlib.axes): Axis you want to plot on. kwargs (optional): When 'box' is specified as shape, xc: Center of x. yc: Center of y. width: Width. height: Height. xmin: Minimum of x. xmax: Maximum of x. ymin: Minimum of y. ymax: Maximum of y. When 'circle' is specified as shape, xc: Center of x. yc: Center of y. radius: Radius. Remaining kwargs are passed to ax.step(). Notes: All kwargs should be specified as pixel coordinates. """ if ax is None: ax = plt.gca() ### pick up kwargs xc = kwargs.pop('xc', None) yc = kwargs.pop('yc', None) width = kwargs.pop('width', None) height = kwargs.pop('height', None) xmin = kwargs.pop('xmin', None) xmax = kwargs.pop('xmax', None) ymin = kwargs.pop('ymin', None) ymax = kwargs.pop('ymax', None) radius = kwargs.pop('radius', None) exchs = kwargs.pop('exchs', None) ### labels xlabeldict = {'freq': 'frequency [GHz]', 'id': 'kidid'} cube = cube.copy() datatype = cube.datatype if aperture == 'box': if None not in [xc, yc, width, height]: xmin, xmax = int(xc - width / 2), int(xc + width / 2) ymin, ymax = int(yc - width / 2), int(yc + width / 2) elif None not in [xmin, xmax, ymin, ymax]: pass else: raise KeyError('Invalid arguments.') value = getattr(cube[xmin:xmax, ymin:ymax, :], ytick)(dim=('x', 'y')) elif aperture == 'circle': if None not in [xc, yc, radius]: pass else: raise KeyError('Invalid arguments.') x, y = np.ogrid[0:len(cube.x), 0:len(cube.y)] mask = ((x - xc)**2 + (y - yc)**2 < radius**2) mask = np.broadcast_to(mask[:, :, np.newaxis], cube.shape) masked = np.ma.array(cube.values, mask=~mask) value = getattr(np, 'nan'+ytick)(masked, axis=(0, 1)) else: raise KeyError(aperture) if xtick == 'freq': kidfq = cube.kidfq.values freqrange = ~np.isnan(kidfq) if exchs is not None: freqrange[exchs] = False x = kidfq[freqrange] y = value[freqrange] ax.step(x[np.argsort(x)], y[np.argsort(x)], where='mid', **kwargs) elif xtick == 'id': ax.step(cube.kidid.values, value, where='mid', **kwargs) else: raise KeyError(xtick) ax.set_xlabel('{}'.format(xlabeldict[xtick])) ax.set_ylabel('{} ({})'.format(datatype.values, ytick)) ax.set_title('spectrum')
[ "def", "plot_spectrum", "(", "cube", ",", "xtick", ",", "ytick", ",", "aperture", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "### pick up kwargs", "xc", "=", "...
Plot a spectrum. Args: cube (xarray.DataArray): Cube which the spectrum information is included. xtick (str): Type of x axis. 'freq': Frequency [GHz]. 'id': Kid id. ytick (str): Type of y axis. 'max': Maximum. 'sum': Summation. 'mean': Mean. aperture (str): The shape of aperture. 'box': Box. 'circle': Circle. ax (matplotlib.axes): Axis you want to plot on. kwargs (optional): When 'box' is specified as shape, xc: Center of x. yc: Center of y. width: Width. height: Height. xmin: Minimum of x. xmax: Maximum of x. ymin: Minimum of y. ymax: Maximum of y. When 'circle' is specified as shape, xc: Center of x. yc: Center of y. radius: Radius. Remaining kwargs are passed to ax.step(). Notes: All kwargs should be specified as pixel coordinates.
[ "Plot", "a", "spectrum", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/plot/functions.py#L104-L195
deshima-dev/decode
decode/plot/functions.py
plot_chmap
def plot_chmap(cube, kidid, ax=None, **kwargs): """Plot an intensity map. Args: cube (xarray.DataArray): Cube which the spectrum information is included. kidid (int): Kidid. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.imshow(). """ if ax is None: ax = plt.gca() index = np.where(cube.kidid == kidid)[0] if len(index) == 0: raise KeyError('Such a kidid does not exist.') index = int(index) im = ax.pcolormesh(cube.x, cube.y, cube[:, :, index].T, **kwargs) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_title('intensity map ch #{}'.format(kidid)) return im
python
def plot_chmap(cube, kidid, ax=None, **kwargs): """Plot an intensity map. Args: cube (xarray.DataArray): Cube which the spectrum information is included. kidid (int): Kidid. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.imshow(). """ if ax is None: ax = plt.gca() index = np.where(cube.kidid == kidid)[0] if len(index) == 0: raise KeyError('Such a kidid does not exist.') index = int(index) im = ax.pcolormesh(cube.x, cube.y, cube[:, :, index].T, **kwargs) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_title('intensity map ch #{}'.format(kidid)) return im
[ "def", "plot_chmap", "(", "cube", ",", "kidid", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "index", "=", "np", ".", "where", "(", "cube", ".", "kidid", "==...
Plot an intensity map. Args: cube (xarray.DataArray): Cube which the spectrum information is included. kidid (int): Kidid. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.imshow().
[ "Plot", "an", "intensity", "map", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/plot/functions.py#L198-L219
deshima-dev/decode
decode/plot/functions.py
plotpsd
def plotpsd(data, dt, ndivide=1, window=hanning, overlap_half=False, ax=None, **kwargs): """Plot PSD (Power Spectral Density). Args: data (np.ndarray): Input data. dt (float): Time between each data. ndivide (int): Do averaging (split data into ndivide, get psd of each, and average them). overlap_half (bool): Split data to half-overlapped regions. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.plot(). """ if ax is None: ax = plt.gca() vk, psddata = psd(data, dt, ndivide, window, overlap_half) ax.loglog(vk, psddata, **kwargs) ax.set_xlabel('Frequency [Hz]') ax.set_ylabel('PSD') ax.legend()
python
def plotpsd(data, dt, ndivide=1, window=hanning, overlap_half=False, ax=None, **kwargs): """Plot PSD (Power Spectral Density). Args: data (np.ndarray): Input data. dt (float): Time between each data. ndivide (int): Do averaging (split data into ndivide, get psd of each, and average them). overlap_half (bool): Split data to half-overlapped regions. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.plot(). """ if ax is None: ax = plt.gca() vk, psddata = psd(data, dt, ndivide, window, overlap_half) ax.loglog(vk, psddata, **kwargs) ax.set_xlabel('Frequency [Hz]') ax.set_ylabel('PSD') ax.legend()
[ "def", "plotpsd", "(", "data", ",", "dt", ",", "ndivide", "=", "1", ",", "window", "=", "hanning", ",", "overlap_half", "=", "False", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", "....
Plot PSD (Power Spectral Density). Args: data (np.ndarray): Input data. dt (float): Time between each data. ndivide (int): Do averaging (split data into ndivide, get psd of each, and average them). overlap_half (bool): Split data to half-overlapped regions. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.plot().
[ "Plot", "PSD", "(", "Power", "Spectral", "Density", ")", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/plot/functions.py#L222-L239
deshima-dev/decode
decode/plot/functions.py
plotallanvar
def plotallanvar(data, dt, tmax=10, ax=None, **kwargs): """Plot Allan variance. Args: data (np.ndarray): Input data. dt (float): Time between each data. tmax (float): Maximum time. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.plot(). """ if ax is None: ax = plt.gca() tk, allanvar = allan_variance(data, dt, tmax) ax.loglog(tk, allanvar, **kwargs) ax.set_xlabel('Time [s]') ax.set_ylabel('Allan Variance') ax.legend()
python
def plotallanvar(data, dt, tmax=10, ax=None, **kwargs): """Plot Allan variance. Args: data (np.ndarray): Input data. dt (float): Time between each data. tmax (float): Maximum time. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.plot(). """ if ax is None: ax = plt.gca() tk, allanvar = allan_variance(data, dt, tmax) ax.loglog(tk, allanvar, **kwargs) ax.set_xlabel('Time [s]') ax.set_ylabel('Allan Variance') ax.legend()
[ "def", "plotallanvar", "(", "data", ",", "dt", ",", "tmax", "=", "10", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "tk", ",", "allanvar", "=", "allan_variance...
Plot Allan variance. Args: data (np.ndarray): Input data. dt (float): Time between each data. tmax (float): Maximum time. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.plot().
[ "Plot", "Allan", "variance", "." ]
train
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/plot/functions.py#L242-L258
KeithSSmith/switcheo-python
switcheo/authenticated_client.py
AuthenticatedClient.cancel_order
def cancel_order(self, order_id, private_key): """ This function is a wrapper function around the create and execute cancellation functions to help make this processes simpler for the end user by combining these requests in 1 step. Execution of this function is as follows:: cancel_order(order_id=order['id'], private_key=kp) cancel_order(order_id=order['id'], private_key=eth_private_key) The expected return result for this function is the same as the execute_cancellation function:: { 'id': 'b8e617d5-f5ed-4600-b8f2-7d370d837750', 'blockchain': 'neo', 'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59', 'side': 'buy', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'offer_amount': '2000000', 'want_amount': '10000000000', 'transfer_amount': '0', 'priority_gas_amount': '0', 'use_native_token': True, 'native_fee_transfer_amount': 0, 'deposit_txn': None, 'created_at': '2018-08-05T11:16:47.021Z', 'status': 'processed', 'fills': [], 'makes': [ { 'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74', 'offer_hash': '6830d82dbdda566ab32e9a8d9d9d94d3297f67c10374d69bb35d6c5a86bd3e92', 'available_amount': '0', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'offer_amount': '2000000', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'want_amount': '10000000000', 'filled_amount': '0.0', 'txn': None, 'cancel_txn': None, 'price': '0.0002', 'status': 'cancelling', 'created_at': '2018-08-05T11:16:47.036Z', 'transaction_hash': 'e5b08c4a55c7494f1ec7dd93ac2bb2b4e84e77dec9e00e91be1d520cb818c415', 'trades': [] } ] } :param order_id: The order ID of the open transaction on the order book that you want to cancel. :type order_id: str :param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain. :type private_key: KeyPair :return: Dictionary of the transaction details and state after sending the signed transaction to the blockchain. """ create_cancellation = self.create_cancellation(order_id=order_id, private_key=private_key) return self.execute_cancellation(cancellation_params=create_cancellation, private_key=private_key)
python
def cancel_order(self, order_id, private_key): """ This function is a wrapper function around the create and execute cancellation functions to help make this processes simpler for the end user by combining these requests in 1 step. Execution of this function is as follows:: cancel_order(order_id=order['id'], private_key=kp) cancel_order(order_id=order['id'], private_key=eth_private_key) The expected return result for this function is the same as the execute_cancellation function:: { 'id': 'b8e617d5-f5ed-4600-b8f2-7d370d837750', 'blockchain': 'neo', 'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59', 'side': 'buy', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'offer_amount': '2000000', 'want_amount': '10000000000', 'transfer_amount': '0', 'priority_gas_amount': '0', 'use_native_token': True, 'native_fee_transfer_amount': 0, 'deposit_txn': None, 'created_at': '2018-08-05T11:16:47.021Z', 'status': 'processed', 'fills': [], 'makes': [ { 'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74', 'offer_hash': '6830d82dbdda566ab32e9a8d9d9d94d3297f67c10374d69bb35d6c5a86bd3e92', 'available_amount': '0', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'offer_amount': '2000000', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'want_amount': '10000000000', 'filled_amount': '0.0', 'txn': None, 'cancel_txn': None, 'price': '0.0002', 'status': 'cancelling', 'created_at': '2018-08-05T11:16:47.036Z', 'transaction_hash': 'e5b08c4a55c7494f1ec7dd93ac2bb2b4e84e77dec9e00e91be1d520cb818c415', 'trades': [] } ] } :param order_id: The order ID of the open transaction on the order book that you want to cancel. :type order_id: str :param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain. :type private_key: KeyPair :return: Dictionary of the transaction details and state after sending the signed transaction to the blockchain. """ create_cancellation = self.create_cancellation(order_id=order_id, private_key=private_key) return self.execute_cancellation(cancellation_params=create_cancellation, private_key=private_key)
[ "def", "cancel_order", "(", "self", ",", "order_id", ",", "private_key", ")", ":", "create_cancellation", "=", "self", ".", "create_cancellation", "(", "order_id", "=", "order_id", ",", "private_key", "=", "private_key", ")", "return", "self", ".", "execute_canc...
This function is a wrapper function around the create and execute cancellation functions to help make this processes simpler for the end user by combining these requests in 1 step. Execution of this function is as follows:: cancel_order(order_id=order['id'], private_key=kp) cancel_order(order_id=order['id'], private_key=eth_private_key) The expected return result for this function is the same as the execute_cancellation function:: { 'id': 'b8e617d5-f5ed-4600-b8f2-7d370d837750', 'blockchain': 'neo', 'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59', 'side': 'buy', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'offer_amount': '2000000', 'want_amount': '10000000000', 'transfer_amount': '0', 'priority_gas_amount': '0', 'use_native_token': True, 'native_fee_transfer_amount': 0, 'deposit_txn': None, 'created_at': '2018-08-05T11:16:47.021Z', 'status': 'processed', 'fills': [], 'makes': [ { 'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74', 'offer_hash': '6830d82dbdda566ab32e9a8d9d9d94d3297f67c10374d69bb35d6c5a86bd3e92', 'available_amount': '0', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'offer_amount': '2000000', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'want_amount': '10000000000', 'filled_amount': '0.0', 'txn': None, 'cancel_txn': None, 'price': '0.0002', 'status': 'cancelling', 'created_at': '2018-08-05T11:16:47.036Z', 'transaction_hash': 'e5b08c4a55c7494f1ec7dd93ac2bb2b4e84e77dec9e00e91be1d520cb818c415', 'trades': [] } ] } :param order_id: The order ID of the open transaction on the order book that you want to cancel. :type order_id: str :param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain. :type private_key: KeyPair :return: Dictionary of the transaction details and state after sending the signed transaction to the blockchain.
[ "This", "function", "is", "a", "wrapper", "function", "around", "the", "create", "and", "execute", "cancellation", "functions", "to", "help", "make", "this", "processes", "simpler", "for", "the", "end", "user", "by", "combining", "these", "requests", "in", "1"...
train
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/authenticated_client.py#L89-L146
KeithSSmith/switcheo-python
switcheo/authenticated_client.py
AuthenticatedClient.create_cancellation
def create_cancellation(self, order_id, private_key): """ Function to create a cancellation request for the order ID from the open orders on the order book. Execution of this function is as follows:: create_cancellation(order_id=order['id'], private_key=kp) The expected return result for this function is as follows:: { 'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74', 'transaction': { 'hash': '50d99ebd7e57dbdceb7edc2014da5f446c8f44cc0a0b6d9c762a29e8a74bb051', 'sha256': '509edb9888fa675988fa71a27600b2655e63fe979424f13f5c958897b2e99ed8', 'type': 209, 'version': 1, 'attributes': [ { 'usage': 32, 'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe' } ], 'inputs': [ { 'prevHash': '9eaca1adcbbc0669a936576cb9ad03c11c99c356347aae3037ce1f0e4d330d85', 'prevIndex': 0 }, { 'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d', 'prevIndex': 37 } ], 'outputs': [ { 'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7', 'scriptHash': 'e707714512577b42f9a011f8b870625429f93573', 'value': 1e-08 } ], 'scripts': [], 'script': '....', 'gas': 0 }, 'script_params': { 'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'operation': 'cancelOffer', 'args': [ '923ebd865a6c5db39bd67403c1677f29d3949d9d8d9a2eb36a56dabd2dd83068' ] } } :param order_id: The order ID of the open transaction on the order book that you want to cancel. :type order_id: str :param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain. :type private_key: KeyPair :return: Dictionary that contains the cancellation request along with blockchain transaction information. """ cancellation_params = { "order_id": order_id, "timestamp": get_epoch_milliseconds() } api_params = self.sign_create_cancellation_function[self.blockchain](cancellation_params, private_key) return self.request.post(path='/cancellations', json_data=api_params)
python
def create_cancellation(self, order_id, private_key): """ Function to create a cancellation request for the order ID from the open orders on the order book. Execution of this function is as follows:: create_cancellation(order_id=order['id'], private_key=kp) The expected return result for this function is as follows:: { 'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74', 'transaction': { 'hash': '50d99ebd7e57dbdceb7edc2014da5f446c8f44cc0a0b6d9c762a29e8a74bb051', 'sha256': '509edb9888fa675988fa71a27600b2655e63fe979424f13f5c958897b2e99ed8', 'type': 209, 'version': 1, 'attributes': [ { 'usage': 32, 'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe' } ], 'inputs': [ { 'prevHash': '9eaca1adcbbc0669a936576cb9ad03c11c99c356347aae3037ce1f0e4d330d85', 'prevIndex': 0 }, { 'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d', 'prevIndex': 37 } ], 'outputs': [ { 'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7', 'scriptHash': 'e707714512577b42f9a011f8b870625429f93573', 'value': 1e-08 } ], 'scripts': [], 'script': '....', 'gas': 0 }, 'script_params': { 'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'operation': 'cancelOffer', 'args': [ '923ebd865a6c5db39bd67403c1677f29d3949d9d8d9a2eb36a56dabd2dd83068' ] } } :param order_id: The order ID of the open transaction on the order book that you want to cancel. :type order_id: str :param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain. :type private_key: KeyPair :return: Dictionary that contains the cancellation request along with blockchain transaction information. """ cancellation_params = { "order_id": order_id, "timestamp": get_epoch_milliseconds() } api_params = self.sign_create_cancellation_function[self.blockchain](cancellation_params, private_key) return self.request.post(path='/cancellations', json_data=api_params)
[ "def", "create_cancellation", "(", "self", ",", "order_id", ",", "private_key", ")", ":", "cancellation_params", "=", "{", "\"order_id\"", ":", "order_id", ",", "\"timestamp\"", ":", "get_epoch_milliseconds", "(", ")", "}", "api_params", "=", "self", ".", "sign_...
Function to create a cancellation request for the order ID from the open orders on the order book. Execution of this function is as follows:: create_cancellation(order_id=order['id'], private_key=kp) The expected return result for this function is as follows:: { 'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74', 'transaction': { 'hash': '50d99ebd7e57dbdceb7edc2014da5f446c8f44cc0a0b6d9c762a29e8a74bb051', 'sha256': '509edb9888fa675988fa71a27600b2655e63fe979424f13f5c958897b2e99ed8', 'type': 209, 'version': 1, 'attributes': [ { 'usage': 32, 'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe' } ], 'inputs': [ { 'prevHash': '9eaca1adcbbc0669a936576cb9ad03c11c99c356347aae3037ce1f0e4d330d85', 'prevIndex': 0 }, { 'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d', 'prevIndex': 37 } ], 'outputs': [ { 'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7', 'scriptHash': 'e707714512577b42f9a011f8b870625429f93573', 'value': 1e-08 } ], 'scripts': [], 'script': '....', 'gas': 0 }, 'script_params': { 'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'operation': 'cancelOffer', 'args': [ '923ebd865a6c5db39bd67403c1677f29d3949d9d8d9a2eb36a56dabd2dd83068' ] } } :param order_id: The order ID of the open transaction on the order book that you want to cancel. :type order_id: str :param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain. :type private_key: KeyPair :return: Dictionary that contains the cancellation request along with blockchain transaction information.
[ "Function", "to", "create", "a", "cancellation", "request", "for", "the", "order", "ID", "from", "the", "open", "orders", "on", "the", "order", "book", ".", "Execution", "of", "this", "function", "is", "as", "follows", "::" ]
train
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/authenticated_client.py#L148-L210
KeithSSmith/switcheo-python
switcheo/authenticated_client.py
AuthenticatedClient.execute_cancellation
def execute_cancellation(self, cancellation_params, private_key): """ This function executes the order created before it and signs the transaction to be submitted to the blockchain. Execution of this function is as follows:: execute_cancellation(cancellation_params=create_cancellation, private_key=kp) The expected return result for this function is as follows:: { 'id': 'b8e617d5-f5ed-4600-b8f2-7d370d837750', 'blockchain': 'neo', 'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59', 'side': 'buy', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'offer_amount': '2000000', 'want_amount': '10000000000', 'transfer_amount': '0', 'priority_gas_amount': '0', 'use_native_token': True, 'native_fee_transfer_amount': 0, 'deposit_txn': None, 'created_at': '2018-08-05T11:16:47.021Z', 'status': 'processed', 'fills': [], 'makes': [ { 'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74', 'offer_hash': '6830d82dbdda566ab32e9a8d9d9d94d3297f67c10374d69bb35d6c5a86bd3e92', 'available_amount': '0', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'offer_amount': '2000000', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'want_amount': '10000000000', 'filled_amount': '0.0', 'txn': None, 'cancel_txn': None, 'price': '0.0002', 'status': 'cancelling', 'created_at': '2018-08-05T11:16:47.036Z', 'transaction_hash': 'e5b08c4a55c7494f1ec7dd93ac2bb2b4e84e77dec9e00e91be1d520cb818c415', 'trades': [] } ] } :param cancellation_params: Parameters generated from the Switcheo API to cancel an order on the order book. :type cancellation_params: dict :param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain. :type private_key: KeyPair :return: Dictionary of the transaction details and state after sending the signed transaction to the blockchain. """ cancellation_id = cancellation_params['id'] api_params = self.sign_execute_cancellation_function[self.blockchain](cancellation_params, private_key) return self.request.post(path='/cancellations/{}/broadcast'.format(cancellation_id), json_data=api_params)
python
def execute_cancellation(self, cancellation_params, private_key): """ This function executes the order created before it and signs the transaction to be submitted to the blockchain. Execution of this function is as follows:: execute_cancellation(cancellation_params=create_cancellation, private_key=kp) The expected return result for this function is as follows:: { 'id': 'b8e617d5-f5ed-4600-b8f2-7d370d837750', 'blockchain': 'neo', 'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59', 'side': 'buy', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'offer_amount': '2000000', 'want_amount': '10000000000', 'transfer_amount': '0', 'priority_gas_amount': '0', 'use_native_token': True, 'native_fee_transfer_amount': 0, 'deposit_txn': None, 'created_at': '2018-08-05T11:16:47.021Z', 'status': 'processed', 'fills': [], 'makes': [ { 'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74', 'offer_hash': '6830d82dbdda566ab32e9a8d9d9d94d3297f67c10374d69bb35d6c5a86bd3e92', 'available_amount': '0', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'offer_amount': '2000000', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'want_amount': '10000000000', 'filled_amount': '0.0', 'txn': None, 'cancel_txn': None, 'price': '0.0002', 'status': 'cancelling', 'created_at': '2018-08-05T11:16:47.036Z', 'transaction_hash': 'e5b08c4a55c7494f1ec7dd93ac2bb2b4e84e77dec9e00e91be1d520cb818c415', 'trades': [] } ] } :param cancellation_params: Parameters generated from the Switcheo API to cancel an order on the order book. :type cancellation_params: dict :param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain. :type private_key: KeyPair :return: Dictionary of the transaction details and state after sending the signed transaction to the blockchain. """ cancellation_id = cancellation_params['id'] api_params = self.sign_execute_cancellation_function[self.blockchain](cancellation_params, private_key) return self.request.post(path='/cancellations/{}/broadcast'.format(cancellation_id), json_data=api_params)
[ "def", "execute_cancellation", "(", "self", ",", "cancellation_params", ",", "private_key", ")", ":", "cancellation_id", "=", "cancellation_params", "[", "'id'", "]", "api_params", "=", "self", ".", "sign_execute_cancellation_function", "[", "self", ".", "blockchain",...
This function executes the order created before it and signs the transaction to be submitted to the blockchain. Execution of this function is as follows:: execute_cancellation(cancellation_params=create_cancellation, private_key=kp) The expected return result for this function is as follows:: { 'id': 'b8e617d5-f5ed-4600-b8f2-7d370d837750', 'blockchain': 'neo', 'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59', 'side': 'buy', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'offer_amount': '2000000', 'want_amount': '10000000000', 'transfer_amount': '0', 'priority_gas_amount': '0', 'use_native_token': True, 'native_fee_transfer_amount': 0, 'deposit_txn': None, 'created_at': '2018-08-05T11:16:47.021Z', 'status': 'processed', 'fills': [], 'makes': [ { 'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74', 'offer_hash': '6830d82dbdda566ab32e9a8d9d9d94d3297f67c10374d69bb35d6c5a86bd3e92', 'available_amount': '0', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'offer_amount': '2000000', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'want_amount': '10000000000', 'filled_amount': '0.0', 'txn': None, 'cancel_txn': None, 'price': '0.0002', 'status': 'cancelling', 'created_at': '2018-08-05T11:16:47.036Z', 'transaction_hash': 'e5b08c4a55c7494f1ec7dd93ac2bb2b4e84e77dec9e00e91be1d520cb818c415', 'trades': [] } ] } :param cancellation_params: Parameters generated from the Switcheo API to cancel an order on the order book. :type cancellation_params: dict :param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain. :type private_key: KeyPair :return: Dictionary of the transaction details and state after sending the signed transaction to the blockchain.
[ "This", "function", "executes", "the", "order", "created", "before", "it", "and", "signs", "the", "transaction", "to", "be", "submitted", "to", "the", "blockchain", ".", "Execution", "of", "this", "function", "is", "as", "follows", "::" ]
train
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/authenticated_client.py#L212-L268
KeithSSmith/switcheo-python
switcheo/authenticated_client.py
AuthenticatedClient.deposit
def deposit(self, asset, amount, private_key): """ This function is a wrapper function around the create and execute deposit functions to help make this processes simpler for the end user by combining these requests in 1 step. Execution of this function is as follows:: deposit(asset="SWTH", amount=1.1, private_key=KeyPair) deposit(asset="SWTH", amount=1.1, private_key=eth_private_key) The expected return result for this function is the same as the execute_deposit function:: { 'result': 'ok' } :param asset: Symbol or Script Hash of asset ID from the available products. :type asset: str :param amount: The amount of coins/tokens to be deposited. :type amount: float :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :return: Dictionary with the result status of the deposit attempt. """ create_deposit = self.create_deposit(asset=asset, amount=amount, private_key=private_key) return self.execute_deposit(deposit_params=create_deposit, private_key=private_key)
python
def deposit(self, asset, amount, private_key): """ This function is a wrapper function around the create and execute deposit functions to help make this processes simpler for the end user by combining these requests in 1 step. Execution of this function is as follows:: deposit(asset="SWTH", amount=1.1, private_key=KeyPair) deposit(asset="SWTH", amount=1.1, private_key=eth_private_key) The expected return result for this function is the same as the execute_deposit function:: { 'result': 'ok' } :param asset: Symbol or Script Hash of asset ID from the available products. :type asset: str :param amount: The amount of coins/tokens to be deposited. :type amount: float :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :return: Dictionary with the result status of the deposit attempt. """ create_deposit = self.create_deposit(asset=asset, amount=amount, private_key=private_key) return self.execute_deposit(deposit_params=create_deposit, private_key=private_key)
[ "def", "deposit", "(", "self", ",", "asset", ",", "amount", ",", "private_key", ")", ":", "create_deposit", "=", "self", ".", "create_deposit", "(", "asset", "=", "asset", ",", "amount", "=", "amount", ",", "private_key", "=", "private_key", ")", "return",...
This function is a wrapper function around the create and execute deposit functions to help make this processes simpler for the end user by combining these requests in 1 step. Execution of this function is as follows:: deposit(asset="SWTH", amount=1.1, private_key=KeyPair) deposit(asset="SWTH", amount=1.1, private_key=eth_private_key) The expected return result for this function is the same as the execute_deposit function:: { 'result': 'ok' } :param asset: Symbol or Script Hash of asset ID from the available products. :type asset: str :param amount: The amount of coins/tokens to be deposited. :type amount: float :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :return: Dictionary with the result status of the deposit attempt.
[ "This", "function", "is", "a", "wrapper", "function", "around", "the", "create", "and", "execute", "deposit", "functions", "to", "help", "make", "this", "processes", "simpler", "for", "the", "end", "user", "by", "combining", "these", "requests", "in", "1", "...
train
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/authenticated_client.py#L270-L294
KeithSSmith/switcheo-python
switcheo/authenticated_client.py
AuthenticatedClient.create_deposit
def create_deposit(self, asset, amount, private_key): """ Function to create a deposit request by generating a transaction request from the Switcheo API. Execution of this function is as follows:: create_deposit(asset="SWTH", amount=1.1, private_key=KeyPair) create_deposit(asset="ETH", amount=1.1, private_key=eth_private_key) The expected return result for this function is as follows:: { 'id': '768e2079-1504-4dad-b688-7e1e99ec0a24', 'transaction': { 'hash': '72b74c96b9174e9b9e1b216f7e8f21a6475e6541876a62614df7c1998c6e8376', 'sha256': '2109cbb5eea67a06f5dd8663e10fcd1128e28df5721a25d993e05fe2097c34f3', 'type': 209, 'version': 1, 'attributes': [ { 'usage': 32, 'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe' } ], 'inputs': [ { 'prevHash': 'f09b3b697c580d1730cd360da5e1f0beeae00827eb2f0055cbc85a5a4dadd8ea', 'prevIndex': 0 }, { 'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d', 'prevIndex': 31 } ], 'outputs': [ { 'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7', 'scriptHash': 'e707714512577b42f9a011f8b870625429f93573', 'value': 1e-08 } ], 'scripts': [], 'script': '....', 'gas': 0 }, 'script_params': { 'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'operation': 'deposit', 'args': [ '592c8a46a0d06c600f06c994d1f25e7283b8a2fe', '32e125258b7db0a0dffde5bd03b2b859253538ab', 100000000 ] } } :param asset: Symbol or Script Hash of asset ID from the available products. :type asset: str :param amount: The amount of coins/tokens to be deposited. :type amount: float :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :return: Dictionary response of signed deposit request that is ready to be executed on the specified blockchain. """ signable_params = { 'blockchain': self.blockchain, 'asset_id': asset, 'amount': str(self.blockchain_amount[self.blockchain](amount)), 'timestamp': get_epoch_milliseconds(), 'contract_hash': self.contract_hash } api_params = self.sign_create_deposit_function[self.blockchain](signable_params, private_key) return self.request.post(path='/deposits', json_data=api_params)
python
def create_deposit(self, asset, amount, private_key): """ Function to create a deposit request by generating a transaction request from the Switcheo API. Execution of this function is as follows:: create_deposit(asset="SWTH", amount=1.1, private_key=KeyPair) create_deposit(asset="ETH", amount=1.1, private_key=eth_private_key) The expected return result for this function is as follows:: { 'id': '768e2079-1504-4dad-b688-7e1e99ec0a24', 'transaction': { 'hash': '72b74c96b9174e9b9e1b216f7e8f21a6475e6541876a62614df7c1998c6e8376', 'sha256': '2109cbb5eea67a06f5dd8663e10fcd1128e28df5721a25d993e05fe2097c34f3', 'type': 209, 'version': 1, 'attributes': [ { 'usage': 32, 'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe' } ], 'inputs': [ { 'prevHash': 'f09b3b697c580d1730cd360da5e1f0beeae00827eb2f0055cbc85a5a4dadd8ea', 'prevIndex': 0 }, { 'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d', 'prevIndex': 31 } ], 'outputs': [ { 'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7', 'scriptHash': 'e707714512577b42f9a011f8b870625429f93573', 'value': 1e-08 } ], 'scripts': [], 'script': '....', 'gas': 0 }, 'script_params': { 'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'operation': 'deposit', 'args': [ '592c8a46a0d06c600f06c994d1f25e7283b8a2fe', '32e125258b7db0a0dffde5bd03b2b859253538ab', 100000000 ] } } :param asset: Symbol or Script Hash of asset ID from the available products. :type asset: str :param amount: The amount of coins/tokens to be deposited. :type amount: float :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :return: Dictionary response of signed deposit request that is ready to be executed on the specified blockchain. """ signable_params = { 'blockchain': self.blockchain, 'asset_id': asset, 'amount': str(self.blockchain_amount[self.blockchain](amount)), 'timestamp': get_epoch_milliseconds(), 'contract_hash': self.contract_hash } api_params = self.sign_create_deposit_function[self.blockchain](signable_params, private_key) return self.request.post(path='/deposits', json_data=api_params)
[ "def", "create_deposit", "(", "self", ",", "asset", ",", "amount", ",", "private_key", ")", ":", "signable_params", "=", "{", "'blockchain'", ":", "self", ".", "blockchain", ",", "'asset_id'", ":", "asset", ",", "'amount'", ":", "str", "(", "self", ".", ...
Function to create a deposit request by generating a transaction request from the Switcheo API. Execution of this function is as follows:: create_deposit(asset="SWTH", amount=1.1, private_key=KeyPair) create_deposit(asset="ETH", amount=1.1, private_key=eth_private_key) The expected return result for this function is as follows:: { 'id': '768e2079-1504-4dad-b688-7e1e99ec0a24', 'transaction': { 'hash': '72b74c96b9174e9b9e1b216f7e8f21a6475e6541876a62614df7c1998c6e8376', 'sha256': '2109cbb5eea67a06f5dd8663e10fcd1128e28df5721a25d993e05fe2097c34f3', 'type': 209, 'version': 1, 'attributes': [ { 'usage': 32, 'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe' } ], 'inputs': [ { 'prevHash': 'f09b3b697c580d1730cd360da5e1f0beeae00827eb2f0055cbc85a5a4dadd8ea', 'prevIndex': 0 }, { 'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d', 'prevIndex': 31 } ], 'outputs': [ { 'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7', 'scriptHash': 'e707714512577b42f9a011f8b870625429f93573', 'value': 1e-08 } ], 'scripts': [], 'script': '....', 'gas': 0 }, 'script_params': { 'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'operation': 'deposit', 'args': [ '592c8a46a0d06c600f06c994d1f25e7283b8a2fe', '32e125258b7db0a0dffde5bd03b2b859253538ab', 100000000 ] } } :param asset: Symbol or Script Hash of asset ID from the available products. :type asset: str :param amount: The amount of coins/tokens to be deposited. :type amount: float :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :return: Dictionary response of signed deposit request that is ready to be executed on the specified blockchain.
[ "Function", "to", "create", "a", "deposit", "request", "by", "generating", "a", "transaction", "request", "from", "the", "Switcheo", "API", ".", "Execution", "of", "this", "function", "is", "as", "follows", "::" ]
train
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/authenticated_client.py#L296-L366
KeithSSmith/switcheo-python
switcheo/authenticated_client.py
AuthenticatedClient.execute_deposit
def execute_deposit(self, deposit_params, private_key): """ Function to execute the deposit request by signing the transaction generated by the create deposit function. Execution of this function is as follows:: execute_deposit(deposit_params=create_deposit, private_key=KeyPair) execute_deposit(deposit_params=create_deposit, private_key=eth_private_key) The expected return result for this function is as follows:: { 'result': 'ok' } :param deposit_params: Parameters from the API to be signed and deposited to the Switcheo Smart Contract. :type deposit_params: dict :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :return: Dictionary with the result status of the deposit attempt. """ deposit_id = deposit_params['id'] api_params = self.sign_execute_deposit_function[self.blockchain](deposit_params, private_key) return self.request.post(path='/deposits/{}/broadcast'.format(deposit_id), json_data=api_params)
python
def execute_deposit(self, deposit_params, private_key): """ Function to execute the deposit request by signing the transaction generated by the create deposit function. Execution of this function is as follows:: execute_deposit(deposit_params=create_deposit, private_key=KeyPair) execute_deposit(deposit_params=create_deposit, private_key=eth_private_key) The expected return result for this function is as follows:: { 'result': 'ok' } :param deposit_params: Parameters from the API to be signed and deposited to the Switcheo Smart Contract. :type deposit_params: dict :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :return: Dictionary with the result status of the deposit attempt. """ deposit_id = deposit_params['id'] api_params = self.sign_execute_deposit_function[self.blockchain](deposit_params, private_key) return self.request.post(path='/deposits/{}/broadcast'.format(deposit_id), json_data=api_params)
[ "def", "execute_deposit", "(", "self", ",", "deposit_params", ",", "private_key", ")", ":", "deposit_id", "=", "deposit_params", "[", "'id'", "]", "api_params", "=", "self", ".", "sign_execute_deposit_function", "[", "self", ".", "blockchain", "]", "(", "deposit...
Function to execute the deposit request by signing the transaction generated by the create deposit function. Execution of this function is as follows:: execute_deposit(deposit_params=create_deposit, private_key=KeyPair) execute_deposit(deposit_params=create_deposit, private_key=eth_private_key) The expected return result for this function is as follows:: { 'result': 'ok' } :param deposit_params: Parameters from the API to be signed and deposited to the Switcheo Smart Contract. :type deposit_params: dict :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :return: Dictionary with the result status of the deposit attempt.
[ "Function", "to", "execute", "the", "deposit", "request", "by", "signing", "the", "transaction", "generated", "by", "the", "create", "deposit", "function", ".", "Execution", "of", "this", "function", "is", "as", "follows", "::" ]
train
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/authenticated_client.py#L368-L390
KeithSSmith/switcheo-python
switcheo/authenticated_client.py
AuthenticatedClient.order
def order(self, pair, side, price, quantity, private_key, use_native_token=True, order_type="limit"): """ This function is a wrapper function around the create and execute order functions to help make this processes simpler for the end user by combining these requests in 1 step. Execution of this function is as follows:: order(pair="SWTH_NEO", side="buy", price=0.0002, quantity=100, private_key=kp, use_native_token=True, order_type="limit") The expected return result for this function is the same as the execute_order function:: { 'id': '4e6a59fd-d750-4332-aaf0-f2babfa8ad67', 'blockchain': 'neo', 'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59', 'side': 'buy', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'offer_amount': '2000000', 'want_amount': '10000000000', 'transfer_amount': '0', 'priority_gas_amount': '0', 'use_native_token': True, 'native_fee_transfer_amount': 0, 'deposit_txn': None, 'created_at': '2018-08-05T10:38:37.714Z', 'status': 'processed', 'fills': [], 'makes': [ { 'id': 'e30a7fdf-779c-4623-8f92-8a961450d843', 'offer_hash': 'b45ddfb97ade5e0363d9e707dac9ad1c530448db263e86494225a0025006f968', 'available_amount': '2000000', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'offer_amount': '2000000', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'want_amount': '10000000000', 'filled_amount': '0.0', 'txn': None, 'cancel_txn': None, 'price': '0.0002', 'status': 'confirming', 'created_at': '2018-08-05T10:38:37.731Z', 'transaction_hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f', 'trades': [] } ] } :param pair: The trading pair this order is being submitted for. :type pair: str :param side: The side of the trade being submitted i.e. buy or sell :type side: str :param price: The price target for this trade. :type price: float :param quantity: The amount of the asset being exchanged in the trade. :type quantity: float :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :param use_native_token: Flag to indicate whether or not to pay fees with the Switcheo native token. :type use_native_token: bool :param order_type: The type of order being submitted, currently this can only be a limit order. :type order_type: str :return: Dictionary of the transaction on the order book. """ create_order = self.create_order(private_key=private_key, pair=pair, side=side, price=price, quantity=quantity, use_native_token=use_native_token, order_type=order_type) return self.execute_order(order_params=create_order, private_key=private_key)
python
def order(self, pair, side, price, quantity, private_key, use_native_token=True, order_type="limit"): """ This function is a wrapper function around the create and execute order functions to help make this processes simpler for the end user by combining these requests in 1 step. Execution of this function is as follows:: order(pair="SWTH_NEO", side="buy", price=0.0002, quantity=100, private_key=kp, use_native_token=True, order_type="limit") The expected return result for this function is the same as the execute_order function:: { 'id': '4e6a59fd-d750-4332-aaf0-f2babfa8ad67', 'blockchain': 'neo', 'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59', 'side': 'buy', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'offer_amount': '2000000', 'want_amount': '10000000000', 'transfer_amount': '0', 'priority_gas_amount': '0', 'use_native_token': True, 'native_fee_transfer_amount': 0, 'deposit_txn': None, 'created_at': '2018-08-05T10:38:37.714Z', 'status': 'processed', 'fills': [], 'makes': [ { 'id': 'e30a7fdf-779c-4623-8f92-8a961450d843', 'offer_hash': 'b45ddfb97ade5e0363d9e707dac9ad1c530448db263e86494225a0025006f968', 'available_amount': '2000000', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'offer_amount': '2000000', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'want_amount': '10000000000', 'filled_amount': '0.0', 'txn': None, 'cancel_txn': None, 'price': '0.0002', 'status': 'confirming', 'created_at': '2018-08-05T10:38:37.731Z', 'transaction_hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f', 'trades': [] } ] } :param pair: The trading pair this order is being submitted for. :type pair: str :param side: The side of the trade being submitted i.e. buy or sell :type side: str :param price: The price target for this trade. :type price: float :param quantity: The amount of the asset being exchanged in the trade. :type quantity: float :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :param use_native_token: Flag to indicate whether or not to pay fees with the Switcheo native token. :type use_native_token: bool :param order_type: The type of order being submitted, currently this can only be a limit order. :type order_type: str :return: Dictionary of the transaction on the order book. """ create_order = self.create_order(private_key=private_key, pair=pair, side=side, price=price, quantity=quantity, use_native_token=use_native_token, order_type=order_type) return self.execute_order(order_params=create_order, private_key=private_key)
[ "def", "order", "(", "self", ",", "pair", ",", "side", ",", "price", ",", "quantity", ",", "private_key", ",", "use_native_token", "=", "True", ",", "order_type", "=", "\"limit\"", ")", ":", "create_order", "=", "self", ".", "create_order", "(", "private_k...
This function is a wrapper function around the create and execute order functions to help make this processes simpler for the end user by combining these requests in 1 step. Execution of this function is as follows:: order(pair="SWTH_NEO", side="buy", price=0.0002, quantity=100, private_key=kp, use_native_token=True, order_type="limit") The expected return result for this function is the same as the execute_order function:: { 'id': '4e6a59fd-d750-4332-aaf0-f2babfa8ad67', 'blockchain': 'neo', 'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59', 'side': 'buy', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'offer_amount': '2000000', 'want_amount': '10000000000', 'transfer_amount': '0', 'priority_gas_amount': '0', 'use_native_token': True, 'native_fee_transfer_amount': 0, 'deposit_txn': None, 'created_at': '2018-08-05T10:38:37.714Z', 'status': 'processed', 'fills': [], 'makes': [ { 'id': 'e30a7fdf-779c-4623-8f92-8a961450d843', 'offer_hash': 'b45ddfb97ade5e0363d9e707dac9ad1c530448db263e86494225a0025006f968', 'available_amount': '2000000', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'offer_amount': '2000000', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'want_amount': '10000000000', 'filled_amount': '0.0', 'txn': None, 'cancel_txn': None, 'price': '0.0002', 'status': 'confirming', 'created_at': '2018-08-05T10:38:37.731Z', 'transaction_hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f', 'trades': [] } ] } :param pair: The trading pair this order is being submitted for. :type pair: str :param side: The side of the trade being submitted i.e. buy or sell :type side: str :param price: The price target for this trade. :type price: float :param quantity: The amount of the asset being exchanged in the trade. :type quantity: float :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :param use_native_token: Flag to indicate whether or not to pay fees with the Switcheo native token. :type use_native_token: bool :param order_type: The type of order being submitted, currently this can only be a limit order. :type order_type: str :return: Dictionary of the transaction on the order book.
[ "This", "function", "is", "a", "wrapper", "function", "around", "the", "create", "and", "execute", "order", "functions", "to", "help", "make", "this", "processes", "simpler", "for", "the", "end", "user", "by", "combining", "these", "requests", "in", "1", "st...
train
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/authenticated_client.py#L392-L462
KeithSSmith/switcheo-python
switcheo/authenticated_client.py
AuthenticatedClient.create_order
def create_order(self, pair, side, price, quantity, private_key, use_native_token=True, order_type="limit", otc_address=None): """ Function to create an order for the trade pair and details requested. Execution of this function is as follows:: create_order(pair="SWTH_NEO", side="buy", price=0.0002, quantity=100, private_key=kp, use_native_token=True, order_type="limit") The expected return result for this function is as follows:: { 'id': '4e6a59fd-d750-4332-aaf0-f2babfa8ad67', 'blockchain': 'neo', 'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59', 'side': 'buy', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'offer_amount': '2000000', 'want_amount': '10000000000', 'transfer_amount': '0', 'priority_gas_amount': '0', 'use_native_token': True, 'native_fee_transfer_amount': 0, 'deposit_txn': None, 'created_at': '2018-08-05T10:38:37.714Z', 'status': 'pending', 'fills': [], 'makes': [ { 'id': 'e30a7fdf-779c-4623-8f92-8a961450d843', 'offer_hash': None, 'available_amount': None, 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'offer_amount': '2000000', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'want_amount': '10000000000', 'filled_amount': None, 'txn': { 'offerHash': 'b45ddfb97ade5e0363d9e707dac9ad1c530448db263e86494225a0025006f968', 'hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f', 'sha256': 'f0b70640627947584a2976edeb055a124ae85594db76453532b893c05618e6ca', 'invoke': { 'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'operation': 'makeOffer', 'args': [ '592c8a46a0d06c600f06c994d1f25e7283b8a2fe', '9b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc5', 2000000, '32e125258b7db0a0dffde5bd03b2b859253538ab', 10000000000, '65333061376664662d373739632d343632332d386639322d386139363134353064383433' ] }, 'type': 209, 'version': 1, 'attributes': [ { 'usage': 32, 'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe' } ], 'inputs': [ { 'prevHash': '0fcfd792a9d20a7795255d1d3d3927f5968b9953e80d16ffd222656edf8fedbc', 'prevIndex': 0 }, { 'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d', 'prevIndex': 35 } ], 'outputs': [ { 'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7', 'scriptHash': 'e707714512577b42f9a011f8b870625429f93573', 'value': 1e-08 } ], 'scripts': [], 'script': '....', 'gas': 0 }, 'cancel_txn': None, 'price': '0.0002', 'status': 'pending', 'created_at': '2018-08-05T10:38:37.731Z', 'transaction_hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f', 'trades': [] } ] } :param pair: The trading pair this order is being submitted for. :type pair: str :param side: The side of the trade being submitted i.e. buy or sell :type side: str :param price: The price target for this trade. :type price: float :param quantity: The amount of the asset being exchanged in the trade. :type quantity: float :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :param use_native_token: Flag to indicate whether or not to pay fees with the Switcheo native token. :type use_native_token: bool :param order_type: The type of order being submitted, currently this can only be a limit order. :type order_type: str :param otc_address: The address to trade with for Over the Counter exchanges. :type otc_address: str :return: Dictionary of order details to specify which parts of the trade will be filled (taker) or open (maker) """ if side.lower() not in ["buy", "sell"]: raise ValueError("Allowed trade types are buy or sell, you entered {}".format(side.lower())) if order_type.lower() not in ["limit", "market", "otc"]: raise ValueError("Allowed order type is limit, you entered {}".format(order_type.lower())) if order_type.lower() == "otc" and otc_address is None: raise ValueError("OTC Address is required when trade type is otc (over the counter).") order_params = { "blockchain": self.blockchain, "pair": pair, "side": side, "price": '{:.8f}'.format(price) if order_type.lower() != "market" else None, "quantity": str(self.blockchain_amount[self.blockchain](quantity)), "use_native_tokens": use_native_token, "order_type": order_type, "timestamp": get_epoch_milliseconds(), "contract_hash": self.contract_hash } api_params = self.sign_create_order_function[self.blockchain](order_params, private_key) return self.request.post(path='/orders', json_data=api_params)
python
def create_order(self, pair, side, price, quantity, private_key, use_native_token=True, order_type="limit", otc_address=None): """ Function to create an order for the trade pair and details requested. Execution of this function is as follows:: create_order(pair="SWTH_NEO", side="buy", price=0.0002, quantity=100, private_key=kp, use_native_token=True, order_type="limit") The expected return result for this function is as follows:: { 'id': '4e6a59fd-d750-4332-aaf0-f2babfa8ad67', 'blockchain': 'neo', 'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59', 'side': 'buy', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'offer_amount': '2000000', 'want_amount': '10000000000', 'transfer_amount': '0', 'priority_gas_amount': '0', 'use_native_token': True, 'native_fee_transfer_amount': 0, 'deposit_txn': None, 'created_at': '2018-08-05T10:38:37.714Z', 'status': 'pending', 'fills': [], 'makes': [ { 'id': 'e30a7fdf-779c-4623-8f92-8a961450d843', 'offer_hash': None, 'available_amount': None, 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'offer_amount': '2000000', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'want_amount': '10000000000', 'filled_amount': None, 'txn': { 'offerHash': 'b45ddfb97ade5e0363d9e707dac9ad1c530448db263e86494225a0025006f968', 'hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f', 'sha256': 'f0b70640627947584a2976edeb055a124ae85594db76453532b893c05618e6ca', 'invoke': { 'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'operation': 'makeOffer', 'args': [ '592c8a46a0d06c600f06c994d1f25e7283b8a2fe', '9b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc5', 2000000, '32e125258b7db0a0dffde5bd03b2b859253538ab', 10000000000, '65333061376664662d373739632d343632332d386639322d386139363134353064383433' ] }, 'type': 209, 'version': 1, 'attributes': [ { 'usage': 32, 'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe' } ], 'inputs': [ { 'prevHash': '0fcfd792a9d20a7795255d1d3d3927f5968b9953e80d16ffd222656edf8fedbc', 'prevIndex': 0 }, { 'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d', 'prevIndex': 35 } ], 'outputs': [ { 'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7', 'scriptHash': 'e707714512577b42f9a011f8b870625429f93573', 'value': 1e-08 } ], 'scripts': [], 'script': '....', 'gas': 0 }, 'cancel_txn': None, 'price': '0.0002', 'status': 'pending', 'created_at': '2018-08-05T10:38:37.731Z', 'transaction_hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f', 'trades': [] } ] } :param pair: The trading pair this order is being submitted for. :type pair: str :param side: The side of the trade being submitted i.e. buy or sell :type side: str :param price: The price target for this trade. :type price: float :param quantity: The amount of the asset being exchanged in the trade. :type quantity: float :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :param use_native_token: Flag to indicate whether or not to pay fees with the Switcheo native token. :type use_native_token: bool :param order_type: The type of order being submitted, currently this can only be a limit order. :type order_type: str :param otc_address: The address to trade with for Over the Counter exchanges. :type otc_address: str :return: Dictionary of order details to specify which parts of the trade will be filled (taker) or open (maker) """ if side.lower() not in ["buy", "sell"]: raise ValueError("Allowed trade types are buy or sell, you entered {}".format(side.lower())) if order_type.lower() not in ["limit", "market", "otc"]: raise ValueError("Allowed order type is limit, you entered {}".format(order_type.lower())) if order_type.lower() == "otc" and otc_address is None: raise ValueError("OTC Address is required when trade type is otc (over the counter).") order_params = { "blockchain": self.blockchain, "pair": pair, "side": side, "price": '{:.8f}'.format(price) if order_type.lower() != "market" else None, "quantity": str(self.blockchain_amount[self.blockchain](quantity)), "use_native_tokens": use_native_token, "order_type": order_type, "timestamp": get_epoch_milliseconds(), "contract_hash": self.contract_hash } api_params = self.sign_create_order_function[self.blockchain](order_params, private_key) return self.request.post(path='/orders', json_data=api_params)
[ "def", "create_order", "(", "self", ",", "pair", ",", "side", ",", "price", ",", "quantity", ",", "private_key", ",", "use_native_token", "=", "True", ",", "order_type", "=", "\"limit\"", ",", "otc_address", "=", "None", ")", ":", "if", "side", ".", "low...
Function to create an order for the trade pair and details requested. Execution of this function is as follows:: create_order(pair="SWTH_NEO", side="buy", price=0.0002, quantity=100, private_key=kp, use_native_token=True, order_type="limit") The expected return result for this function is as follows:: { 'id': '4e6a59fd-d750-4332-aaf0-f2babfa8ad67', 'blockchain': 'neo', 'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59', 'side': 'buy', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'offer_amount': '2000000', 'want_amount': '10000000000', 'transfer_amount': '0', 'priority_gas_amount': '0', 'use_native_token': True, 'native_fee_transfer_amount': 0, 'deposit_txn': None, 'created_at': '2018-08-05T10:38:37.714Z', 'status': 'pending', 'fills': [], 'makes': [ { 'id': 'e30a7fdf-779c-4623-8f92-8a961450d843', 'offer_hash': None, 'available_amount': None, 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'offer_amount': '2000000', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'want_amount': '10000000000', 'filled_amount': None, 'txn': { 'offerHash': 'b45ddfb97ade5e0363d9e707dac9ad1c530448db263e86494225a0025006f968', 'hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f', 'sha256': 'f0b70640627947584a2976edeb055a124ae85594db76453532b893c05618e6ca', 'invoke': { 'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'operation': 'makeOffer', 'args': [ '592c8a46a0d06c600f06c994d1f25e7283b8a2fe', '9b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc5', 2000000, '32e125258b7db0a0dffde5bd03b2b859253538ab', 10000000000, '65333061376664662d373739632d343632332d386639322d386139363134353064383433' ] }, 'type': 209, 'version': 1, 'attributes': [ { 'usage': 32, 'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe' } ], 'inputs': [ { 'prevHash': '0fcfd792a9d20a7795255d1d3d3927f5968b9953e80d16ffd222656edf8fedbc', 'prevIndex': 0 }, { 'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d', 'prevIndex': 35 } ], 'outputs': [ { 'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7', 'scriptHash': 'e707714512577b42f9a011f8b870625429f93573', 'value': 1e-08 } ], 'scripts': [], 'script': '....', 'gas': 0 }, 'cancel_txn': None, 'price': '0.0002', 'status': 'pending', 'created_at': '2018-08-05T10:38:37.731Z', 'transaction_hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f', 'trades': [] } ] } :param pair: The trading pair this order is being submitted for. :type pair: str :param side: The side of the trade being submitted i.e. buy or sell :type side: str :param price: The price target for this trade. :type price: float :param quantity: The amount of the asset being exchanged in the trade. :type quantity: float :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :param use_native_token: Flag to indicate whether or not to pay fees with the Switcheo native token. :type use_native_token: bool :param order_type: The type of order being submitted, currently this can only be a limit order. :type order_type: str :param otc_address: The address to trade with for Over the Counter exchanges. :type otc_address: str :return: Dictionary of order details to specify which parts of the trade will be filled (taker) or open (maker)
[ "Function", "to", "create", "an", "order", "for", "the", "trade", "pair", "and", "details", "requested", ".", "Execution", "of", "this", "function", "is", "as", "follows", "::" ]
train
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/authenticated_client.py#L464-L593