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
sixty-north/asq
asq/queryables.py
Queryable.last_or_default
def last_or_default(self, default, predicate=None): '''The last element (optionally satisfying a predicate) or a default. If the predicate is omitted or is None this query returns the last element in the sequence; otherwise, it returns the last element in the sequence for which the predicate evaluates to True. If there is no such element the value of the default argument is returned. Note: This method uses immediate execution. Args: default: The value which will be returned if either the sequence is empty or there are no elements matching the predicate. predicate: An optional unary predicate function, the only argument to which is the element. The return value should be True for matching elements, otherwise False. If the predicate is omitted or None the last element of the source sequence will be returned. Returns: The last element of the sequence if predicate is None, otherwise the last element for which the predicate returns True. If there is no such element, the default argument is returned. Raises: ValueError: If the Queryable is closed. TypeError: If the predicate is not callable. ''' if self.closed(): raise ValueError("Attempt to call last_or_default() on a " "closed Queryable.") return self._last_or_default(default) if predicate is None else self._last_or_default_predicate(default, predicate)
python
def last_or_default(self, default, predicate=None): '''The last element (optionally satisfying a predicate) or a default. If the predicate is omitted or is None this query returns the last element in the sequence; otherwise, it returns the last element in the sequence for which the predicate evaluates to True. If there is no such element the value of the default argument is returned. Note: This method uses immediate execution. Args: default: The value which will be returned if either the sequence is empty or there are no elements matching the predicate. predicate: An optional unary predicate function, the only argument to which is the element. The return value should be True for matching elements, otherwise False. If the predicate is omitted or None the last element of the source sequence will be returned. Returns: The last element of the sequence if predicate is None, otherwise the last element for which the predicate returns True. If there is no such element, the default argument is returned. Raises: ValueError: If the Queryable is closed. TypeError: If the predicate is not callable. ''' if self.closed(): raise ValueError("Attempt to call last_or_default() on a " "closed Queryable.") return self._last_or_default(default) if predicate is None else self._last_or_default_predicate(default, predicate)
[ "def", "last_or_default", "(", "self", ",", "default", ",", "predicate", "=", "None", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call last_or_default() on a \"", "\"closed Queryable.\"", ")", "return", "self", ...
The last element (optionally satisfying a predicate) or a default. If the predicate is omitted or is None this query returns the last element in the sequence; otherwise, it returns the last element in the sequence for which the predicate evaluates to True. If there is no such element the value of the default argument is returned. Note: This method uses immediate execution. Args: default: The value which will be returned if either the sequence is empty or there are no elements matching the predicate. predicate: An optional unary predicate function, the only argument to which is the element. The return value should be True for matching elements, otherwise False. If the predicate is omitted or None the last element of the source sequence will be returned. Returns: The last element of the sequence if predicate is None, otherwise the last element for which the predicate returns True. If there is no such element, the default argument is returned. Raises: ValueError: If the Queryable is closed. TypeError: If the predicate is not callable.
[ "The", "last", "element", "(", "optionally", "satisfying", "a", "predicate", ")", "or", "a", "default", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1828-L1861
sixty-north/asq
asq/queryables.py
Queryable.aggregate
def aggregate(self, reducer, seed=default, result_selector=identity): '''Apply a function over a sequence to produce a single result. Apply a binary function cumulatively to the elements of the source sequence so as to reduce the iterable to a single value. Note: This method uses immediate execution. Args: reducer: A binary function the first positional argument of which is an accumulated value and the second is the update value from the source sequence. The return value should be the new accumulated value after the update value has been incorporated. seed: An optional value used to initialise the accumulator before iteration over the source sequence. If seed is omitted the and the source sequence contains only one item, then that item is returned. result_selector: An optional unary function applied to the final accumulator value to produce the result. If omitted, defaults to the identity function. Raises: ValueError: If called on an empty sequence with no seed value. TypeError: If reducer is not callable. TypeError: If result_selector is not callable. ''' if self.closed(): raise ValueError("Attempt to call aggregate() on a " "closed Queryable.") if not is_callable(reducer): raise TypeError("aggregate() parameter reducer={0} is " "not callable".format(repr(reducer))) if not is_callable(result_selector): raise TypeError("aggregate() parameter result_selector={0} is " "not callable".format(repr(result_selector))) if seed is default: try: return result_selector(fold(reducer, self)) except TypeError as e: if 'empty sequence' in str(e): raise ValueError("Cannot aggregate() empty sequence with " "no seed value") return result_selector(fold(reducer, self, seed))
python
def aggregate(self, reducer, seed=default, result_selector=identity): '''Apply a function over a sequence to produce a single result. Apply a binary function cumulatively to the elements of the source sequence so as to reduce the iterable to a single value. Note: This method uses immediate execution. Args: reducer: A binary function the first positional argument of which is an accumulated value and the second is the update value from the source sequence. The return value should be the new accumulated value after the update value has been incorporated. seed: An optional value used to initialise the accumulator before iteration over the source sequence. If seed is omitted the and the source sequence contains only one item, then that item is returned. result_selector: An optional unary function applied to the final accumulator value to produce the result. If omitted, defaults to the identity function. Raises: ValueError: If called on an empty sequence with no seed value. TypeError: If reducer is not callable. TypeError: If result_selector is not callable. ''' if self.closed(): raise ValueError("Attempt to call aggregate() on a " "closed Queryable.") if not is_callable(reducer): raise TypeError("aggregate() parameter reducer={0} is " "not callable".format(repr(reducer))) if not is_callable(result_selector): raise TypeError("aggregate() parameter result_selector={0} is " "not callable".format(repr(result_selector))) if seed is default: try: return result_selector(fold(reducer, self)) except TypeError as e: if 'empty sequence' in str(e): raise ValueError("Cannot aggregate() empty sequence with " "no seed value") return result_selector(fold(reducer, self, seed))
[ "def", "aggregate", "(", "self", ",", "reducer", ",", "seed", "=", "default", ",", "result_selector", "=", "identity", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call aggregate() on a \"", "\"closed Queryable....
Apply a function over a sequence to produce a single result. Apply a binary function cumulatively to the elements of the source sequence so as to reduce the iterable to a single value. Note: This method uses immediate execution. Args: reducer: A binary function the first positional argument of which is an accumulated value and the second is the update value from the source sequence. The return value should be the new accumulated value after the update value has been incorporated. seed: An optional value used to initialise the accumulator before iteration over the source sequence. If seed is omitted the and the source sequence contains only one item, then that item is returned. result_selector: An optional unary function applied to the final accumulator value to produce the result. If omitted, defaults to the identity function. Raises: ValueError: If called on an empty sequence with no seed value. TypeError: If reducer is not callable. TypeError: If result_selector is not callable.
[ "Apply", "a", "function", "over", "a", "sequence", "to", "produce", "a", "single", "result", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1904-L1951
sixty-north/asq
asq/queryables.py
Queryable.zip
def zip(self, second_iterable, result_selector=lambda x, y: (x, y)): '''Elementwise combination of two sequences. The source sequence and the second iterable are merged element-by- element using a function to combine them into the single corresponding element of the result sequence. The length of the result sequence is equal to the length of the shorter of the two input sequences. Note: This method uses deferred execution. Args: second_iterable: The second sequence to be combined with the source sequence. result_selector: An optional binary function for combining corresponding elements of the source sequences into an element of the result sequence. The first and second positional arguments are the elements from the source sequences. The result should be the result sequence element. If omitted, the result sequence will consist of 2-tuple pairs of corresponding elements from the source sequences. Returns: A Queryable over the merged elements. Raises: ValueError: If the Queryable is closed. TypeError: If result_selector is not callable. ''' if self.closed(): raise ValueError("Attempt to call zip() on a closed Queryable.") if not is_iterable(second_iterable): raise TypeError("Cannot compute zip() with second_iterable of " "non-iterable {0}".format(str(type(second_iterable))[7: -1])) if not is_callable(result_selector): raise TypeError("zip() parameter result_selector={0} is " "not callable".format(repr(result_selector))) return self._create(result_selector(*t) for t in izip(self, second_iterable))
python
def zip(self, second_iterable, result_selector=lambda x, y: (x, y)): '''Elementwise combination of two sequences. The source sequence and the second iterable are merged element-by- element using a function to combine them into the single corresponding element of the result sequence. The length of the result sequence is equal to the length of the shorter of the two input sequences. Note: This method uses deferred execution. Args: second_iterable: The second sequence to be combined with the source sequence. result_selector: An optional binary function for combining corresponding elements of the source sequences into an element of the result sequence. The first and second positional arguments are the elements from the source sequences. The result should be the result sequence element. If omitted, the result sequence will consist of 2-tuple pairs of corresponding elements from the source sequences. Returns: A Queryable over the merged elements. Raises: ValueError: If the Queryable is closed. TypeError: If result_selector is not callable. ''' if self.closed(): raise ValueError("Attempt to call zip() on a closed Queryable.") if not is_iterable(second_iterable): raise TypeError("Cannot compute zip() with second_iterable of " "non-iterable {0}".format(str(type(second_iterable))[7: -1])) if not is_callable(result_selector): raise TypeError("zip() parameter result_selector={0} is " "not callable".format(repr(result_selector))) return self._create(result_selector(*t) for t in izip(self, second_iterable))
[ "def", "zip", "(", "self", ",", "second_iterable", ",", "result_selector", "=", "lambda", "x", ",", "y", ":", "(", "x", ",", "y", ")", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call zip() on a closed ...
Elementwise combination of two sequences. The source sequence and the second iterable are merged element-by- element using a function to combine them into the single corresponding element of the result sequence. The length of the result sequence is equal to the length of the shorter of the two input sequences. Note: This method uses deferred execution. Args: second_iterable: The second sequence to be combined with the source sequence. result_selector: An optional binary function for combining corresponding elements of the source sequences into an element of the result sequence. The first and second positional arguments are the elements from the source sequences. The result should be the result sequence element. If omitted, the result sequence will consist of 2-tuple pairs of corresponding elements from the source sequences. Returns: A Queryable over the merged elements. Raises: ValueError: If the Queryable is closed. TypeError: If result_selector is not callable.
[ "Elementwise", "combination", "of", "two", "sequences", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1953-L1993
sixty-north/asq
asq/queryables.py
Queryable.to_list
def to_list(self): '''Convert the source sequence to a list. Note: This method uses immediate execution. ''' if self.closed(): raise ValueError("Attempt to call to_list() on a closed Queryable.") # Maybe use with closable(self) construct to achieve this. if isinstance(self._iterable, list): return self._iterable lst = list(self) # Ideally we would close here. Why can't we - what is the problem? #self.close() return lst
python
def to_list(self): '''Convert the source sequence to a list. Note: This method uses immediate execution. ''' if self.closed(): raise ValueError("Attempt to call to_list() on a closed Queryable.") # Maybe use with closable(self) construct to achieve this. if isinstance(self._iterable, list): return self._iterable lst = list(self) # Ideally we would close here. Why can't we - what is the problem? #self.close() return lst
[ "def", "to_list", "(", "self", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call to_list() on a closed Queryable.\"", ")", "# Maybe use with closable(self) construct to achieve this.", "if", "isinstance", "(", "self", "...
Convert the source sequence to a list. Note: This method uses immediate execution.
[ "Convert", "the", "source", "sequence", "to", "a", "list", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1995-L2009
sixty-north/asq
asq/queryables.py
Queryable.to_tuple
def to_tuple(self): '''Convert the source sequence to a tuple. Note: This method uses immediate execution. ''' if self.closed(): raise ValueError("Attempt to call to_tuple() on a closed Queryable.") if isinstance(self._iterable, tuple): return self._iterable tup = tuple(self) # Ideally we would close here #self.close() return tup
python
def to_tuple(self): '''Convert the source sequence to a tuple. Note: This method uses immediate execution. ''' if self.closed(): raise ValueError("Attempt to call to_tuple() on a closed Queryable.") if isinstance(self._iterable, tuple): return self._iterable tup = tuple(self) # Ideally we would close here #self.close() return tup
[ "def", "to_tuple", "(", "self", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call to_tuple() on a closed Queryable.\"", ")", "if", "isinstance", "(", "self", ".", "_iterable", ",", "tuple", ")", ":", "return",...
Convert the source sequence to a tuple. Note: This method uses immediate execution.
[ "Convert", "the", "source", "sequence", "to", "a", "tuple", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2011-L2024
sixty-north/asq
asq/queryables.py
Queryable.to_set
def to_set(self): '''Convert the source sequence to a set. Note: This method uses immediate execution. Raises: ValueError: If duplicate keys are in the projected source sequence. ValueError: If the Queryable is closed(). ''' if self.closed(): raise ValueError("Attempt to call to_set() on a closed Queryable.") if isinstance(self._iterable, set): return self._iterable s = set() for item in self: if item in s: raise ValueError("Duplicate item value {0} in sequence " "during to_set()".format(repr(item))) s.add(item) # Ideally we would close here #self.close() return s
python
def to_set(self): '''Convert the source sequence to a set. Note: This method uses immediate execution. Raises: ValueError: If duplicate keys are in the projected source sequence. ValueError: If the Queryable is closed(). ''' if self.closed(): raise ValueError("Attempt to call to_set() on a closed Queryable.") if isinstance(self._iterable, set): return self._iterable s = set() for item in self: if item in s: raise ValueError("Duplicate item value {0} in sequence " "during to_set()".format(repr(item))) s.add(item) # Ideally we would close here #self.close() return s
[ "def", "to_set", "(", "self", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call to_set() on a closed Queryable.\"", ")", "if", "isinstance", "(", "self", ".", "_iterable", ",", "set", ")", ":", "return", "se...
Convert the source sequence to a set. Note: This method uses immediate execution. Raises: ValueError: If duplicate keys are in the projected source sequence. ValueError: If the Queryable is closed().
[ "Convert", "the", "source", "sequence", "to", "a", "set", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2026-L2048
sixty-north/asq
asq/queryables.py
Queryable.to_lookup
def to_lookup(self, key_selector=identity, value_selector=identity): '''Returns a Lookup object, using the provided selector to generate a key for each item. Note: This method uses immediate execution. ''' if self.closed(): raise ValueError("Attempt to call to_lookup() on a closed Queryable.") if not is_callable(key_selector): raise TypeError("to_lookup() parameter key_selector={key_selector} is not callable".format( key_selector=repr(key_selector))) if not is_callable(value_selector): raise TypeError("to_lookup() parameter value_selector={value_selector} is not callable".format( value_selector=repr(value_selector))) key_value_pairs = self.select(lambda item: (key_selector(item), value_selector(item))) lookup = Lookup(key_value_pairs) # Ideally we would close here #self.close() return lookup
python
def to_lookup(self, key_selector=identity, value_selector=identity): '''Returns a Lookup object, using the provided selector to generate a key for each item. Note: This method uses immediate execution. ''' if self.closed(): raise ValueError("Attempt to call to_lookup() on a closed Queryable.") if not is_callable(key_selector): raise TypeError("to_lookup() parameter key_selector={key_selector} is not callable".format( key_selector=repr(key_selector))) if not is_callable(value_selector): raise TypeError("to_lookup() parameter value_selector={value_selector} is not callable".format( value_selector=repr(value_selector))) key_value_pairs = self.select(lambda item: (key_selector(item), value_selector(item))) lookup = Lookup(key_value_pairs) # Ideally we would close here #self.close() return lookup
[ "def", "to_lookup", "(", "self", ",", "key_selector", "=", "identity", ",", "value_selector", "=", "identity", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call to_lookup() on a closed Queryable.\"", ")", "if", ...
Returns a Lookup object, using the provided selector to generate a key for each item. Note: This method uses immediate execution.
[ "Returns", "a", "Lookup", "object", "using", "the", "provided", "selector", "to", "generate", "a", "key", "for", "each", "item", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2050-L2071
sixty-north/asq
asq/queryables.py
Queryable.to_dictionary
def to_dictionary(self, key_selector=identity, value_selector=identity): """Build a dictionary from the source sequence. Args: key_selector: A unary callable to extract a key from each item. By default the key is the item itself. value_selector: A unary callable to extract a value from each item. By default the value is the item itself. Note: This method uses immediate execution. Raises: ValueError: If the Queryable is closed. TypeError: If key_selector is not callable. TypeError: If value_selector is not callable. """ if self.closed(): raise ValueError("Attempt to call to_dictionary() on a closed Queryable.") if not is_callable(key_selector): raise TypeError("to_dictionary() parameter key_selector={key_selector} is not callable".format( key_selector=repr(key_selector))) if not is_callable(value_selector): raise TypeError("to_dictionary() parameter value_selector={value_selector} is not callable".format( value_selector=repr(value_selector))) dictionary = {} for key, value in self.select(lambda x: (key_selector(x), value_selector(x))): dictionary[key] = value return dictionary
python
def to_dictionary(self, key_selector=identity, value_selector=identity): """Build a dictionary from the source sequence. Args: key_selector: A unary callable to extract a key from each item. By default the key is the item itself. value_selector: A unary callable to extract a value from each item. By default the value is the item itself. Note: This method uses immediate execution. Raises: ValueError: If the Queryable is closed. TypeError: If key_selector is not callable. TypeError: If value_selector is not callable. """ if self.closed(): raise ValueError("Attempt to call to_dictionary() on a closed Queryable.") if not is_callable(key_selector): raise TypeError("to_dictionary() parameter key_selector={key_selector} is not callable".format( key_selector=repr(key_selector))) if not is_callable(value_selector): raise TypeError("to_dictionary() parameter value_selector={value_selector} is not callable".format( value_selector=repr(value_selector))) dictionary = {} for key, value in self.select(lambda x: (key_selector(x), value_selector(x))): dictionary[key] = value return dictionary
[ "def", "to_dictionary", "(", "self", ",", "key_selector", "=", "identity", ",", "value_selector", "=", "identity", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call to_dictionary() on a closed Queryable.\"", ")", ...
Build a dictionary from the source sequence. Args: key_selector: A unary callable to extract a key from each item. By default the key is the item itself. value_selector: A unary callable to extract a value from each item. By default the value is the item itself. Note: This method uses immediate execution. Raises: ValueError: If the Queryable is closed. TypeError: If key_selector is not callable. TypeError: If value_selector is not callable.
[ "Build", "a", "dictionary", "from", "the", "source", "sequence", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2073-L2104
sixty-north/asq
asq/queryables.py
Queryable.to_str
def to_str(self, separator=''): '''Build a string from the source sequence. The elements of the query result will each coerced to a string and then the resulting strings concatenated to return a single string. This allows the natural processing of character sequences as strings. An optional separator which will be inserted between each item may be specified. Note: this method uses immediate execution. Args: separator: An optional separator which will be coerced to a string and inserted between each source item in the resulting string. Returns: A single string which is the result of stringifying each element and concatenating the results into a single string. Raises: TypeError: If any element cannot be coerced to a string. TypeError: If the separator cannot be coerced to a string. ValueError: If the Queryable is closed. ''' if self.closed(): raise ValueError("Attempt to call to_str() on a closed Queryable.") return str(separator).join(self.select(str))
python
def to_str(self, separator=''): '''Build a string from the source sequence. The elements of the query result will each coerced to a string and then the resulting strings concatenated to return a single string. This allows the natural processing of character sequences as strings. An optional separator which will be inserted between each item may be specified. Note: this method uses immediate execution. Args: separator: An optional separator which will be coerced to a string and inserted between each source item in the resulting string. Returns: A single string which is the result of stringifying each element and concatenating the results into a single string. Raises: TypeError: If any element cannot be coerced to a string. TypeError: If the separator cannot be coerced to a string. ValueError: If the Queryable is closed. ''' if self.closed(): raise ValueError("Attempt to call to_str() on a closed Queryable.") return str(separator).join(self.select(str))
[ "def", "to_str", "(", "self", ",", "separator", "=", "''", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call to_str() on a closed Queryable.\"", ")", "return", "str", "(", "separator", ")", ".", "join", "(",...
Build a string from the source sequence. The elements of the query result will each coerced to a string and then the resulting strings concatenated to return a single string. This allows the natural processing of character sequences as strings. An optional separator which will be inserted between each item may be specified. Note: this method uses immediate execution. Args: separator: An optional separator which will be coerced to a string and inserted between each source item in the resulting string. Returns: A single string which is the result of stringifying each element and concatenating the results into a single string. Raises: TypeError: If any element cannot be coerced to a string. TypeError: If the separator cannot be coerced to a string. ValueError: If the Queryable is closed.
[ "Build", "a", "string", "from", "the", "source", "sequence", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2106-L2133
sixty-north/asq
asq/queryables.py
Queryable.sequence_equal
def sequence_equal(self, second_iterable, equality_comparer=operator.eq): ''' Determine whether two sequences are equal by elementwise comparison. Sequence equality is defined as the two sequences being equal length and corresponding elements being equal as determined by the equality comparer. Note: This method uses immediate execution. Args: second_iterable: The sequence which will be compared with the source sequence. equality_comparer: An optional binary predicate function which is used to compare corresponding elements. Should return True if the elements are equal, otherwise False. The default equality comparer is operator.eq which calls __eq__ on elements of the source sequence with the corresponding element of the second sequence as a parameter. Returns: True if the sequences are equal, otherwise False. Raises: ValueError: If the Queryable is closed. TypeError: If second_iterable is not in fact iterable. TypeError: If equality_comparer is not callable. ''' if self.closed(): raise ValueError("Attempt to call to_tuple() on a closed Queryable.") if not is_iterable(second_iterable): raise TypeError("Cannot compute sequence_equal() with second_iterable of non-iterable {type}".format( type=str(type(second_iterable))[7: -1])) if not is_callable(equality_comparer): raise TypeError("aggregate() parameter equality_comparer={equality_comparer} is not callable".format( equality_comparer=repr(equality_comparer))) # Try to check the lengths directly as an optimization try: if len(self._iterable) != len(second_iterable): return False except TypeError: pass sentinel = object() for first, second in izip_longest(self, second_iterable, fillvalue=sentinel): if first is sentinel or second is sentinel: return False if not equality_comparer(first, second): return False return True
python
def sequence_equal(self, second_iterable, equality_comparer=operator.eq): ''' Determine whether two sequences are equal by elementwise comparison. Sequence equality is defined as the two sequences being equal length and corresponding elements being equal as determined by the equality comparer. Note: This method uses immediate execution. Args: second_iterable: The sequence which will be compared with the source sequence. equality_comparer: An optional binary predicate function which is used to compare corresponding elements. Should return True if the elements are equal, otherwise False. The default equality comparer is operator.eq which calls __eq__ on elements of the source sequence with the corresponding element of the second sequence as a parameter. Returns: True if the sequences are equal, otherwise False. Raises: ValueError: If the Queryable is closed. TypeError: If second_iterable is not in fact iterable. TypeError: If equality_comparer is not callable. ''' if self.closed(): raise ValueError("Attempt to call to_tuple() on a closed Queryable.") if not is_iterable(second_iterable): raise TypeError("Cannot compute sequence_equal() with second_iterable of non-iterable {type}".format( type=str(type(second_iterable))[7: -1])) if not is_callable(equality_comparer): raise TypeError("aggregate() parameter equality_comparer={equality_comparer} is not callable".format( equality_comparer=repr(equality_comparer))) # Try to check the lengths directly as an optimization try: if len(self._iterable) != len(second_iterable): return False except TypeError: pass sentinel = object() for first, second in izip_longest(self, second_iterable, fillvalue=sentinel): if first is sentinel or second is sentinel: return False if not equality_comparer(first, second): return False return True
[ "def", "sequence_equal", "(", "self", ",", "second_iterable", ",", "equality_comparer", "=", "operator", ".", "eq", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call to_tuple() on a closed Queryable.\"", ")", "if"...
Determine whether two sequences are equal by elementwise comparison. Sequence equality is defined as the two sequences being equal length and corresponding elements being equal as determined by the equality comparer. Note: This method uses immediate execution. Args: second_iterable: The sequence which will be compared with the source sequence. equality_comparer: An optional binary predicate function which is used to compare corresponding elements. Should return True if the elements are equal, otherwise False. The default equality comparer is operator.eq which calls __eq__ on elements of the source sequence with the corresponding element of the second sequence as a parameter. Returns: True if the sequences are equal, otherwise False. Raises: ValueError: If the Queryable is closed. TypeError: If second_iterable is not in fact iterable. TypeError: If equality_comparer is not callable.
[ "Determine", "whether", "two", "sequences", "are", "equal", "by", "elementwise", "comparison", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2135-L2189
sixty-north/asq
asq/queryables.py
Queryable.log
def log(self, logger=None, label=None, eager=False): ''' Log query result consumption details to a logger. Args: logger: Any object which supports a debug() method which accepts a str, such as a Python standard library logger object from the logging module. If logger is not provided or is None, this method has no logging side effects. label: An optional label which will be inserted into each line of logging output produced by this particular use of log eager: An optional boolean which controls how the query result will be consumed. If True, the sequence will be consumed and logged in its entirety. If False (the default) the sequence will be evaluated and logged lazily as it consumed. Warning: Use of eager=True requires use of sufficient memory to hold the entire sequence which is obviously not possible with infinite sequences. Use with care! Returns: A queryable over the unaltered source sequence. Raises: AttributeError: If logger does not support a debug() method. ValueError: If the Queryable has been closed. ''' if self.closed(): raise ValueError("Attempt to call log() on a closed Queryable.") if logger is None: return self if label is None: label = repr(self) if eager: return self._create(self._eager_log_result(logger, label)) return self._create(self._generate_lazy_log_result(logger, label))
python
def log(self, logger=None, label=None, eager=False): ''' Log query result consumption details to a logger. Args: logger: Any object which supports a debug() method which accepts a str, such as a Python standard library logger object from the logging module. If logger is not provided or is None, this method has no logging side effects. label: An optional label which will be inserted into each line of logging output produced by this particular use of log eager: An optional boolean which controls how the query result will be consumed. If True, the sequence will be consumed and logged in its entirety. If False (the default) the sequence will be evaluated and logged lazily as it consumed. Warning: Use of eager=True requires use of sufficient memory to hold the entire sequence which is obviously not possible with infinite sequences. Use with care! Returns: A queryable over the unaltered source sequence. Raises: AttributeError: If logger does not support a debug() method. ValueError: If the Queryable has been closed. ''' if self.closed(): raise ValueError("Attempt to call log() on a closed Queryable.") if logger is None: return self if label is None: label = repr(self) if eager: return self._create(self._eager_log_result(logger, label)) return self._create(self._generate_lazy_log_result(logger, label))
[ "def", "log", "(", "self", ",", "logger", "=", "None", ",", "label", "=", "None", ",", "eager", "=", "False", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call log() on a closed Queryable.\"", ")", "if", ...
Log query result consumption details to a logger. Args: logger: Any object which supports a debug() method which accepts a str, such as a Python standard library logger object from the logging module. If logger is not provided or is None, this method has no logging side effects. label: An optional label which will be inserted into each line of logging output produced by this particular use of log eager: An optional boolean which controls how the query result will be consumed. If True, the sequence will be consumed and logged in its entirety. If False (the default) the sequence will be evaluated and logged lazily as it consumed. Warning: Use of eager=True requires use of sufficient memory to hold the entire sequence which is obviously not possible with infinite sequences. Use with care! Returns: A queryable over the unaltered source sequence. Raises: AttributeError: If logger does not support a debug() method. ValueError: If the Queryable has been closed.
[ "Log", "query", "result", "consumption", "details", "to", "a", "logger", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2213-L2254
sixty-north/asq
asq/queryables.py
Queryable.scan
def scan(self, func=operator.add): ''' An inclusive prefix sum which returns the cumulative application of the supplied function up to an including the current element. Args: func: An optional binary function which is commutative - that is, the order of the arguments is unimportant. Defaults to a summing operator. Returns: A Queryable such that the nth element is the sum of the first n elements of the source sequence. Raises: ValueError: If the Queryable has been closed. TypeError: If func is not callable. ''' if self.closed(): raise ValueError("Attempt to call scan() on a " "closed Queryable.") if not is_callable(func): raise TypeError("scan() parameter func={0} is " "not callable".format(repr(func))) return self._create(self._generate_scan_result(func))
python
def scan(self, func=operator.add): ''' An inclusive prefix sum which returns the cumulative application of the supplied function up to an including the current element. Args: func: An optional binary function which is commutative - that is, the order of the arguments is unimportant. Defaults to a summing operator. Returns: A Queryable such that the nth element is the sum of the first n elements of the source sequence. Raises: ValueError: If the Queryable has been closed. TypeError: If func is not callable. ''' if self.closed(): raise ValueError("Attempt to call scan() on a " "closed Queryable.") if not is_callable(func): raise TypeError("scan() parameter func={0} is " "not callable".format(repr(func))) return self._create(self._generate_scan_result(func))
[ "def", "scan", "(", "self", ",", "func", "=", "operator", ".", "add", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call scan() on a \"", "\"closed Queryable.\"", ")", "if", "not", "is_callable", "(", "func",...
An inclusive prefix sum which returns the cumulative application of the supplied function up to an including the current element. Args: func: An optional binary function which is commutative - that is, the order of the arguments is unimportant. Defaults to a summing operator. Returns: A Queryable such that the nth element is the sum of the first n elements of the source sequence. Raises: ValueError: If the Queryable has been closed. TypeError: If func is not callable.
[ "An", "inclusive", "prefix", "sum", "which", "returns", "the", "cumulative", "application", "of", "the", "supplied", "function", "up", "to", "an", "including", "the", "current", "element", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2295-L2321
sixty-north/asq
asq/queryables.py
Queryable.pre_scan
def pre_scan(self, func=operator.add, seed=0): ''' An exclusive prefix sum which returns the cumulative application of the supplied function up to but excluding the current element. Args: func: An optional binary function which is commutative - that is, the order of the arguments is unimportant. Defaults to a summing operator. seed: The first element of the prefix sum and therefore also the first element of the returned sequence. Returns: A Queryable such that the nth element is the sum of the first n-1 elements of the source sequence. Raises: ValueError: If the Queryable has been closed. TypeError: If func is not callable. ''' if self.closed(): raise ValueError("Attempt to call pre_scan() on a " "closed Queryable.") if not is_callable(func): raise TypeError("pre_scan() parameter func={0} is " "not callable".format(repr(func))) return self._create(self._generate_pre_scan_result(func, seed))
python
def pre_scan(self, func=operator.add, seed=0): ''' An exclusive prefix sum which returns the cumulative application of the supplied function up to but excluding the current element. Args: func: An optional binary function which is commutative - that is, the order of the arguments is unimportant. Defaults to a summing operator. seed: The first element of the prefix sum and therefore also the first element of the returned sequence. Returns: A Queryable such that the nth element is the sum of the first n-1 elements of the source sequence. Raises: ValueError: If the Queryable has been closed. TypeError: If func is not callable. ''' if self.closed(): raise ValueError("Attempt to call pre_scan() on a " "closed Queryable.") if not is_callable(func): raise TypeError("pre_scan() parameter func={0} is " "not callable".format(repr(func))) return self._create(self._generate_pre_scan_result(func, seed))
[ "def", "pre_scan", "(", "self", ",", "func", "=", "operator", ".", "add", ",", "seed", "=", "0", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call pre_scan() on a \"", "\"closed Queryable.\"", ")", "if", "...
An exclusive prefix sum which returns the cumulative application of the supplied function up to but excluding the current element. Args: func: An optional binary function which is commutative - that is, the order of the arguments is unimportant. Defaults to a summing operator. seed: The first element of the prefix sum and therefore also the first element of the returned sequence. Returns: A Queryable such that the nth element is the sum of the first n-1 elements of the source sequence. Raises: ValueError: If the Queryable has been closed. TypeError: If func is not callable.
[ "An", "exclusive", "prefix", "sum", "which", "returns", "the", "cumulative", "application", "of", "the", "supplied", "function", "up", "to", "but", "excluding", "the", "current", "element", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2337-L2366
sixty-north/asq
asq/queryables.py
OrderedQueryable.then_by
def then_by(self, key_selector=identity): '''Introduce subsequent ordering to the sequence with an optional key. The returned sequence will be sorted in ascending order by the selected key. Note: This method uses deferred execution. Args: key_selector: A unary function the only positional argument to which is the element value from which the key will be selected. The return value should be the key from that element. Returns: An OrderedQueryable over the sorted items. Raises: ValueError: If the OrderedQueryable is closed(). TypeError: If key_selector is not callable. ''' if self.closed(): raise ValueError("Attempt to call then_by() on a " "closed OrderedQueryable.") if not is_callable(key_selector): raise TypeError("then_by() parameter key_selector={key_selector} " "is not callable".format(key_selector=repr(key_selector))) self._funcs.append((-1, key_selector)) return self
python
def then_by(self, key_selector=identity): '''Introduce subsequent ordering to the sequence with an optional key. The returned sequence will be sorted in ascending order by the selected key. Note: This method uses deferred execution. Args: key_selector: A unary function the only positional argument to which is the element value from which the key will be selected. The return value should be the key from that element. Returns: An OrderedQueryable over the sorted items. Raises: ValueError: If the OrderedQueryable is closed(). TypeError: If key_selector is not callable. ''' if self.closed(): raise ValueError("Attempt to call then_by() on a " "closed OrderedQueryable.") if not is_callable(key_selector): raise TypeError("then_by() parameter key_selector={key_selector} " "is not callable".format(key_selector=repr(key_selector))) self._funcs.append((-1, key_selector)) return self
[ "def", "then_by", "(", "self", ",", "key_selector", "=", "identity", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call then_by() on a \"", "\"closed OrderedQueryable.\"", ")", "if", "not", "is_callable", "(", "k...
Introduce subsequent ordering to the sequence with an optional key. The returned sequence will be sorted in ascending order by the selected key. Note: This method uses deferred execution. Args: key_selector: A unary function the only positional argument to which is the element value from which the key will be selected. The return value should be the key from that element. Returns: An OrderedQueryable over the sorted items. Raises: ValueError: If the OrderedQueryable is closed(). TypeError: If key_selector is not callable.
[ "Introduce", "subsequent", "ordering", "to", "the", "sequence", "with", "an", "optional", "key", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2526-L2556
sixty-north/asq
asq/queryables.py
Lookup.to_dictionary
def to_dictionary( self, key_selector=lambda item: item.key, value_selector=list): """Build a dictionary from the source sequence. Args: key_selector: A unary callable to extract a key from each item. By default the key of the Grouping. value_selector: A unary callable to extract a value from each item. By default the value is the list of items from the Grouping. Note: This method uses immediate execution. Raises: ValueError: If the Queryable is closed. TypeError: If key_selector is not callable. TypeError: If value_selector is not callable. """ return super(Lookup, self).to_dictionary(key_selector, value_selector)
python
def to_dictionary( self, key_selector=lambda item: item.key, value_selector=list): """Build a dictionary from the source sequence. Args: key_selector: A unary callable to extract a key from each item. By default the key of the Grouping. value_selector: A unary callable to extract a value from each item. By default the value is the list of items from the Grouping. Note: This method uses immediate execution. Raises: ValueError: If the Queryable is closed. TypeError: If key_selector is not callable. TypeError: If value_selector is not callable. """ return super(Lookup, self).to_dictionary(key_selector, value_selector)
[ "def", "to_dictionary", "(", "self", ",", "key_selector", "=", "lambda", "item", ":", "item", ".", "key", ",", "value_selector", "=", "list", ")", ":", "return", "super", "(", "Lookup", ",", "self", ")", ".", "to_dictionary", "(", "key_selector", ",", "v...
Build a dictionary from the source sequence. Args: key_selector: A unary callable to extract a key from each item. By default the key of the Grouping. value_selector: A unary callable to extract a value from each item. By default the value is the list of items from the Grouping. Note: This method uses immediate execution. Raises: ValueError: If the Queryable is closed. TypeError: If key_selector is not callable. TypeError: If value_selector is not callable.
[ "Build", "a", "dictionary", "from", "the", "source", "sequence", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2739-L2759
sixty-north/asq
asq/queryables.py
Grouping.to_dictionary
def to_dictionary( self, key_selector=None, value_selector=None): """Build a dictionary from the source sequence. Args: key_selector: A unary callable to extract a key from each item or None. If None, the default key selector produces a single dictionary key, which if the key of this Grouping. value_selector: A unary callable to extract a value from each item. If None, the default value selector produces a list, which contains all elements from this Grouping. Note: This method uses immediate execution. Raises: ValueError: If the Queryable is closed. TypeError: If key_selector is not callable. TypeError: If value_selector is not callable. """ if key_selector is None: key_selector = lambda _: self.key if value_selector is None: value_selector = lambda _: self.to_list() return super(Grouping, self).to_dictionary(key_selector, value_selector)
python
def to_dictionary( self, key_selector=None, value_selector=None): """Build a dictionary from the source sequence. Args: key_selector: A unary callable to extract a key from each item or None. If None, the default key selector produces a single dictionary key, which if the key of this Grouping. value_selector: A unary callable to extract a value from each item. If None, the default value selector produces a list, which contains all elements from this Grouping. Note: This method uses immediate execution. Raises: ValueError: If the Queryable is closed. TypeError: If key_selector is not callable. TypeError: If value_selector is not callable. """ if key_selector is None: key_selector = lambda _: self.key if value_selector is None: value_selector = lambda _: self.to_list() return super(Grouping, self).to_dictionary(key_selector, value_selector)
[ "def", "to_dictionary", "(", "self", ",", "key_selector", "=", "None", ",", "value_selector", "=", "None", ")", ":", "if", "key_selector", "is", "None", ":", "key_selector", "=", "lambda", "_", ":", "self", ".", "key", "if", "value_selector", "is", "None",...
Build a dictionary from the source sequence. Args: key_selector: A unary callable to extract a key from each item or None. If None, the default key selector produces a single dictionary key, which if the key of this Grouping. value_selector: A unary callable to extract a value from each item. If None, the default value selector produces a list, which contains all elements from this Grouping. Note: This method uses immediate execution. Raises: ValueError: If the Queryable is closed. TypeError: If key_selector is not callable. TypeError: If value_selector is not callable.
[ "Build", "a", "dictionary", "from", "the", "source", "sequence", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2818-L2846
sixty-north/asq
asq/initiators.py
integers
def integers(start, count): '''Generates in sequence the integral numbers within a range. Note: This method uses deferred execution. Args: start: The first integer in the sequence. count: The number of sequential integers to generate. Returns: A Queryable over the specified range of integers. Raises: ValueError: If count is negative. ''' if count < 0: raise ValueError("integers() count cannot be negative") return query(irange(start, start + count))
python
def integers(start, count): '''Generates in sequence the integral numbers within a range. Note: This method uses deferred execution. Args: start: The first integer in the sequence. count: The number of sequential integers to generate. Returns: A Queryable over the specified range of integers. Raises: ValueError: If count is negative. ''' if count < 0: raise ValueError("integers() count cannot be negative") return query(irange(start, start + count))
[ "def", "integers", "(", "start", ",", "count", ")", ":", "if", "count", "<", "0", ":", "raise", "ValueError", "(", "\"integers() count cannot be negative\"", ")", "return", "query", "(", "irange", "(", "start", ",", "start", "+", "count", ")", ")" ]
Generates in sequence the integral numbers within a range. Note: This method uses deferred execution. Args: start: The first integer in the sequence. count: The number of sequential integers to generate. Returns: A Queryable over the specified range of integers. Raises: ValueError: If count is negative.
[ "Generates", "in", "sequence", "the", "integral", "numbers", "within", "a", "range", ".", "Note", ":", "This", "method", "uses", "deferred", "execution", ".", "Args", ":", "start", ":", "The", "first", "integer", "in", "the", "sequence", ".", "count", ":",...
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/initiators.py#L34-L51
sixty-north/asq
asq/initiators.py
repeat
def repeat(element, count): '''Generate a sequence with one repeated value. Note: This method uses deferred execution. Args: element: The value to be repeated. count: The number of times to repeat the value. Raises: ValueError: If the count is negative. ''' if count < 0: raise ValueError("repeat() count cannot be negative") return query(itertools.repeat(element, count))
python
def repeat(element, count): '''Generate a sequence with one repeated value. Note: This method uses deferred execution. Args: element: The value to be repeated. count: The number of times to repeat the value. Raises: ValueError: If the count is negative. ''' if count < 0: raise ValueError("repeat() count cannot be negative") return query(itertools.repeat(element, count))
[ "def", "repeat", "(", "element", ",", "count", ")", ":", "if", "count", "<", "0", ":", "raise", "ValueError", "(", "\"repeat() count cannot be negative\"", ")", "return", "query", "(", "itertools", ".", "repeat", "(", "element", ",", "count", ")", ")" ]
Generate a sequence with one repeated value. Note: This method uses deferred execution. Args: element: The value to be repeated. count: The number of times to repeat the value. Raises: ValueError: If the count is negative.
[ "Generate", "a", "sequence", "with", "one", "repeated", "value", ".", "Note", ":", "This", "method", "uses", "deferred", "execution", ".", "Args", ":", "element", ":", "The", "value", "to", "be", "repeated", ".", "count", ":", "The", "number", "of", "tim...
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/initiators.py#L54-L68
sixty-north/asq
asq/parallel_queryable.py
geometric_partitions
def geometric_partitions(iterable, floor=1, ceiling=32768): ''' Partition an iterable into chunks. Returns an iterator over partitions. ''' partition_size = floor run_length = multiprocessing.cpu_count() run_count = 0 try: while True: #print("partition_size =", partition_size) # Split the iterable and replace the original iterator to avoid # advancing it partition, iterable = itertools.tee(iterable) # Yield the first partition, limited to the partition size yield Queryable(partition).take(partition_size) # Advance to the start of the next partition, this will raise # StopIteration if the iterator is exhausted for i in range(partition_size): next(iterable) # If we've reached the end of a run of this size, double the # partition size run_count += 1 if run_count >= run_length: partition_size *= 2 run_count = 0 # Unless we have hit the ceiling if partition_size > ceiling: partition_size = ceiling except StopIteration: pass
python
def geometric_partitions(iterable, floor=1, ceiling=32768): ''' Partition an iterable into chunks. Returns an iterator over partitions. ''' partition_size = floor run_length = multiprocessing.cpu_count() run_count = 0 try: while True: #print("partition_size =", partition_size) # Split the iterable and replace the original iterator to avoid # advancing it partition, iterable = itertools.tee(iterable) # Yield the first partition, limited to the partition size yield Queryable(partition).take(partition_size) # Advance to the start of the next partition, this will raise # StopIteration if the iterator is exhausted for i in range(partition_size): next(iterable) # If we've reached the end of a run of this size, double the # partition size run_count += 1 if run_count >= run_length: partition_size *= 2 run_count = 0 # Unless we have hit the ceiling if partition_size > ceiling: partition_size = ceiling except StopIteration: pass
[ "def", "geometric_partitions", "(", "iterable", ",", "floor", "=", "1", ",", "ceiling", "=", "32768", ")", ":", "partition_size", "=", "floor", "run_length", "=", "multiprocessing", ".", "cpu_count", "(", ")", "run_count", "=", "0", "try", ":", "while", "T...
Partition an iterable into chunks. Returns an iterator over partitions.
[ "Partition", "an", "iterable", "into", "chunks", ".", "Returns", "an", "iterator", "over", "partitions", "." ]
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/parallel_queryable.py#L268-L303
sixty-north/asq
asq/parallel_queryable.py
ParallelQueryable.select
def select(self, selector): '''Transforms each element of a sequence into a new form. Each element is transformed through a selector function to produce a value for each value in the source sequence. The generated sequence is lazily evaluated. Args: selector: A unary function mapping a value in the source sequence to the corresponding value in the generated generated sequence. The argument of the selector function (which can have any name) is, Args: element: The value of the element Returns: The selected value derived from the element value Returns: A generated sequence whose elements are the result of invoking the selector function on each element of the source sequence. ''' return self._create(self._pool.imap_unordered(selector, iter(self), self._chunksize))
python
def select(self, selector): '''Transforms each element of a sequence into a new form. Each element is transformed through a selector function to produce a value for each value in the source sequence. The generated sequence is lazily evaluated. Args: selector: A unary function mapping a value in the source sequence to the corresponding value in the generated generated sequence. The argument of the selector function (which can have any name) is, Args: element: The value of the element Returns: The selected value derived from the element value Returns: A generated sequence whose elements are the result of invoking the selector function on each element of the source sequence. ''' return self._create(self._pool.imap_unordered(selector, iter(self), self._chunksize))
[ "def", "select", "(", "self", ",", "selector", ")", ":", "return", "self", ".", "_create", "(", "self", ".", "_pool", ".", "imap_unordered", "(", "selector", ",", "iter", "(", "self", ")", ",", "self", ".", "_chunksize", ")", ")" ]
Transforms each element of a sequence into a new form. Each element is transformed through a selector function to produce a value for each value in the source sequence. The generated sequence is lazily evaluated. Args: selector: A unary function mapping a value in the source sequence to the corresponding value in the generated generated sequence. The argument of the selector function (which can have any name) is, Args: element: The value of the element Returns: The selected value derived from the element value Returns: A generated sequence whose elements are the result of invoking the selector function on each element of the source sequence.
[ "Transforms", "each", "element", "of", "a", "sequence", "into", "a", "new", "form", ".", "Each", "element", "is", "transformed", "through", "a", "selector", "function", "to", "produce", "a", "value", "for", "each", "value", "in", "the", "source", "sequence",...
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/parallel_queryable.py#L51-L75
sixty-north/asq
asq/parallel_queryable.py
ParallelQueryable.select_with_index
def select_with_index(self, selector): '''Transforms each element of a sequence into a new form, incorporating the index of the element. Each element is transformed through a selector function which accepts the element value and its zero-based index in the source sequence. The generated sequence is lazily evaluated. Args: selector: A two argument function mapping the index of a value in the source sequence and the element value itself to the corresponding value in the generated sequence. The two arguments of the selector function (which can have any names) and its return value are, Args: index: The zero-based index of the element element: The value of the element Returns: The selected value derived from the index and element Returns: A generated sequence whose elements are the result of invoking the selector function on each element of the source sequence ''' return self._create(self._pool.imap_unordered(star, zip(itertools.repeat(selector), enumerate(iter(self))), self._chunksize))
python
def select_with_index(self, selector): '''Transforms each element of a sequence into a new form, incorporating the index of the element. Each element is transformed through a selector function which accepts the element value and its zero-based index in the source sequence. The generated sequence is lazily evaluated. Args: selector: A two argument function mapping the index of a value in the source sequence and the element value itself to the corresponding value in the generated sequence. The two arguments of the selector function (which can have any names) and its return value are, Args: index: The zero-based index of the element element: The value of the element Returns: The selected value derived from the index and element Returns: A generated sequence whose elements are the result of invoking the selector function on each element of the source sequence ''' return self._create(self._pool.imap_unordered(star, zip(itertools.repeat(selector), enumerate(iter(self))), self._chunksize))
[ "def", "select_with_index", "(", "self", ",", "selector", ")", ":", "return", "self", ".", "_create", "(", "self", ".", "_pool", ".", "imap_unordered", "(", "star", ",", "zip", "(", "itertools", ".", "repeat", "(", "selector", ")", ",", "enumerate", "(",...
Transforms each element of a sequence into a new form, incorporating the index of the element. Each element is transformed through a selector function which accepts the element value and its zero-based index in the source sequence. The generated sequence is lazily evaluated. Args: selector: A two argument function mapping the index of a value in the source sequence and the element value itself to the corresponding value in the generated sequence. The two arguments of the selector function (which can have any names) and its return value are, Args: index: The zero-based index of the element element: The value of the element Returns: The selected value derived from the index and element Returns: A generated sequence whose elements are the result of invoking the selector function on each element of the source sequence
[ "Transforms", "each", "element", "of", "a", "sequence", "into", "a", "new", "form", "incorporating", "the", "index", "of", "the", "element", ".", "Each", "element", "is", "transformed", "through", "a", "selector", "function", "which", "accepts", "the", "elemen...
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/parallel_queryable.py#L77-L106
sixty-north/asq
asq/parallel_queryable.py
ParallelQueryable.select_many
def select_many(self, projector, selector=identity): '''Projects each element of a sequence to an intermediate new sequence, flattens the resulting sequence into one sequence and optionally transforms the flattened sequence using a selector function. Args: projector: A unary function mapping each element of the source sequence into an intermediate sequence. If no projection function is provided, the intermediate sequence will consist of the single corresponding element from the source sequence. The projector function argument (which can have any name) and return values are, Args: element: The value of the element Returns: An iterable derived from the element value selector: An optional unary function mapping the elements in the flattened intermediate sequence to corresponding elements of the result sequence. If no selector function is provided, the identity function is used. The selector function argument and return values are, Args: element: The value of the intermediate element from the concatenated sequences arising from the projector function. Returns: The selected value derived from the element value Returns: A generated sequence whose elements are the result of projecting each element of the source sequence using projector function and then mapping each element through an optional selector function. ''' sequences = (self._create(item).select(projector) for item in iter(self)) # TODO: [asq 2.0] Without the list() to force evaluation # multiprocessing deadlocks... chained_sequence = list(itertools.chain.from_iterable(sequences)) return self._create(self._pool.imap_unordered(selector, chained_sequence, self._chunksize))
python
def select_many(self, projector, selector=identity): '''Projects each element of a sequence to an intermediate new sequence, flattens the resulting sequence into one sequence and optionally transforms the flattened sequence using a selector function. Args: projector: A unary function mapping each element of the source sequence into an intermediate sequence. If no projection function is provided, the intermediate sequence will consist of the single corresponding element from the source sequence. The projector function argument (which can have any name) and return values are, Args: element: The value of the element Returns: An iterable derived from the element value selector: An optional unary function mapping the elements in the flattened intermediate sequence to corresponding elements of the result sequence. If no selector function is provided, the identity function is used. The selector function argument and return values are, Args: element: The value of the intermediate element from the concatenated sequences arising from the projector function. Returns: The selected value derived from the element value Returns: A generated sequence whose elements are the result of projecting each element of the source sequence using projector function and then mapping each element through an optional selector function. ''' sequences = (self._create(item).select(projector) for item in iter(self)) # TODO: [asq 2.0] Without the list() to force evaluation # multiprocessing deadlocks... chained_sequence = list(itertools.chain.from_iterable(sequences)) return self._create(self._pool.imap_unordered(selector, chained_sequence, self._chunksize))
[ "def", "select_many", "(", "self", ",", "projector", ",", "selector", "=", "identity", ")", ":", "sequences", "=", "(", "self", ".", "_create", "(", "item", ")", ".", "select", "(", "projector", ")", "for", "item", "in", "iter", "(", "self", ")", ")"...
Projects each element of a sequence to an intermediate new sequence, flattens the resulting sequence into one sequence and optionally transforms the flattened sequence using a selector function. Args: projector: A unary function mapping each element of the source sequence into an intermediate sequence. If no projection function is provided, the intermediate sequence will consist of the single corresponding element from the source sequence. The projector function argument (which can have any name) and return values are, Args: element: The value of the element Returns: An iterable derived from the element value selector: An optional unary function mapping the elements in the flattened intermediate sequence to corresponding elements of the result sequence. If no selector function is provided, the identity function is used. The selector function argument and return values are, Args: element: The value of the intermediate element from the concatenated sequences arising from the projector function. Returns: The selected value derived from the element value Returns: A generated sequence whose elements are the result of projecting each element of the source sequence using projector function and then mapping each element through an optional selector function.
[ "Projects", "each", "element", "of", "a", "sequence", "to", "an", "intermediate", "new", "sequence", "flattens", "the", "resulting", "sequence", "into", "one", "sequence", "and", "optionally", "transforms", "the", "flattened", "sequence", "using", "a", "selector",...
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/parallel_queryable.py#L108-L150
sixty-north/asq
asq/parallel_queryable.py
OrderedParallelQueryable.select
def select(self, selector): '''Transforms each element of a sequence into a new form. Each element is transformed through a selector function to produce a value for each value in the source sequence. The generated sequence is lazily evaluated. Args: selector: A unary function mapping a value in the source sequence to the corresponding value in the generated generated sequence. The argument of the selector function (which can have any name) is, Args: element: The value of the element Returns: The selected value derived from the element value Returns: A generated sequence whose elements are the result of invoking the selector function on each element of the source sequence. ''' return self.create(self._pool.imap(selector, iter(self), self._chunksize))
python
def select(self, selector): '''Transforms each element of a sequence into a new form. Each element is transformed through a selector function to produce a value for each value in the source sequence. The generated sequence is lazily evaluated. Args: selector: A unary function mapping a value in the source sequence to the corresponding value in the generated generated sequence. The argument of the selector function (which can have any name) is, Args: element: The value of the element Returns: The selected value derived from the element value Returns: A generated sequence whose elements are the result of invoking the selector function on each element of the source sequence. ''' return self.create(self._pool.imap(selector, iter(self), self._chunksize))
[ "def", "select", "(", "self", ",", "selector", ")", ":", "return", "self", ".", "create", "(", "self", ".", "_pool", ".", "imap", "(", "selector", ",", "iter", "(", "self", ")", ",", "self", ".", "_chunksize", ")", ")" ]
Transforms each element of a sequence into a new form. Each element is transformed through a selector function to produce a value for each value in the source sequence. The generated sequence is lazily evaluated. Args: selector: A unary function mapping a value in the source sequence to the corresponding value in the generated generated sequence. The argument of the selector function (which can have any name) is, Args: element: The value of the element Returns: The selected value derived from the element value Returns: A generated sequence whose elements are the result of invoking the selector function on each element of the source sequence.
[ "Transforms", "each", "element", "of", "a", "sequence", "into", "a", "new", "form", ".", "Each", "element", "is", "transformed", "through", "a", "selector", "function", "to", "produce", "a", "value", "for", "each", "value", "in", "the", "source", "sequence",...
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/parallel_queryable.py#L210-L233
sixty-north/asq
asq/selectors.py
make_selector
def make_selector(value): '''Create a selector callable from the supplied value. Args: value: If is a callable, then returned unchanged. If a string is used then create an attribute selector. If in an integer is used then create a key selector. Returns: A callable selector based on the supplied value. Raises: ValueError: If a selector cannot be created from the value. ''' if is_callable(value): return value if is_string(value): return a_(value) raise ValueError("Unable to create callable selector from '{0}'".format(value))
python
def make_selector(value): '''Create a selector callable from the supplied value. Args: value: If is a callable, then returned unchanged. If a string is used then create an attribute selector. If in an integer is used then create a key selector. Returns: A callable selector based on the supplied value. Raises: ValueError: If a selector cannot be created from the value. ''' if is_callable(value): return value if is_string(value): return a_(value) raise ValueError("Unable to create callable selector from '{0}'".format(value))
[ "def", "make_selector", "(", "value", ")", ":", "if", "is_callable", "(", "value", ")", ":", "return", "value", "if", "is_string", "(", "value", ")", ":", "return", "a_", "(", "value", ")", "raise", "ValueError", "(", "\"Unable to create callable selector from...
Create a selector callable from the supplied value. Args: value: If is a callable, then returned unchanged. If a string is used then create an attribute selector. If in an integer is used then create a key selector. Returns: A callable selector based on the supplied value. Raises: ValueError: If a selector cannot be created from the value.
[ "Create", "a", "selector", "callable", "from", "the", "supplied", "value", ".", "Args", ":", "value", ":", "If", "is", "a", "callable", "then", "returned", "unchanged", ".", "If", "a", "string", "is", "used", "then", "create", "an", "attribute", "selector"...
train
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/selectors.py#L89-L107
leonardt/hwtypes
hwtypes/bit_vector.py
BitVector.adc
def adc(self, other : 'BitVector', carry : Bit) -> tp.Tuple['BitVector', Bit]: """ add with carry returns a two element tuple of the form (result, carry) """ T = type(self) other = _coerce(T, other) carry = _coerce(T.unsized_t[1], carry) a = self.zext(1) b = other.zext(1) c = carry.zext(T.size) res = a + b + c return res[0:-1], res[-1]
python
def adc(self, other : 'BitVector', carry : Bit) -> tp.Tuple['BitVector', Bit]: """ add with carry returns a two element tuple of the form (result, carry) """ T = type(self) other = _coerce(T, other) carry = _coerce(T.unsized_t[1], carry) a = self.zext(1) b = other.zext(1) c = carry.zext(T.size) res = a + b + c return res[0:-1], res[-1]
[ "def", "adc", "(", "self", ",", "other", ":", "'BitVector'", ",", "carry", ":", "Bit", ")", "->", "tp", ".", "Tuple", "[", "'BitVector'", ",", "Bit", "]", ":", "T", "=", "type", "(", "self", ")", "other", "=", "_coerce", "(", "T", ",", "other", ...
add with carry returns a two element tuple of the form (result, carry)
[ "add", "with", "carry" ]
train
https://github.com/leonardt/hwtypes/blob/65439bb5e1d8f9afa7852c00a8378b622a9f986e/hwtypes/bit_vector.py#L273-L289
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/types.py
ExpandPath.convert
def convert(self, value, *args, **kwargs): # pylint: disable=arguments-differ """Take a path with $HOME variables and resolve it to full path.""" value = os.path.expanduser(value) return super(ExpandPath, self).convert(value, *args, **kwargs)
python
def convert(self, value, *args, **kwargs): # pylint: disable=arguments-differ """Take a path with $HOME variables and resolve it to full path.""" value = os.path.expanduser(value) return super(ExpandPath, self).convert(value, *args, **kwargs)
[ "def", "convert", "(", "self", ",", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=arguments-differ", "value", "=", "os", ".", "path", ".", "expanduser", "(", "value", ")", "return", "super", "(", "ExpandPath", ",", "sel...
Take a path with $HOME variables and resolve it to full path.
[ "Take", "a", "path", "with", "$HOME", "variables", "and", "resolve", "it", "to", "full", "path", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/types.py#L13-L16
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/table.py
make_table
def make_table(headers=None, rows=None): """Make a table from headers and rows.""" if callable(headers): headers = headers() if callable(rows): rows = rows() assert isinstance(headers, list) assert isinstance(rows, list) assert all(len(row) == len(headers) for row in rows) plain_headers = [strip_ansi(six.text_type(v)) for v in headers] plain_rows = [row for row in [strip_ansi(six.text_type(v)) for v in rows]] plain_headers = [] column_widths = [] for k, v in enumerate(headers): v = six.text_type(v) plain = strip_ansi(v) plain_headers.append(plain) column_widths.append(len(plain)) if len(v) == len(plain): # Value was unstyled, make it bold v = click.style(v, bold=True) headers[k] = v plain_rows = [] for row in rows: plain_row = [] for k, v in enumerate(row): v = six.text_type(v) plain = strip_ansi(v) plain_row.append(plain) column_widths[k] = max(column_widths[k], len(plain)) plain_rows.append(plain_row) return Table( headers=headers, plain_headers=plain_headers, rows=rows, plain_rows=plain_rows, column_widths=column_widths, )
python
def make_table(headers=None, rows=None): """Make a table from headers and rows.""" if callable(headers): headers = headers() if callable(rows): rows = rows() assert isinstance(headers, list) assert isinstance(rows, list) assert all(len(row) == len(headers) for row in rows) plain_headers = [strip_ansi(six.text_type(v)) for v in headers] plain_rows = [row for row in [strip_ansi(six.text_type(v)) for v in rows]] plain_headers = [] column_widths = [] for k, v in enumerate(headers): v = six.text_type(v) plain = strip_ansi(v) plain_headers.append(plain) column_widths.append(len(plain)) if len(v) == len(plain): # Value was unstyled, make it bold v = click.style(v, bold=True) headers[k] = v plain_rows = [] for row in rows: plain_row = [] for k, v in enumerate(row): v = six.text_type(v) plain = strip_ansi(v) plain_row.append(plain) column_widths[k] = max(column_widths[k], len(plain)) plain_rows.append(plain_row) return Table( headers=headers, plain_headers=plain_headers, rows=rows, plain_rows=plain_rows, column_widths=column_widths, )
[ "def", "make_table", "(", "headers", "=", "None", ",", "rows", "=", "None", ")", ":", "if", "callable", "(", "headers", ")", ":", "headers", "=", "headers", "(", ")", "if", "callable", "(", "rows", ")", ":", "rows", "=", "rows", "(", ")", "assert",...
Make a table from headers and rows.
[ "Make", "a", "table", "from", "headers", "and", "rows", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/table.py#L17-L62
venmo/slouch
slouch/__init__.py
_dual_decorator
def _dual_decorator(func): """This is a decorator that converts a paramaterized decorator for no-param use. source: http://stackoverflow.com/questions/3888158 """ @functools.wraps(func) def inner(*args, **kwargs): if ((len(args) == 1 and not kwargs and callable(args[0]) and not (type(args[0]) == type and issubclass(args[0], BaseException)))): return func()(args[0]) elif len(args) == 2 and inspect.isclass(args[0]) and callable(args[1]): return func(args[0], **kwargs)(args[1]) else: return func(*args, **kwargs) return inner
python
def _dual_decorator(func): """This is a decorator that converts a paramaterized decorator for no-param use. source: http://stackoverflow.com/questions/3888158 """ @functools.wraps(func) def inner(*args, **kwargs): if ((len(args) == 1 and not kwargs and callable(args[0]) and not (type(args[0]) == type and issubclass(args[0], BaseException)))): return func()(args[0]) elif len(args) == 2 and inspect.isclass(args[0]) and callable(args[1]): return func(args[0], **kwargs)(args[1]) else: return func(*args, **kwargs) return inner
[ "def", "_dual_decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "(", "(", "len", "(", "args", ")", "==", "1", "and", "not", "kwargs", ...
This is a decorator that converts a paramaterized decorator for no-param use. source: http://stackoverflow.com/questions/3888158
[ "This", "is", "a", "decorator", "that", "converts", "a", "paramaterized", "decorator", "for", "no", "-", "param", "use", "." ]
train
https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L20-L36
venmo/slouch
slouch/__init__.py
help
def help(opts, bot, _): """Usage: help [<command>] With no arguments, print the form of all supported commands. With an argument, print a detailed explanation of a command. """ command = opts['<command>'] if command is None: return bot.help_text() if command not in bot.commands: return "%r is not a known command" % command return bot.commands[command].__doc__
python
def help(opts, bot, _): """Usage: help [<command>] With no arguments, print the form of all supported commands. With an argument, print a detailed explanation of a command. """ command = opts['<command>'] if command is None: return bot.help_text() if command not in bot.commands: return "%r is not a known command" % command return bot.commands[command].__doc__
[ "def", "help", "(", "opts", ",", "bot", ",", "_", ")", ":", "command", "=", "opts", "[", "'<command>'", "]", "if", "command", "is", "None", ":", "return", "bot", ".", "help_text", "(", ")", "if", "command", "not", "in", "bot", ".", "commands", ":",...
Usage: help [<command>] With no arguments, print the form of all supported commands. With an argument, print a detailed explanation of a command.
[ "Usage", ":", "help", "[", "<command", ">", "]" ]
train
https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L39-L52
venmo/slouch
slouch/__init__.py
Bot.command
def command(cls, name=None): """ A decorator to convert a function to a command. A command's docstring must be a docopt usage string. See docopt.org for what it supports. Commands receive three arguments: * opts: a dictionary output by docopt * bot: the Bot instance handling the command (eg for storing state between commands) * event: the Slack event that triggered the command (eg for finding the message's sender) Additional options may be passed in as keyword arguments: * name: the string used to execute the command (no spaces allowed) They must return one of three things: * a string of response text. It will be sent via the RTM api to the channel where the bot received the message. Slack will format it as per https://api.slack.com/docs/message-formatting. * None, to send no response. * a dictionary of kwargs representing a message to send via https://api.slack.com/methods/chat.postMessage. Use this to send more complex messages, such as those with custom link text or DMs. For example, to respond with a DM containing custom link text, return `{'text': '<http://example.com|my text>', 'channel': event['user'], 'username': bot.name}`. Note that this api has higher latency than the RTM api; use it only when necessary. """ # adapted from https://github.com/docopt/docopt/blob/master/examples/interactive_example.py def decorator(func): @functools.wraps(func) def _cmd_wrapper(rest, *args, **kwargs): try: usage = _cmd_wrapper.__doc__.partition('\n')[0] opts = docopt(usage, rest) except (SystemExit, DocoptExit) as e: # opts did not match return str(e) return func(opts, *args, **kwargs) cls.commands[name or func.__name__] = _cmd_wrapper return _cmd_wrapper return decorator
python
def command(cls, name=None): """ A decorator to convert a function to a command. A command's docstring must be a docopt usage string. See docopt.org for what it supports. Commands receive three arguments: * opts: a dictionary output by docopt * bot: the Bot instance handling the command (eg for storing state between commands) * event: the Slack event that triggered the command (eg for finding the message's sender) Additional options may be passed in as keyword arguments: * name: the string used to execute the command (no spaces allowed) They must return one of three things: * a string of response text. It will be sent via the RTM api to the channel where the bot received the message. Slack will format it as per https://api.slack.com/docs/message-formatting. * None, to send no response. * a dictionary of kwargs representing a message to send via https://api.slack.com/methods/chat.postMessage. Use this to send more complex messages, such as those with custom link text or DMs. For example, to respond with a DM containing custom link text, return `{'text': '<http://example.com|my text>', 'channel': event['user'], 'username': bot.name}`. Note that this api has higher latency than the RTM api; use it only when necessary. """ # adapted from https://github.com/docopt/docopt/blob/master/examples/interactive_example.py def decorator(func): @functools.wraps(func) def _cmd_wrapper(rest, *args, **kwargs): try: usage = _cmd_wrapper.__doc__.partition('\n')[0] opts = docopt(usage, rest) except (SystemExit, DocoptExit) as e: # opts did not match return str(e) return func(opts, *args, **kwargs) cls.commands[name or func.__name__] = _cmd_wrapper return _cmd_wrapper return decorator
[ "def", "command", "(", "cls", ",", "name", "=", "None", ")", ":", "# adapted from https://github.com/docopt/docopt/blob/master/examples/interactive_example.py", "def", "decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "_cmd...
A decorator to convert a function to a command. A command's docstring must be a docopt usage string. See docopt.org for what it supports. Commands receive three arguments: * opts: a dictionary output by docopt * bot: the Bot instance handling the command (eg for storing state between commands) * event: the Slack event that triggered the command (eg for finding the message's sender) Additional options may be passed in as keyword arguments: * name: the string used to execute the command (no spaces allowed) They must return one of three things: * a string of response text. It will be sent via the RTM api to the channel where the bot received the message. Slack will format it as per https://api.slack.com/docs/message-formatting. * None, to send no response. * a dictionary of kwargs representing a message to send via https://api.slack.com/methods/chat.postMessage. Use this to send more complex messages, such as those with custom link text or DMs. For example, to respond with a DM containing custom link text, return `{'text': '<http://example.com|my text>', 'channel': event['user'], 'username': bot.name}`. Note that this api has higher latency than the RTM api; use it only when necessary.
[ "A", "decorator", "to", "convert", "a", "function", "to", "a", "command", "." ]
train
https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L83-L129
venmo/slouch
slouch/__init__.py
Bot.help_text
def help_text(cls): """Return a slack-formatted list of commands with their usage.""" docs = [cmd_func.__doc__ for cmd_func in cls.commands.values()] # Don't want to include 'usage: ' or explanation. usage_lines = [doc.partition('\n')[0] for doc in docs] terse_lines = [line[len('Usage: '):] for line in usage_lines] terse_lines.sort() return '\n'.join(['Available commands:\n'] + terse_lines)
python
def help_text(cls): """Return a slack-formatted list of commands with their usage.""" docs = [cmd_func.__doc__ for cmd_func in cls.commands.values()] # Don't want to include 'usage: ' or explanation. usage_lines = [doc.partition('\n')[0] for doc in docs] terse_lines = [line[len('Usage: '):] for line in usage_lines] terse_lines.sort() return '\n'.join(['Available commands:\n'] + terse_lines)
[ "def", "help_text", "(", "cls", ")", ":", "docs", "=", "[", "cmd_func", ".", "__doc__", "for", "cmd_func", "in", "cls", ".", "commands", ".", "values", "(", ")", "]", "# Don't want to include 'usage: ' or explanation.", "usage_lines", "=", "[", "doc", ".", "...
Return a slack-formatted list of commands with their usage.
[ "Return", "a", "slack", "-", "formatted", "list", "of", "commands", "with", "their", "usage", "." ]
train
https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L132-L140
venmo/slouch
slouch/__init__.py
Bot.run_forever
def run_forever(self): """Run the bot, blocking forever.""" res = self.slack.rtm.start() self.log.info("current channels: %s", ','.join(c['name'] for c in res.body['channels'] if c['is_member'])) self.id = res.body['self']['id'] self.name = res.body['self']['name'] self.my_mention = "<@%s>" % self.id self.ws = websocket.WebSocketApp( res.body['url'], on_message=self._on_message, on_error=self._on_error, on_close=self._on_close, on_open=self._on_open) self.prepare_connection(self.config) self.ws.run_forever()
python
def run_forever(self): """Run the bot, blocking forever.""" res = self.slack.rtm.start() self.log.info("current channels: %s", ','.join(c['name'] for c in res.body['channels'] if c['is_member'])) self.id = res.body['self']['id'] self.name = res.body['self']['name'] self.my_mention = "<@%s>" % self.id self.ws = websocket.WebSocketApp( res.body['url'], on_message=self._on_message, on_error=self._on_error, on_close=self._on_close, on_open=self._on_open) self.prepare_connection(self.config) self.ws.run_forever()
[ "def", "run_forever", "(", "self", ")", ":", "res", "=", "self", ".", "slack", ".", "rtm", ".", "start", "(", ")", "self", ".", "log", ".", "info", "(", "\"current channels: %s\"", ",", "','", ".", "join", "(", "c", "[", "'name'", "]", "for", "c", ...
Run the bot, blocking forever.
[ "Run", "the", "bot", "blocking", "forever", "." ]
train
https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L199-L216
venmo/slouch
slouch/__init__.py
Bot._bot_identifier
def _bot_identifier(self, message): """Return the identifier used to address this bot in this message. If one is not found, return None. :param message: a message dict from the slack api. """ text = message['text'] formatters = [ lambda identifier: "%s " % identifier, lambda identifier: "%s:" % identifier, ] my_identifiers = [formatter(identifier) for identifier in [self.name, self.my_mention] for formatter in formatters] for identifier in my_identifiers: if text.startswith(identifier): self.log.debug("sent to me:\n%s", pprint.pformat(message)) return identifier return None
python
def _bot_identifier(self, message): """Return the identifier used to address this bot in this message. If one is not found, return None. :param message: a message dict from the slack api. """ text = message['text'] formatters = [ lambda identifier: "%s " % identifier, lambda identifier: "%s:" % identifier, ] my_identifiers = [formatter(identifier) for identifier in [self.name, self.my_mention] for formatter in formatters] for identifier in my_identifiers: if text.startswith(identifier): self.log.debug("sent to me:\n%s", pprint.pformat(message)) return identifier return None
[ "def", "_bot_identifier", "(", "self", ",", "message", ")", ":", "text", "=", "message", "[", "'text'", "]", "formatters", "=", "[", "lambda", "identifier", ":", "\"%s \"", "%", "identifier", ",", "lambda", "identifier", ":", "\"%s:\"", "%", "identifier", ...
Return the identifier used to address this bot in this message. If one is not found, return None. :param message: a message dict from the slack api.
[ "Return", "the", "identifier", "used", "to", "address", "this", "bot", "in", "this", "message", ".", "If", "one", "is", "not", "found", "return", "None", "." ]
train
https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L218-L238
venmo/slouch
slouch/__init__.py
Bot._handle_command_response
def _handle_command_response(self, res, event): """Either send a message (choosing between rtm and postMessage) or ignore the response. :param event: a slacker event dict :param res: a string, a dict, or None. See the command docstring for what these represent. """ response_handler = None if isinstance(res, basestring): response_handler = functools.partial(self._send_rtm_message, event['channel']) elif isinstance(res, dict): response_handler = self._send_api_message if response_handler is not None: response_handler(res)
python
def _handle_command_response(self, res, event): """Either send a message (choosing between rtm and postMessage) or ignore the response. :param event: a slacker event dict :param res: a string, a dict, or None. See the command docstring for what these represent. """ response_handler = None if isinstance(res, basestring): response_handler = functools.partial(self._send_rtm_message, event['channel']) elif isinstance(res, dict): response_handler = self._send_api_message if response_handler is not None: response_handler(res)
[ "def", "_handle_command_response", "(", "self", ",", "res", ",", "event", ")", ":", "response_handler", "=", "None", "if", "isinstance", "(", "res", ",", "basestring", ")", ":", "response_handler", "=", "functools", ".", "partial", "(", "self", ".", "_send_r...
Either send a message (choosing between rtm and postMessage) or ignore the response. :param event: a slacker event dict :param res: a string, a dict, or None. See the command docstring for what these represent.
[ "Either", "send", "a", "message", "(", "choosing", "between", "rtm", "and", "postMessage", ")", "or", "ignore", "the", "response", "." ]
train
https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L240-L256
venmo/slouch
slouch/__init__.py
Bot._handle_long_response
def _handle_long_response(self, res): """Splits messages that are too long into multiple events :param res: a slack response string or dict """ is_rtm_message = isinstance(res, basestring) is_api_message = isinstance(res, dict) if is_rtm_message: text = res elif is_api_message: text = res['text'] message_length = len(text) if message_length <= SLACK_MESSAGE_LIMIT: return [res] remaining_str = text responses = [] while remaining_str: less_than_limit = len(remaining_str) < SLACK_MESSAGE_LIMIT if less_than_limit: last_line_break = None else: last_line_break = remaining_str[:SLACK_MESSAGE_LIMIT].rfind('\n') if is_rtm_message: responses.append(remaining_str[:last_line_break]) elif is_api_message: template = res.copy() template['text'] = remaining_str[:last_line_break] responses.append(template) if less_than_limit: remaining_str = None else: remaining_str = remaining_str[last_line_break:] self.log.debug("_handle_long_response: splitting long response %s, returns: \n %s", pprint.pformat(res), pprint.pformat(responses)) return responses
python
def _handle_long_response(self, res): """Splits messages that are too long into multiple events :param res: a slack response string or dict """ is_rtm_message = isinstance(res, basestring) is_api_message = isinstance(res, dict) if is_rtm_message: text = res elif is_api_message: text = res['text'] message_length = len(text) if message_length <= SLACK_MESSAGE_LIMIT: return [res] remaining_str = text responses = [] while remaining_str: less_than_limit = len(remaining_str) < SLACK_MESSAGE_LIMIT if less_than_limit: last_line_break = None else: last_line_break = remaining_str[:SLACK_MESSAGE_LIMIT].rfind('\n') if is_rtm_message: responses.append(remaining_str[:last_line_break]) elif is_api_message: template = res.copy() template['text'] = remaining_str[:last_line_break] responses.append(template) if less_than_limit: remaining_str = None else: remaining_str = remaining_str[last_line_break:] self.log.debug("_handle_long_response: splitting long response %s, returns: \n %s", pprint.pformat(res), pprint.pformat(responses)) return responses
[ "def", "_handle_long_response", "(", "self", ",", "res", ")", ":", "is_rtm_message", "=", "isinstance", "(", "res", ",", "basestring", ")", "is_api_message", "=", "isinstance", "(", "res", ",", "dict", ")", "if", "is_rtm_message", ":", "text", "=", "res", ...
Splits messages that are too long into multiple events :param res: a slack response string or dict
[ "Splits", "messages", "that", "are", "too", "long", "into", "multiple", "events", ":", "param", "res", ":", "a", "slack", "response", "string", "or", "dict" ]
train
https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L258-L301
venmo/slouch
slouch/__init__.py
Bot._send_rtm_message
def _send_rtm_message(self, channel_id, text): """Send a Slack message to a channel over RTM. :param channel_id: a slack channel id. :param text: a slack message. Serverside formatting is done in a similar way to normal user message; see `Slack's docs <https://api.slack.com/docs/formatting>`__. """ message = { 'id': self._current_message_id, 'type': 'message', 'channel': channel_id, 'text': text, } self.ws.send(json.dumps(message)) self._current_message_id += 1
python
def _send_rtm_message(self, channel_id, text): """Send a Slack message to a channel over RTM. :param channel_id: a slack channel id. :param text: a slack message. Serverside formatting is done in a similar way to normal user message; see `Slack's docs <https://api.slack.com/docs/formatting>`__. """ message = { 'id': self._current_message_id, 'type': 'message', 'channel': channel_id, 'text': text, } self.ws.send(json.dumps(message)) self._current_message_id += 1
[ "def", "_send_rtm_message", "(", "self", ",", "channel_id", ",", "text", ")", ":", "message", "=", "{", "'id'", ":", "self", ".", "_current_message_id", ",", "'type'", ":", "'message'", ",", "'channel'", ":", "channel_id", ",", "'text'", ":", "text", ",", ...
Send a Slack message to a channel over RTM. :param channel_id: a slack channel id. :param text: a slack message. Serverside formatting is done in a similar way to normal user message; see `Slack's docs <https://api.slack.com/docs/formatting>`__.
[ "Send", "a", "Slack", "message", "to", "a", "channel", "over", "RTM", "." ]
train
https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L303-L319
venmo/slouch
slouch/__init__.py
Bot._send_api_message
def _send_api_message(self, message): """Send a Slack message via the chat.postMessage api. :param message: a dict of kwargs to be passed to slacker. """ self.slack.chat.post_message(**message) self.log.debug("sent api message %r", message)
python
def _send_api_message(self, message): """Send a Slack message via the chat.postMessage api. :param message: a dict of kwargs to be passed to slacker. """ self.slack.chat.post_message(**message) self.log.debug("sent api message %r", message)
[ "def", "_send_api_message", "(", "self", ",", "message", ")", ":", "self", ".", "slack", ".", "chat", ".", "post_message", "(", "*", "*", "message", ")", "self", ".", "log", ".", "debug", "(", "\"sent api message %r\"", ",", "message", ")" ]
Send a Slack message via the chat.postMessage api. :param message: a dict of kwargs to be passed to slacker.
[ "Send", "a", "Slack", "message", "via", "the", "chat", ".", "postMessage", "api", "." ]
train
https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L321-L328
marrow/schema
marrow/schema/validate/compound.py
Compound._validators
def _validators(self): """Iterate across the complete set of child validators.""" for validator in self.__validators__.values(): yield validator if self.validators: for validator in self.validators: yield validator
python
def _validators(self): """Iterate across the complete set of child validators.""" for validator in self.__validators__.values(): yield validator if self.validators: for validator in self.validators: yield validator
[ "def", "_validators", "(", "self", ")", ":", "for", "validator", "in", "self", ".", "__validators__", ".", "values", "(", ")", ":", "yield", "validator", "if", "self", ".", "validators", ":", "for", "validator", "in", "self", ".", "validators", ":", "yie...
Iterate across the complete set of child validators.
[ "Iterate", "across", "the", "complete", "set", "of", "child", "validators", "." ]
train
https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/validate/compound.py#L24-L32
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/utils.py
make_user_agent
def make_user_agent(prefix=None): """Get a suitable user agent for identifying the CLI process.""" prefix = (prefix or platform.platform(terse=1)).strip().lower() return "cloudsmith-cli/%(prefix)s cli:%(version)s api:%(api_version)s" % { "version": get_cli_version(), "api_version": get_api_version(), "prefix": prefix, }
python
def make_user_agent(prefix=None): """Get a suitable user agent for identifying the CLI process.""" prefix = (prefix or platform.platform(terse=1)).strip().lower() return "cloudsmith-cli/%(prefix)s cli:%(version)s api:%(api_version)s" % { "version": get_cli_version(), "api_version": get_api_version(), "prefix": prefix, }
[ "def", "make_user_agent", "(", "prefix", "=", "None", ")", ":", "prefix", "=", "(", "prefix", "or", "platform", ".", "platform", "(", "terse", "=", "1", ")", ")", ".", "strip", "(", ")", ".", "lower", "(", ")", "return", "\"cloudsmith-cli/%(prefix)s cli:...
Get a suitable user agent for identifying the CLI process.
[ "Get", "a", "suitable", "user", "agent", "for", "identifying", "the", "CLI", "process", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/utils.py#L18-L25
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/utils.py
pretty_print_list_info
def pretty_print_list_info(num_results, page_info=None, suffix=None): """Pretty print list info, with pagination, for user display.""" num_results_fg = "green" if num_results else "red" num_results_text = click.style(str(num_results), fg=num_results_fg) if page_info and page_info.is_valid: page_range = page_info.calculate_range(num_results) page_info_text = "page: %(page)s/%(page_total)s, page size: %(page_size)s" % { "page": click.style(str(page_info.page), bold=True), "page_size": click.style(str(page_info.page_size), bold=True), "page_total": click.style(str(page_info.page_total), bold=True), } range_results_text = "%(from)s-%(to)s (%(num_results)s) of %(total)s" % { "num_results": num_results_text, "from": click.style(str(page_range[0]), fg=num_results_fg), "to": click.style(str(page_range[1]), fg=num_results_fg), "total": click.style(str(page_info.count), fg=num_results_fg), } else: page_info_text = "" range_results_text = num_results_text click.secho( "Results: %(range_results)s %(suffix)s%(page_info)s" % { "range_results": range_results_text, "page_info": " (%s)" % page_info_text if page_info_text else "", "suffix": suffix or "item(s)", } )
python
def pretty_print_list_info(num_results, page_info=None, suffix=None): """Pretty print list info, with pagination, for user display.""" num_results_fg = "green" if num_results else "red" num_results_text = click.style(str(num_results), fg=num_results_fg) if page_info and page_info.is_valid: page_range = page_info.calculate_range(num_results) page_info_text = "page: %(page)s/%(page_total)s, page size: %(page_size)s" % { "page": click.style(str(page_info.page), bold=True), "page_size": click.style(str(page_info.page_size), bold=True), "page_total": click.style(str(page_info.page_total), bold=True), } range_results_text = "%(from)s-%(to)s (%(num_results)s) of %(total)s" % { "num_results": num_results_text, "from": click.style(str(page_range[0]), fg=num_results_fg), "to": click.style(str(page_range[1]), fg=num_results_fg), "total": click.style(str(page_info.count), fg=num_results_fg), } else: page_info_text = "" range_results_text = num_results_text click.secho( "Results: %(range_results)s %(suffix)s%(page_info)s" % { "range_results": range_results_text, "page_info": " (%s)" % page_info_text if page_info_text else "", "suffix": suffix or "item(s)", } )
[ "def", "pretty_print_list_info", "(", "num_results", ",", "page_info", "=", "None", ",", "suffix", "=", "None", ")", ":", "num_results_fg", "=", "\"green\"", "if", "num_results", "else", "\"red\"", "num_results_text", "=", "click", ".", "style", "(", "str", "(...
Pretty print list info, with pagination, for user display.
[ "Pretty", "print", "list", "info", "with", "pagination", "for", "user", "display", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/utils.py#L28-L57
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/utils.py
pretty_print_table
def pretty_print_table(headers, rows): """Pretty print a table from headers and rows.""" table = make_table(headers=headers, rows=rows) pretty_print_table_instance(table)
python
def pretty_print_table(headers, rows): """Pretty print a table from headers and rows.""" table = make_table(headers=headers, rows=rows) pretty_print_table_instance(table)
[ "def", "pretty_print_table", "(", "headers", ",", "rows", ")", ":", "table", "=", "make_table", "(", "headers", "=", "headers", ",", "rows", "=", "rows", ")", "pretty_print_table_instance", "(", "table", ")" ]
Pretty print a table from headers and rows.
[ "Pretty", "print", "a", "table", "from", "headers", "and", "rows", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/utils.py#L60-L63
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/utils.py
pretty_print_table_instance
def pretty_print_table_instance(table): """Pretty print a table instance.""" assert isinstance(table, Table) def pretty_print_row(styled, plain): """Pretty print a row.""" click.secho( " | ".join( v + " " * (table.column_widths[k] - len(plain[k])) for k, v in enumerate(styled) ) ) pretty_print_row(table.headers, table.plain_headers) for k, row in enumerate(table.rows): pretty_print_row(row, table.plain_rows[k])
python
def pretty_print_table_instance(table): """Pretty print a table instance.""" assert isinstance(table, Table) def pretty_print_row(styled, plain): """Pretty print a row.""" click.secho( " | ".join( v + " " * (table.column_widths[k] - len(plain[k])) for k, v in enumerate(styled) ) ) pretty_print_row(table.headers, table.plain_headers) for k, row in enumerate(table.rows): pretty_print_row(row, table.plain_rows[k])
[ "def", "pretty_print_table_instance", "(", "table", ")", ":", "assert", "isinstance", "(", "table", ",", "Table", ")", "def", "pretty_print_row", "(", "styled", ",", "plain", ")", ":", "\"\"\"Pretty print a row.\"\"\"", "click", ".", "secho", "(", "\" | \"", "."...
Pretty print a table instance.
[ "Pretty", "print", "a", "table", "instance", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/utils.py#L66-L81
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/utils.py
print_rate_limit_info
def print_rate_limit_info(opts, rate_info, atexit=False): """Tell the user when we're being rate limited.""" if not rate_info: return show_info = ( opts.always_show_rate_limit or atexit or rate_info.interval > opts.rate_limit_warning ) if not show_info: return click.echo(err=True) click.secho( "Throttling (rate limited) for: %(throttle)s seconds ... " % {"throttle": click.style(six.text_type(rate_info.interval), reverse=True)}, err=True, reset=False, )
python
def print_rate_limit_info(opts, rate_info, atexit=False): """Tell the user when we're being rate limited.""" if not rate_info: return show_info = ( opts.always_show_rate_limit or atexit or rate_info.interval > opts.rate_limit_warning ) if not show_info: return click.echo(err=True) click.secho( "Throttling (rate limited) for: %(throttle)s seconds ... " % {"throttle": click.style(six.text_type(rate_info.interval), reverse=True)}, err=True, reset=False, )
[ "def", "print_rate_limit_info", "(", "opts", ",", "rate_info", ",", "atexit", "=", "False", ")", ":", "if", "not", "rate_info", ":", "return", "show_info", "=", "(", "opts", ".", "always_show_rate_limit", "or", "atexit", "or", "rate_info", ".", "interval", "...
Tell the user when we're being rate limited.
[ "Tell", "the", "user", "when", "we", "re", "being", "rate", "limited", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/utils.py#L84-L104
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/utils.py
maybe_print_as_json
def maybe_print_as_json(opts, data, page_info=None): """Maybe print data as JSON.""" if opts.output not in ("json", "pretty_json"): return False root = {"data": data} if page_info is not None and page_info.is_valid: meta = root["meta"] = {} meta["pagination"] = page_info.as_dict(num_results=len(data)) if opts.output == "pretty_json": dump = json.dumps(root, indent=4, sort_keys=True) else: dump = json.dumps(root, sort_keys=True) click.echo(dump) return True
python
def maybe_print_as_json(opts, data, page_info=None): """Maybe print data as JSON.""" if opts.output not in ("json", "pretty_json"): return False root = {"data": data} if page_info is not None and page_info.is_valid: meta = root["meta"] = {} meta["pagination"] = page_info.as_dict(num_results=len(data)) if opts.output == "pretty_json": dump = json.dumps(root, indent=4, sort_keys=True) else: dump = json.dumps(root, sort_keys=True) click.echo(dump) return True
[ "def", "maybe_print_as_json", "(", "opts", ",", "data", ",", "page_info", "=", "None", ")", ":", "if", "opts", ".", "output", "not", "in", "(", "\"json\"", ",", "\"pretty_json\"", ")", ":", "return", "False", "root", "=", "{", "\"data\"", ":", "data", ...
Maybe print data as JSON.
[ "Maybe", "print", "data", "as", "JSON", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/utils.py#L107-L124
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/utils.py
confirm_operation
def confirm_operation(prompt, prefix=None, assume_yes=False, err=False): """Prompt the user for confirmation for dangerous actions.""" if assume_yes: return True prefix = prefix or click.style( "Are you %s certain you want to" % (click.style("absolutely", bold=True)) ) prompt = "%(prefix)s %(prompt)s?" % {"prefix": prefix, "prompt": prompt} if click.confirm(prompt, err=err): return True click.echo(err=err) click.secho("OK, phew! Close call. :-)", fg="green", err=err) return False
python
def confirm_operation(prompt, prefix=None, assume_yes=False, err=False): """Prompt the user for confirmation for dangerous actions.""" if assume_yes: return True prefix = prefix or click.style( "Are you %s certain you want to" % (click.style("absolutely", bold=True)) ) prompt = "%(prefix)s %(prompt)s?" % {"prefix": prefix, "prompt": prompt} if click.confirm(prompt, err=err): return True click.echo(err=err) click.secho("OK, phew! Close call. :-)", fg="green", err=err) return False
[ "def", "confirm_operation", "(", "prompt", ",", "prefix", "=", "None", ",", "assume_yes", "=", "False", ",", "err", "=", "False", ")", ":", "if", "assume_yes", ":", "return", "True", "prefix", "=", "prefix", "or", "click", ".", "style", "(", "\"Are you %...
Prompt the user for confirmation for dangerous actions.
[ "Prompt", "the", "user", "for", "confirmation", "for", "dangerous", "actions", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/utils.py#L127-L143
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/token.py
validate_login
def validate_login(ctx, param, value): """Ensure that login is not blank.""" # pylint: disable=unused-argument value = value.strip() if not value: raise click.BadParameter("The value cannot be blank.", param=param) return value
python
def validate_login(ctx, param, value): """Ensure that login is not blank.""" # pylint: disable=unused-argument value = value.strip() if not value: raise click.BadParameter("The value cannot be blank.", param=param) return value
[ "def", "validate_login", "(", "ctx", ",", "param", ",", "value", ")", ":", "# pylint: disable=unused-argument", "value", "=", "value", ".", "strip", "(", ")", "if", "not", "value", ":", "raise", "click", ".", "BadParameter", "(", "\"The value cannot be blank.\""...
Ensure that login is not blank.
[ "Ensure", "that", "login", "is", "not", "blank", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/token.py#L22-L28
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/token.py
create_config_files
def create_config_files(ctx, opts, api_key): """Create default config files.""" # pylint: disable=unused-argument config_reader = opts.get_config_reader() creds_reader = opts.get_creds_reader() has_config = config_reader.has_default_file() has_creds = creds_reader.has_default_file() if has_config and has_creds: create = False else: click.echo() create = click.confirm( "No default config file(s) found, do you want to create them?" ) click.echo() if not create: click.secho( "For reference here are your default config file locations:", fg="yellow" ) else: click.secho( "Great! Let me just create your default configs for you now ...", fg="green" ) configs = ( ConfigValues(reader=config_reader, present=has_config, mode=None, data={}), ConfigValues( reader=creds_reader, present=has_creds, mode=stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP, data={"api_key": api_key}, ), ) has_errors = False for config in configs: click.echo( "%(name)s config file: %(filepath)s ... " % { "name": click.style(config.reader.config_name.capitalize(), bold=True), "filepath": click.style( config.reader.get_default_filepath(), fg="magenta" ), }, nl=False, ) if not config.present and create: try: ok = config.reader.create_default_file( data=config.data, mode=config.mode ) except (OSError, IOError) as exc: ok = False error_message = exc.strerror has_errors = True if ok: click.secho("CREATED", fg="green") else: click.secho("ERROR", fg="red") click.secho( "The following error occurred while trying to " "create the file: %(message)s" % {"message": click.style(error_message, fg="red")} ) continue click.secho("EXISTS" if config.present else "NOT CREATED", fg="yellow") return create, has_errors
python
def create_config_files(ctx, opts, api_key): """Create default config files.""" # pylint: disable=unused-argument config_reader = opts.get_config_reader() creds_reader = opts.get_creds_reader() has_config = config_reader.has_default_file() has_creds = creds_reader.has_default_file() if has_config and has_creds: create = False else: click.echo() create = click.confirm( "No default config file(s) found, do you want to create them?" ) click.echo() if not create: click.secho( "For reference here are your default config file locations:", fg="yellow" ) else: click.secho( "Great! Let me just create your default configs for you now ...", fg="green" ) configs = ( ConfigValues(reader=config_reader, present=has_config, mode=None, data={}), ConfigValues( reader=creds_reader, present=has_creds, mode=stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP, data={"api_key": api_key}, ), ) has_errors = False for config in configs: click.echo( "%(name)s config file: %(filepath)s ... " % { "name": click.style(config.reader.config_name.capitalize(), bold=True), "filepath": click.style( config.reader.get_default_filepath(), fg="magenta" ), }, nl=False, ) if not config.present and create: try: ok = config.reader.create_default_file( data=config.data, mode=config.mode ) except (OSError, IOError) as exc: ok = False error_message = exc.strerror has_errors = True if ok: click.secho("CREATED", fg="green") else: click.secho("ERROR", fg="red") click.secho( "The following error occurred while trying to " "create the file: %(message)s" % {"message": click.style(error_message, fg="red")} ) continue click.secho("EXISTS" if config.present else "NOT CREATED", fg="yellow") return create, has_errors
[ "def", "create_config_files", "(", "ctx", ",", "opts", ",", "api_key", ")", ":", "# pylint: disable=unused-argument", "config_reader", "=", "opts", ".", "get_config_reader", "(", ")", "creds_reader", "=", "opts", ".", "get_creds_reader", "(", ")", "has_config", "=...
Create default config files.
[ "Create", "default", "config", "files", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/token.py#L31-L103
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/token.py
token
def token(ctx, opts, login, password): """Retrieve your API authentication token/key.""" click.echo( "Retrieving API token for %(login)s ... " % {"login": click.style(login, bold=True)}, nl=False, ) context_msg = "Failed to retrieve the API token!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): api_key = get_user_token(login=login, password=password) click.secho("OK", fg="green") click.echo( "Your API key/token is: %(token)s" % {"token": click.style(api_key, fg="magenta")} ) create, has_errors = create_config_files(ctx, opts, api_key=api_key) if has_errors: click.echo() click.secho("Oops, please fix the errors and try again!", fg="red") return if opts.api_key != api_key: click.echo() if opts.api_key: click.secho( "Note: The above API key doesn't match what you have in " "your default credentials config file.", fg="yellow", ) elif not create: click.secho( "Note: Don't forget to put your API key in a config file, " "export it on the environment, or set it via -k.", fg="yellow", ) click.secho( "If you need more help please see the documentation: " "%(website)s" % {"website": click.style(get_help_website(), bold=True)} ) click.echo() click.secho("You're ready to rock, let's start automating!", fg="green")
python
def token(ctx, opts, login, password): """Retrieve your API authentication token/key.""" click.echo( "Retrieving API token for %(login)s ... " % {"login": click.style(login, bold=True)}, nl=False, ) context_msg = "Failed to retrieve the API token!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): api_key = get_user_token(login=login, password=password) click.secho("OK", fg="green") click.echo( "Your API key/token is: %(token)s" % {"token": click.style(api_key, fg="magenta")} ) create, has_errors = create_config_files(ctx, opts, api_key=api_key) if has_errors: click.echo() click.secho("Oops, please fix the errors and try again!", fg="red") return if opts.api_key != api_key: click.echo() if opts.api_key: click.secho( "Note: The above API key doesn't match what you have in " "your default credentials config file.", fg="yellow", ) elif not create: click.secho( "Note: Don't forget to put your API key in a config file, " "export it on the environment, or set it via -k.", fg="yellow", ) click.secho( "If you need more help please see the documentation: " "%(website)s" % {"website": click.style(get_help_website(), bold=True)} ) click.echo() click.secho("You're ready to rock, let's start automating!", fg="green")
[ "def", "token", "(", "ctx", ",", "opts", ",", "login", ",", "password", ")", ":", "click", ".", "echo", "(", "\"Retrieving API token for %(login)s ... \"", "%", "{", "\"login\"", ":", "click", ".", "style", "(", "login", ",", "bold", "=", "True", ")", "}...
Retrieve your API authentication token/key.
[ "Retrieve", "your", "API", "authentication", "token", "/", "key", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/token.py#L120-L167
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/status.py
status
def status(ctx, opts, owner_repo_package): """ Get the synchronisation status for a package. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the package itself. All separated by a slash. Example: 'your-org/awesome-repo/better-pkg'. """ owner, repo, slug = owner_repo_package click.echo( "Getting status of %(package)s in %(owner)s/%(repo)s ... " % { "owner": click.style(owner, bold=True), "repo": click.style(repo, bold=True), "package": click.style(slug, bold=True), }, nl=False, ) context_msg = "Failed to get status of package!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): res = get_package_status(owner, repo, slug) ok, failed, _, status_str, stage_str, reason = res click.secho("OK", fg="green") if not stage_str: package_status = status_str else: package_status = "%(status)s / %(stage)s" % { "status": status_str, "stage": stage_str, } if ok: status_colour = "green" elif failed: status_colour = "red" else: status_colour = "magenta" click.secho( "The package status is: %(status)s" % {"status": click.style(package_status, fg=status_colour)} ) if reason: click.secho( "Reason given: %(reason)s" % {"reason": click.style(reason, fg="yellow")}, fg=status_colour, )
python
def status(ctx, opts, owner_repo_package): """ Get the synchronisation status for a package. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the package itself. All separated by a slash. Example: 'your-org/awesome-repo/better-pkg'. """ owner, repo, slug = owner_repo_package click.echo( "Getting status of %(package)s in %(owner)s/%(repo)s ... " % { "owner": click.style(owner, bold=True), "repo": click.style(repo, bold=True), "package": click.style(slug, bold=True), }, nl=False, ) context_msg = "Failed to get status of package!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): res = get_package_status(owner, repo, slug) ok, failed, _, status_str, stage_str, reason = res click.secho("OK", fg="green") if not stage_str: package_status = status_str else: package_status = "%(status)s / %(stage)s" % { "status": status_str, "stage": stage_str, } if ok: status_colour = "green" elif failed: status_colour = "red" else: status_colour = "magenta" click.secho( "The package status is: %(status)s" % {"status": click.style(package_status, fg=status_colour)} ) if reason: click.secho( "Reason given: %(reason)s" % {"reason": click.style(reason, fg="yellow")}, fg=status_colour, )
[ "def", "status", "(", "ctx", ",", "opts", ",", "owner_repo_package", ")", ":", "owner", ",", "repo", ",", "slug", "=", "owner_repo_package", "click", ".", "echo", "(", "\"Getting status of %(package)s in %(owner)s/%(repo)s ... \"", "%", "{", "\"owner\"", ":", "cli...
Get the synchronisation status for a package. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the package itself. All separated by a slash. Example: 'your-org/awesome-repo/better-pkg'.
[ "Get", "the", "synchronisation", "status", "for", "a", "package", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/status.py#L25-L79
marrow/schema
marrow/schema/declarative.py
Container._process_arguments
def _process_arguments(self, args, kw): """Map positional to keyword arguments, identify invalid assignments, and return the result. This is likely generic enough to be useful as a standalone utility function, and goes to a fair amount of effort to ensure raised exceptions are as Python-like as possible. """ # Ensure we were not passed too many arguments. if len(args) > len(self.__attributes__): raise TypeError('{0} takes no more than {1} argument{2} ({3} given)'.format( self.__class__.__name__, len(self.__attributes__), '' if len(self.__attributes__) == 1 else 's', len(args) )) # Retrieve the names associated with the positional parameters. names = [name for name in self.__attributes__.keys() if name[0] != '_' or name == '__name__'][:len(args)] # Sets provide a convienent way to identify intersections. duplicates = set(kw.keys()) & set(names) # Given duplicate values, explode gloriously. if duplicates: raise TypeError('{0} got multiple values for keyword argument{1}: {2}'.format( self.__class__.__name__, '' if len(duplicates) == 1 else 's', ', '.join(duplicates) )) def field_values(args, kw): """A little closure to yield out fields and their assigned values in field order.""" for i, arg in enumerate(self.__attributes__.keys()): if len(args): yield arg, args.popleft() if arg in kw: yield arg, kw.pop(arg) result = odict(field_values(deque(args), dict(kw))) # Again use sets, this time to identify unknown keys. unknown = set(kw.keys()) - set(result.keys()) # Given unknown keys, explode gloriously. if unknown: raise TypeError('{0} got unexpected keyword argument{1}: {2}'.format( self.__class__.__name__, '' if len(unknown) == 1 else 's', ', '.join(unknown) )) return result
python
def _process_arguments(self, args, kw): """Map positional to keyword arguments, identify invalid assignments, and return the result. This is likely generic enough to be useful as a standalone utility function, and goes to a fair amount of effort to ensure raised exceptions are as Python-like as possible. """ # Ensure we were not passed too many arguments. if len(args) > len(self.__attributes__): raise TypeError('{0} takes no more than {1} argument{2} ({3} given)'.format( self.__class__.__name__, len(self.__attributes__), '' if len(self.__attributes__) == 1 else 's', len(args) )) # Retrieve the names associated with the positional parameters. names = [name for name in self.__attributes__.keys() if name[0] != '_' or name == '__name__'][:len(args)] # Sets provide a convienent way to identify intersections. duplicates = set(kw.keys()) & set(names) # Given duplicate values, explode gloriously. if duplicates: raise TypeError('{0} got multiple values for keyword argument{1}: {2}'.format( self.__class__.__name__, '' if len(duplicates) == 1 else 's', ', '.join(duplicates) )) def field_values(args, kw): """A little closure to yield out fields and their assigned values in field order.""" for i, arg in enumerate(self.__attributes__.keys()): if len(args): yield arg, args.popleft() if arg in kw: yield arg, kw.pop(arg) result = odict(field_values(deque(args), dict(kw))) # Again use sets, this time to identify unknown keys. unknown = set(kw.keys()) - set(result.keys()) # Given unknown keys, explode gloriously. if unknown: raise TypeError('{0} got unexpected keyword argument{1}: {2}'.format( self.__class__.__name__, '' if len(unknown) == 1 else 's', ', '.join(unknown) )) return result
[ "def", "_process_arguments", "(", "self", ",", "args", ",", "kw", ")", ":", "# Ensure we were not passed too many arguments.", "if", "len", "(", "args", ")", ">", "len", "(", "self", ".", "__attributes__", ")", ":", "raise", "TypeError", "(", "'{0} takes no more...
Map positional to keyword arguments, identify invalid assignments, and return the result. This is likely generic enough to be useful as a standalone utility function, and goes to a fair amount of effort to ensure raised exceptions are as Python-like as possible.
[ "Map", "positional", "to", "keyword", "arguments", "identify", "invalid", "assignments", "and", "return", "the", "result", ".", "This", "is", "likely", "generic", "enough", "to", "be", "useful", "as", "a", "standalone", "utility", "function", "and", "goes", "t...
train
https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/declarative.py#L51-L104
kalefranz/auxlib
auxlib/deprecation.py
import_and_wrap_deprecated
def import_and_wrap_deprecated(module_name, module_dict, warn_import=True): """ Usage: import_and_wrap_deprecated('conda.common.connection', locals()) # looks for conda.common.connection.__all__ """ if warn_import: deprecated_import(module_name) from importlib import import_module module = import_module(module_name) for attr in module.__all__: module_dict[attr] = deprecated(getattr(module, attr))
python
def import_and_wrap_deprecated(module_name, module_dict, warn_import=True): """ Usage: import_and_wrap_deprecated('conda.common.connection', locals()) # looks for conda.common.connection.__all__ """ if warn_import: deprecated_import(module_name) from importlib import import_module module = import_module(module_name) for attr in module.__all__: module_dict[attr] = deprecated(getattr(module, attr))
[ "def", "import_and_wrap_deprecated", "(", "module_name", ",", "module_dict", ",", "warn_import", "=", "True", ")", ":", "if", "warn_import", ":", "deprecated_import", "(", "module_name", ")", "from", "importlib", "import", "import_module", "module", "=", "import_mod...
Usage: import_and_wrap_deprecated('conda.common.connection', locals()) # looks for conda.common.connection.__all__
[ "Usage", ":", "import_and_wrap_deprecated", "(", "conda", ".", "common", ".", "connection", "locals", "()", ")", "#", "looks", "for", "conda", ".", "common", ".", "connection", ".", "__all__" ]
train
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/deprecation.py#L39-L51
kalefranz/auxlib
auxlib/deprecation.py
deprecate_module_with_proxy
def deprecate_module_with_proxy(module_name, module_dict, deprecated_attributes=None): """ Usage: deprecate_module_with_proxy(__name__, locals()) # at bottom of module """ def _ModuleProxy(module, depr): """Return a wrapped object that warns about deprecated accesses""" # http://stackoverflow.com/a/922693/2127762 class Wrapper(object): def __getattr__(self, attr): if depr is None or attr in depr: warnings.warn("Property %s is deprecated" % attr) return getattr(module, attr) def __setattr__(self, attr, value): if depr is None or attr in depr: warnings.warn("Property %s is deprecated" % attr) return setattr(module, attr, value) return Wrapper() deprecated_import(module_name) deprs = set() for key in deprecated_attributes or module_dict: if key.startswith('_'): continue if callable(module_dict[key]) and not isbuiltin(module_dict[key]): module_dict[key] = deprecated(module_dict[key]) else: deprs.add(key) sys.modules[module_name] = _ModuleProxy(sys.modules[module_name], deprs or None)
python
def deprecate_module_with_proxy(module_name, module_dict, deprecated_attributes=None): """ Usage: deprecate_module_with_proxy(__name__, locals()) # at bottom of module """ def _ModuleProxy(module, depr): """Return a wrapped object that warns about deprecated accesses""" # http://stackoverflow.com/a/922693/2127762 class Wrapper(object): def __getattr__(self, attr): if depr is None or attr in depr: warnings.warn("Property %s is deprecated" % attr) return getattr(module, attr) def __setattr__(self, attr, value): if depr is None or attr in depr: warnings.warn("Property %s is deprecated" % attr) return setattr(module, attr, value) return Wrapper() deprecated_import(module_name) deprs = set() for key in deprecated_attributes or module_dict: if key.startswith('_'): continue if callable(module_dict[key]) and not isbuiltin(module_dict[key]): module_dict[key] = deprecated(module_dict[key]) else: deprs.add(key) sys.modules[module_name] = _ModuleProxy(sys.modules[module_name], deprs or None)
[ "def", "deprecate_module_with_proxy", "(", "module_name", ",", "module_dict", ",", "deprecated_attributes", "=", "None", ")", ":", "def", "_ModuleProxy", "(", "module", ",", "depr", ")", ":", "\"\"\"Return a wrapped object that warns about deprecated accesses\"\"\"", "# htt...
Usage: deprecate_module_with_proxy(__name__, locals()) # at bottom of module
[ "Usage", ":", "deprecate_module_with_proxy", "(", "__name__", "locals", "()", ")", "#", "at", "bottom", "of", "module" ]
train
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/deprecation.py#L54-L85
marrow/schema
marrow/schema/transform/type.py
Boolean.native
def native(self, value, context=None): """Convert a foreign value to a native boolean.""" value = super().native(value, context) if self.none and (value is None): return None try: value = value.lower() except AttributeError: return bool(value) if value in self.truthy: return True if value in self.falsy: return False raise Concern("Unable to convert {0!r} to a boolean value.", value)
python
def native(self, value, context=None): """Convert a foreign value to a native boolean.""" value = super().native(value, context) if self.none and (value is None): return None try: value = value.lower() except AttributeError: return bool(value) if value in self.truthy: return True if value in self.falsy: return False raise Concern("Unable to convert {0!r} to a boolean value.", value)
[ "def", "native", "(", "self", ",", "value", ",", "context", "=", "None", ")", ":", "value", "=", "super", "(", ")", ".", "native", "(", "value", ",", "context", ")", "if", "self", ".", "none", "and", "(", "value", "is", "None", ")", ":", "return"...
Convert a foreign value to a native boolean.
[ "Convert", "a", "foreign", "value", "to", "a", "native", "boolean", "." ]
train
https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/type.py#L22-L41
marrow/schema
marrow/schema/transform/type.py
Boolean.foreign
def foreign(self, value, context=None): """Convert a native value to a textual boolean.""" if self.none and value is None: return '' try: value = self.native(value, context) except Concern: # The value might not be in the lists; bool() evaluate it instead. value = bool(value.strip() if self.strip and hasattr(value, 'strip') else value) if value in self.truthy or value: return self.truthy[self.use] return self.falsy[self.use]
python
def foreign(self, value, context=None): """Convert a native value to a textual boolean.""" if self.none and value is None: return '' try: value = self.native(value, context) except Concern: # The value might not be in the lists; bool() evaluate it instead. value = bool(value.strip() if self.strip and hasattr(value, 'strip') else value) if value in self.truthy or value: return self.truthy[self.use] return self.falsy[self.use]
[ "def", "foreign", "(", "self", ",", "value", ",", "context", "=", "None", ")", ":", "if", "self", ".", "none", "and", "value", "is", "None", ":", "return", "''", "try", ":", "value", "=", "self", ".", "native", "(", "value", ",", "context", ")", ...
Convert a native value to a textual boolean.
[ "Convert", "a", "native", "value", "to", "a", "textual", "boolean", "." ]
train
https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/type.py#L43-L58
cloudsmith-io/cloudsmith-cli
setup.py
get_root_path
def get_root_path(): """Get the root path for the application.""" root_path = __file__ return os.path.dirname(os.path.realpath(root_path))
python
def get_root_path(): """Get the root path for the application.""" root_path = __file__ return os.path.dirname(os.path.realpath(root_path))
[ "def", "get_root_path", "(", ")", ":", "root_path", "=", "__file__", "return", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "root_path", ")", ")" ]
Get the root path for the application.
[ "Get", "the", "root", "path", "for", "the", "application", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/setup.py#L10-L13
cloudsmith-io/cloudsmith-cli
setup.py
read
def read(path, root_path=None): """Read the specific file into a string in its entirety.""" try: root_path = root_path or get_root_path() real_path = os.path.realpath(os.path.join(root_path, path)) with open(real_path) as fp: return fp.read().strip() except IOError: return ""
python
def read(path, root_path=None): """Read the specific file into a string in its entirety.""" try: root_path = root_path or get_root_path() real_path = os.path.realpath(os.path.join(root_path, path)) with open(real_path) as fp: return fp.read().strip() except IOError: return ""
[ "def", "read", "(", "path", ",", "root_path", "=", "None", ")", ":", "try", ":", "root_path", "=", "root_path", "or", "get_root_path", "(", ")", "real_path", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "root_pat...
Read the specific file into a string in its entirety.
[ "Read", "the", "specific", "file", "into", "a", "string", "in", "its", "entirety", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/setup.py#L16-L24
cloudsmith-io/cloudsmith-cli
setup.py
get_long_description
def get_long_description(): """Grok the readme, turn it into whine (rst).""" root_path = get_root_path() readme_path = os.path.join(root_path, "README.md") try: import pypandoc return pypandoc.convert(readme_path, "rst").strip() except ImportError: return "Cloudsmith CLI"
python
def get_long_description(): """Grok the readme, turn it into whine (rst).""" root_path = get_root_path() readme_path = os.path.join(root_path, "README.md") try: import pypandoc return pypandoc.convert(readme_path, "rst").strip() except ImportError: return "Cloudsmith CLI"
[ "def", "get_long_description", "(", ")", ":", "root_path", "=", "get_root_path", "(", ")", "readme_path", "=", "os", ".", "path", ".", "join", "(", "root_path", ",", "\"README.md\"", ")", "try", ":", "import", "pypandoc", "return", "pypandoc", ".", "convert"...
Grok the readme, turn it into whine (rst).
[ "Grok", "the", "readme", "turn", "it", "into", "whine", "(", "rst", ")", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/setup.py#L27-L37
skulumani/kinematics
kinematics/sphere.py
rand
def rand(n, **kwargs): """Random vector from the n-Sphere This function will return a random vector which is an element of the n-Sphere. The n-Sphere is defined as a vector in R^n+1 with a norm of one. Basically, we'll find a random vector in R^n+1 and normalize it. This uses the method of Marsaglia 1972. Parameters ---------- None Returns ------- rvec Random (n+1,) numpy vector with a norm of 1 """ rvec = np.random.randn(3) rvec = rvec / np.linalg.norm(rvec) return rvec
python
def rand(n, **kwargs): """Random vector from the n-Sphere This function will return a random vector which is an element of the n-Sphere. The n-Sphere is defined as a vector in R^n+1 with a norm of one. Basically, we'll find a random vector in R^n+1 and normalize it. This uses the method of Marsaglia 1972. Parameters ---------- None Returns ------- rvec Random (n+1,) numpy vector with a norm of 1 """ rvec = np.random.randn(3) rvec = rvec / np.linalg.norm(rvec) return rvec
[ "def", "rand", "(", "n", ",", "*", "*", "kwargs", ")", ":", "rvec", "=", "np", ".", "random", ".", "randn", "(", "3", ")", "rvec", "=", "rvec", "/", "np", ".", "linalg", ".", "norm", "(", "rvec", ")", "return", "rvec" ]
Random vector from the n-Sphere This function will return a random vector which is an element of the n-Sphere. The n-Sphere is defined as a vector in R^n+1 with a norm of one. Basically, we'll find a random vector in R^n+1 and normalize it. This uses the method of Marsaglia 1972. Parameters ---------- None Returns ------- rvec Random (n+1,) numpy vector with a norm of 1
[ "Random", "vector", "from", "the", "n", "-", "Sphere" ]
train
https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/sphere.py#L13-L34
skulumani/kinematics
kinematics/sphere.py
tan_rand
def tan_rand(q, seed=9): """Find a random vector in the tangent space of the n sphere This function will find a random orthogonal vector to q. Parameters ---------- q (n+1,) array which is in the n-sphere Returns ------- qd (n+1,) array which is orthogonal to n-sphere and also random """ # probably need a check in case we get a parallel vector rs = np.random.RandomState(seed) rvec = rs.rand(q.shape[0]) qd = np.cross(rvec, q) qd = qd / np.linalg.norm(qd) while np.dot(q, qd) > 1e-6: rvec = rs.rand(q.shape[0]) qd = np.cross(rvec, q) qd = qd / np.linalg.norm(qd) return qd
python
def tan_rand(q, seed=9): """Find a random vector in the tangent space of the n sphere This function will find a random orthogonal vector to q. Parameters ---------- q (n+1,) array which is in the n-sphere Returns ------- qd (n+1,) array which is orthogonal to n-sphere and also random """ # probably need a check in case we get a parallel vector rs = np.random.RandomState(seed) rvec = rs.rand(q.shape[0]) qd = np.cross(rvec, q) qd = qd / np.linalg.norm(qd) while np.dot(q, qd) > 1e-6: rvec = rs.rand(q.shape[0]) qd = np.cross(rvec, q) qd = qd / np.linalg.norm(qd) return qd
[ "def", "tan_rand", "(", "q", ",", "seed", "=", "9", ")", ":", "# probably need a check in case we get a parallel vector", "rs", "=", "np", ".", "random", ".", "RandomState", "(", "seed", ")", "rvec", "=", "rs", ".", "rand", "(", "q", ".", "shape", "[", "...
Find a random vector in the tangent space of the n sphere This function will find a random orthogonal vector to q. Parameters ---------- q (n+1,) array which is in the n-sphere Returns ------- qd (n+1,) array which is orthogonal to n-sphere and also random
[ "Find", "a", "random", "vector", "in", "the", "tangent", "space", "of", "the", "n", "sphere" ]
train
https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/sphere.py#L36-L64
skulumani/kinematics
kinematics/sphere.py
perturb_vec
def perturb_vec(q, cone_half_angle=2): r"""Perturb a vector randomly qp = perturb_vec(q, cone_half_angle=2) Parameters ---------- q : (n,) numpy array Vector to perturb cone_half_angle : float Maximum angle to perturb the vector in degrees Returns ------- perturbed : (n,) numpy array Perturbed numpy array Author ------ Shankar Kulumani GWU [email protected] References ---------- .. [1] https://stackoverflow.com/questions/2659257/perturb-vector-by-some-angle """ rand_vec = tan_rand(q) cross_vector = attitude.unit_vector(np.cross(q, rand_vec)) s = np.random.uniform(0, 1, 1) r = np.random.uniform(0, 1, 1) h = np.cos(np.deg2rad(cone_half_angle)) phi = 2 * np.pi * s z = h + ( 1- h) * r sinT = np.sqrt(1 - z**2) x = np.cos(phi) * sinT y = np.sin(phi) * sinT perturbed = rand_vec * x + cross_vector * y + q * z return perturbed
python
def perturb_vec(q, cone_half_angle=2): r"""Perturb a vector randomly qp = perturb_vec(q, cone_half_angle=2) Parameters ---------- q : (n,) numpy array Vector to perturb cone_half_angle : float Maximum angle to perturb the vector in degrees Returns ------- perturbed : (n,) numpy array Perturbed numpy array Author ------ Shankar Kulumani GWU [email protected] References ---------- .. [1] https://stackoverflow.com/questions/2659257/perturb-vector-by-some-angle """ rand_vec = tan_rand(q) cross_vector = attitude.unit_vector(np.cross(q, rand_vec)) s = np.random.uniform(0, 1, 1) r = np.random.uniform(0, 1, 1) h = np.cos(np.deg2rad(cone_half_angle)) phi = 2 * np.pi * s z = h + ( 1- h) * r sinT = np.sqrt(1 - z**2) x = np.cos(phi) * sinT y = np.sin(phi) * sinT perturbed = rand_vec * x + cross_vector * y + q * z return perturbed
[ "def", "perturb_vec", "(", "q", ",", "cone_half_angle", "=", "2", ")", ":", "rand_vec", "=", "tan_rand", "(", "q", ")", "cross_vector", "=", "attitude", ".", "unit_vector", "(", "np", ".", "cross", "(", "q", ",", "rand_vec", ")", ")", "s", "=", "np",...
r"""Perturb a vector randomly qp = perturb_vec(q, cone_half_angle=2) Parameters ---------- q : (n,) numpy array Vector to perturb cone_half_angle : float Maximum angle to perturb the vector in degrees Returns ------- perturbed : (n,) numpy array Perturbed numpy array Author ------ Shankar Kulumani GWU [email protected] References ---------- .. [1] https://stackoverflow.com/questions/2659257/perturb-vector-by-some-angle
[ "r", "Perturb", "a", "vector", "randomly" ]
train
https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/sphere.py#L66-L109
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/decorators.py
common_package_action_options
def common_package_action_options(f): """Add common options for package actions.""" @click.option( "-s", "--skip-errors", default=False, is_flag=True, help="Skip/ignore errors when copying packages.", ) @click.option( "-W", "--no-wait-for-sync", default=False, is_flag=True, help="Don't wait for package synchronisation to complete before " "exiting.", ) @click.option( "-I", "--wait-interval", default=5.0, type=float, show_default=True, help="The time in seconds to wait between checking synchronisation.", ) @click.option( "--sync-attempts", default=3, type=int, help="Number of times to attempt package synchronisation. If the " "package fails the first time, the client will attempt to " "automatically resynchronise it.", ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring return ctx.invoke(f, *args, **kwargs) return wrapper
python
def common_package_action_options(f): """Add common options for package actions.""" @click.option( "-s", "--skip-errors", default=False, is_flag=True, help="Skip/ignore errors when copying packages.", ) @click.option( "-W", "--no-wait-for-sync", default=False, is_flag=True, help="Don't wait for package synchronisation to complete before " "exiting.", ) @click.option( "-I", "--wait-interval", default=5.0, type=float, show_default=True, help="The time in seconds to wait between checking synchronisation.", ) @click.option( "--sync-attempts", default=3, type=int, help="Number of times to attempt package synchronisation. If the " "package fails the first time, the client will attempt to " "automatically resynchronise it.", ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring return ctx.invoke(f, *args, **kwargs) return wrapper
[ "def", "common_package_action_options", "(", "f", ")", ":", "@", "click", ".", "option", "(", "\"-s\"", ",", "\"--skip-errors\"", ",", "default", "=", "False", ",", "is_flag", "=", "True", ",", "help", "=", "\"Skip/ignore errors when copying packages.\"", ",", "...
Add common options for package actions.
[ "Add", "common", "options", "for", "package", "actions", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/decorators.py#L13-L52
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/decorators.py
common_cli_config_options
def common_cli_config_options(f): """Add common CLI config options to commands.""" @click.option( "-C", "--config-file", envvar="CLOUDSMITH_CONFIG_FILE", type=click.Path(dir_okay=True, exists=True, writable=False, resolve_path=True), help="The path to your config.ini file.", ) @click.option( "--credentials-file", envvar="CLOUDSMITH_CREDENTIALS_FILE", type=click.Path(dir_okay=True, exists=True, writable=False, resolve_path=True), help="The path to your credentials.ini file.", ) @click.option( "-P", "--profile", default=None, envvar="CLOUDSMITH_PROFILE", help="The name of the profile to use for configuration.", ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring opts = config.get_or_create_options(ctx) profile = kwargs.pop("profile") config_file = kwargs.pop("config_file") creds_file = kwargs.pop("credentials_file") opts.load_config_file(path=config_file, profile=profile) opts.load_creds_file(path=creds_file, profile=profile) kwargs["opts"] = opts return ctx.invoke(f, *args, **kwargs) return wrapper
python
def common_cli_config_options(f): """Add common CLI config options to commands.""" @click.option( "-C", "--config-file", envvar="CLOUDSMITH_CONFIG_FILE", type=click.Path(dir_okay=True, exists=True, writable=False, resolve_path=True), help="The path to your config.ini file.", ) @click.option( "--credentials-file", envvar="CLOUDSMITH_CREDENTIALS_FILE", type=click.Path(dir_okay=True, exists=True, writable=False, resolve_path=True), help="The path to your credentials.ini file.", ) @click.option( "-P", "--profile", default=None, envvar="CLOUDSMITH_PROFILE", help="The name of the profile to use for configuration.", ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring opts = config.get_or_create_options(ctx) profile = kwargs.pop("profile") config_file = kwargs.pop("config_file") creds_file = kwargs.pop("credentials_file") opts.load_config_file(path=config_file, profile=profile) opts.load_creds_file(path=creds_file, profile=profile) kwargs["opts"] = opts return ctx.invoke(f, *args, **kwargs) return wrapper
[ "def", "common_cli_config_options", "(", "f", ")", ":", "@", "click", ".", "option", "(", "\"-C\"", ",", "\"--config-file\"", ",", "envvar", "=", "\"CLOUDSMITH_CONFIG_FILE\"", ",", "type", "=", "click", ".", "Path", "(", "dir_okay", "=", "True", ",", "exists...
Add common CLI config options to commands.
[ "Add", "common", "CLI", "config", "options", "to", "commands", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/decorators.py#L55-L91
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/decorators.py
common_cli_output_options
def common_cli_output_options(f): """Add common CLI output options to commands.""" @click.option( "-d", "--debug", default=False, is_flag=True, help="Produce debug output during processing.", ) @click.option( "-F", "--output-format", default="pretty", type=click.Choice(["pretty", "json", "pretty_json"]), help="Determines how output is formatted. This is only supported by a " "subset of the commands at the moment (e.g. list).", ) @click.option( "-v", "--verbose", is_flag=True, default=False, help="Produce more output during processing.", ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring opts = config.get_or_create_options(ctx) opts.debug = kwargs.pop("debug") opts.output = kwargs.pop("output_format") opts.verbose = kwargs.pop("verbose") kwargs["opts"] = opts return ctx.invoke(f, *args, **kwargs) return wrapper
python
def common_cli_output_options(f): """Add common CLI output options to commands.""" @click.option( "-d", "--debug", default=False, is_flag=True, help="Produce debug output during processing.", ) @click.option( "-F", "--output-format", default="pretty", type=click.Choice(["pretty", "json", "pretty_json"]), help="Determines how output is formatted. This is only supported by a " "subset of the commands at the moment (e.g. list).", ) @click.option( "-v", "--verbose", is_flag=True, default=False, help="Produce more output during processing.", ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring opts = config.get_or_create_options(ctx) opts.debug = kwargs.pop("debug") opts.output = kwargs.pop("output_format") opts.verbose = kwargs.pop("verbose") kwargs["opts"] = opts return ctx.invoke(f, *args, **kwargs) return wrapper
[ "def", "common_cli_output_options", "(", "f", ")", ":", "@", "click", ".", "option", "(", "\"-d\"", ",", "\"--debug\"", ",", "default", "=", "False", ",", "is_flag", "=", "True", ",", "help", "=", "\"Produce debug output during processing.\"", ",", ")", "@", ...
Add common CLI output options to commands.
[ "Add", "common", "CLI", "output", "options", "to", "commands", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/decorators.py#L94-L130
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/decorators.py
common_cli_list_options
def common_cli_list_options(f): """Add common list options to commands.""" @click.option( "-p", "--page", default=1, type=int, help="The page to view for lists, where 1 is the first page", callback=validators.validate_page, ) @click.option( "-l", "--page-size", default=30, type=int, help="The amount of items to view per page for lists.", callback=validators.validate_page_size, ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring opts = config.get_or_create_options(ctx) kwargs["opts"] = opts return ctx.invoke(f, *args, **kwargs) return wrapper
python
def common_cli_list_options(f): """Add common list options to commands.""" @click.option( "-p", "--page", default=1, type=int, help="The page to view for lists, where 1 is the first page", callback=validators.validate_page, ) @click.option( "-l", "--page-size", default=30, type=int, help="The amount of items to view per page for lists.", callback=validators.validate_page_size, ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring opts = config.get_or_create_options(ctx) kwargs["opts"] = opts return ctx.invoke(f, *args, **kwargs) return wrapper
[ "def", "common_cli_list_options", "(", "f", ")", ":", "@", "click", ".", "option", "(", "\"-p\"", ",", "\"--page\"", ",", "default", "=", "1", ",", "type", "=", "int", ",", "help", "=", "\"The page to view for lists, where 1 is the first page\"", ",", "callback"...
Add common list options to commands.
[ "Add", "common", "list", "options", "to", "commands", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/decorators.py#L133-L160
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/decorators.py
common_api_auth_options
def common_api_auth_options(f): """Add common API authentication options to commands.""" @click.option( "-k", "--api-key", hide_input=True, envvar="CLOUDSMITH_API_KEY", help="The API key for authenticating with the API.", ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring opts = config.get_or_create_options(ctx) opts.api_key = kwargs.pop("api_key") kwargs["opts"] = opts return ctx.invoke(f, *args, **kwargs) return wrapper
python
def common_api_auth_options(f): """Add common API authentication options to commands.""" @click.option( "-k", "--api-key", hide_input=True, envvar="CLOUDSMITH_API_KEY", help="The API key for authenticating with the API.", ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring opts = config.get_or_create_options(ctx) opts.api_key = kwargs.pop("api_key") kwargs["opts"] = opts return ctx.invoke(f, *args, **kwargs) return wrapper
[ "def", "common_api_auth_options", "(", "f", ")", ":", "@", "click", ".", "option", "(", "\"-k\"", ",", "\"--api-key\"", ",", "hide_input", "=", "True", ",", "envvar", "=", "\"CLOUDSMITH_API_KEY\"", ",", "help", "=", "\"The API key for authenticating with the API.\""...
Add common API authentication options to commands.
[ "Add", "common", "API", "authentication", "options", "to", "commands", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/decorators.py#L163-L182
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/decorators.py
initialise_api
def initialise_api(f): """Initialise the Cloudsmith API for use.""" @click.option( "--api-host", envvar="CLOUDSMITH_API_HOST", help="The API host to connect to." ) @click.option( "--api-proxy", envvar="CLOUDSMITH_API_PROXY", help="The API proxy to connect through.", ) @click.option( "--api-user-agent", envvar="CLOUDSMITH_API_USER_AGENT", help="The user agent to use for requests.", ) @click.option( "--api-headers", envvar="CLOUDSMITH_API_HEADERS", help="A CSV list of extra headers (key=value) to send to the API.", ) @click.option( "-R", "--without-rate-limit", default=False, is_flag=True, help="Don't obey the suggested rate limit interval. The CLI will " "automatically sleep between commands to ensure that you do " "not hit the server-side rate limit.", ) @click.option( "--rate-limit-warning", default=30, help="When rate limiting, display information that it is happening " "if wait interval is higher than this setting. By default no " "information will be printed. Set to zero to always see it.", ) @click.option( "--error-retry-max", default=6, help="The maximum amount of times to retry on errors received from " "the API, as determined by the --error-retry-codes parameter.", ) @click.option( "--error-retry-backoff", default=0.23, type=float, help="The backoff factor determines how long to wait in seconds " "between error retries. The backoff factor is multiplied by the " "amount of retries so far. So if 0.1, then the wait is 0.1s then " "0.2s, then 0.4s, and so forth.", ) @click.option( "--error-retry-codes", default="500,502,503,504", help="The status codes that when received from the API will cause " "a retry (if --error-retry-max is > 0). By default this will be for " "500, 502, 503 and 504 error codes.", ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring opts = config.get_or_create_options(ctx) opts.api_host = kwargs.pop("api_host") opts.api_proxy = kwargs.pop("api_proxy") opts.api_user_agent = kwargs.pop("api_user_agent") opts.api_headers = kwargs.pop("api_headers") opts.rate_limit = not kwargs.pop("without_rate_limit") opts.rate_limit_warning = kwargs.pop("rate_limit_warning") opts.error_retry_max = kwargs.pop("error_retry_max") opts.error_retry_backoff = kwargs.pop("error_retry_backoff") opts.error_retry_codes = kwargs.pop("error_retry_codes") def call_print_rate_limit_info_with_opts(rate_info, atexit=False): utils.print_rate_limit_info(opts, rate_info, atexit=atexit) opts.api_config = _initialise_api( debug=opts.debug, host=opts.api_host, key=opts.api_key, proxy=opts.api_proxy, user_agent=opts.api_user_agent, headers=opts.api_headers, rate_limit=opts.rate_limit, rate_limit_callback=call_print_rate_limit_info_with_opts, error_retry_max=opts.error_retry_max, error_retry_backoff=opts.error_retry_backoff, error_retry_codes=opts.error_retry_codes, ) kwargs["opts"] = opts return ctx.invoke(f, *args, **kwargs) return wrapper
python
def initialise_api(f): """Initialise the Cloudsmith API for use.""" @click.option( "--api-host", envvar="CLOUDSMITH_API_HOST", help="The API host to connect to." ) @click.option( "--api-proxy", envvar="CLOUDSMITH_API_PROXY", help="The API proxy to connect through.", ) @click.option( "--api-user-agent", envvar="CLOUDSMITH_API_USER_AGENT", help="The user agent to use for requests.", ) @click.option( "--api-headers", envvar="CLOUDSMITH_API_HEADERS", help="A CSV list of extra headers (key=value) to send to the API.", ) @click.option( "-R", "--without-rate-limit", default=False, is_flag=True, help="Don't obey the suggested rate limit interval. The CLI will " "automatically sleep between commands to ensure that you do " "not hit the server-side rate limit.", ) @click.option( "--rate-limit-warning", default=30, help="When rate limiting, display information that it is happening " "if wait interval is higher than this setting. By default no " "information will be printed. Set to zero to always see it.", ) @click.option( "--error-retry-max", default=6, help="The maximum amount of times to retry on errors received from " "the API, as determined by the --error-retry-codes parameter.", ) @click.option( "--error-retry-backoff", default=0.23, type=float, help="The backoff factor determines how long to wait in seconds " "between error retries. The backoff factor is multiplied by the " "amount of retries so far. So if 0.1, then the wait is 0.1s then " "0.2s, then 0.4s, and so forth.", ) @click.option( "--error-retry-codes", default="500,502,503,504", help="The status codes that when received from the API will cause " "a retry (if --error-retry-max is > 0). By default this will be for " "500, 502, 503 and 504 error codes.", ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring opts = config.get_or_create_options(ctx) opts.api_host = kwargs.pop("api_host") opts.api_proxy = kwargs.pop("api_proxy") opts.api_user_agent = kwargs.pop("api_user_agent") opts.api_headers = kwargs.pop("api_headers") opts.rate_limit = not kwargs.pop("without_rate_limit") opts.rate_limit_warning = kwargs.pop("rate_limit_warning") opts.error_retry_max = kwargs.pop("error_retry_max") opts.error_retry_backoff = kwargs.pop("error_retry_backoff") opts.error_retry_codes = kwargs.pop("error_retry_codes") def call_print_rate_limit_info_with_opts(rate_info, atexit=False): utils.print_rate_limit_info(opts, rate_info, atexit=atexit) opts.api_config = _initialise_api( debug=opts.debug, host=opts.api_host, key=opts.api_key, proxy=opts.api_proxy, user_agent=opts.api_user_agent, headers=opts.api_headers, rate_limit=opts.rate_limit, rate_limit_callback=call_print_rate_limit_info_with_opts, error_retry_max=opts.error_retry_max, error_retry_backoff=opts.error_retry_backoff, error_retry_codes=opts.error_retry_codes, ) kwargs["opts"] = opts return ctx.invoke(f, *args, **kwargs) return wrapper
[ "def", "initialise_api", "(", "f", ")", ":", "@", "click", ".", "option", "(", "\"--api-host\"", ",", "envvar", "=", "\"CLOUDSMITH_API_HOST\"", ",", "help", "=", "\"The API host to connect to.\"", ")", "@", "click", ".", "option", "(", "\"--api-proxy\"", ",", ...
Initialise the Cloudsmith API for use.
[ "Initialise", "the", "Cloudsmith", "API", "for", "use", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/decorators.py#L185-L279
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/api/entitlements.py
list_entitlements
def list_entitlements(owner, repo, page, page_size, show_tokens): """Get a list of entitlements on a repository.""" client = get_entitlements_api() with catch_raise_api_exception(): data, _, headers = client.entitlements_list_with_http_info( owner=owner, repo=repo, page=page, page_size=page_size, show_tokens=show_tokens, ) ratelimits.maybe_rate_limit(client, headers) page_info = PageInfo.from_headers(headers) entitlements = [ent.to_dict() for ent in data] # pylint: disable=no-member return entitlements, page_info
python
def list_entitlements(owner, repo, page, page_size, show_tokens): """Get a list of entitlements on a repository.""" client = get_entitlements_api() with catch_raise_api_exception(): data, _, headers = client.entitlements_list_with_http_info( owner=owner, repo=repo, page=page, page_size=page_size, show_tokens=show_tokens, ) ratelimits.maybe_rate_limit(client, headers) page_info = PageInfo.from_headers(headers) entitlements = [ent.to_dict() for ent in data] # pylint: disable=no-member return entitlements, page_info
[ "def", "list_entitlements", "(", "owner", ",", "repo", ",", "page", ",", "page_size", ",", "show_tokens", ")", ":", "client", "=", "get_entitlements_api", "(", ")", "with", "catch_raise_api_exception", "(", ")", ":", "data", ",", "_", ",", "headers", "=", ...
Get a list of entitlements on a repository.
[ "Get", "a", "list", "of", "entitlements", "on", "a", "repository", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/entitlements.py#L18-L34
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/api/entitlements.py
create_entitlement
def create_entitlement(owner, repo, name, token, show_tokens): """Create an entitlement in a repository.""" client = get_entitlements_api() data = {} if name is not None: data["name"] = name if token is not None: data["token"] = token with catch_raise_api_exception(): data, _, headers = client.entitlements_create_with_http_info( owner=owner, repo=repo, data=data, show_tokens=show_tokens ) ratelimits.maybe_rate_limit(client, headers) return data.to_dict()
python
def create_entitlement(owner, repo, name, token, show_tokens): """Create an entitlement in a repository.""" client = get_entitlements_api() data = {} if name is not None: data["name"] = name if token is not None: data["token"] = token with catch_raise_api_exception(): data, _, headers = client.entitlements_create_with_http_info( owner=owner, repo=repo, data=data, show_tokens=show_tokens ) ratelimits.maybe_rate_limit(client, headers) return data.to_dict()
[ "def", "create_entitlement", "(", "owner", ",", "repo", ",", "name", ",", "token", ",", "show_tokens", ")", ":", "client", "=", "get_entitlements_api", "(", ")", "data", "=", "{", "}", "if", "name", "is", "not", "None", ":", "data", "[", "\"name\"", "]...
Create an entitlement in a repository.
[ "Create", "an", "entitlement", "in", "a", "repository", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/entitlements.py#L37-L54
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/api/entitlements.py
delete_entitlement
def delete_entitlement(owner, repo, identifier): """Delete an entitlement from a repository.""" client = get_entitlements_api() with catch_raise_api_exception(): _, _, headers = client.entitlements_delete_with_http_info( owner=owner, repo=repo, identifier=identifier ) ratelimits.maybe_rate_limit(client, headers)
python
def delete_entitlement(owner, repo, identifier): """Delete an entitlement from a repository.""" client = get_entitlements_api() with catch_raise_api_exception(): _, _, headers = client.entitlements_delete_with_http_info( owner=owner, repo=repo, identifier=identifier ) ratelimits.maybe_rate_limit(client, headers)
[ "def", "delete_entitlement", "(", "owner", ",", "repo", ",", "identifier", ")", ":", "client", "=", "get_entitlements_api", "(", ")", "with", "catch_raise_api_exception", "(", ")", ":", "_", ",", "_", ",", "headers", "=", "client", ".", "entitlements_delete_wi...
Delete an entitlement from a repository.
[ "Delete", "an", "entitlement", "from", "a", "repository", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/entitlements.py#L57-L66
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/api/entitlements.py
update_entitlement
def update_entitlement(owner, repo, identifier, name, token, show_tokens): """Update an entitlement in a repository.""" client = get_entitlements_api() data = {} if name is not None: data["name"] = name if token is not None: data["token"] = token with catch_raise_api_exception(): data, _, headers = client.entitlements_partial_update_with_http_info( owner=owner, repo=repo, identifier=identifier, data=data, show_tokens=show_tokens, ) ratelimits.maybe_rate_limit(client, headers) return data.to_dict()
python
def update_entitlement(owner, repo, identifier, name, token, show_tokens): """Update an entitlement in a repository.""" client = get_entitlements_api() data = {} if name is not None: data["name"] = name if token is not None: data["token"] = token with catch_raise_api_exception(): data, _, headers = client.entitlements_partial_update_with_http_info( owner=owner, repo=repo, identifier=identifier, data=data, show_tokens=show_tokens, ) ratelimits.maybe_rate_limit(client, headers) return data.to_dict()
[ "def", "update_entitlement", "(", "owner", ",", "repo", ",", "identifier", ",", "name", ",", "token", ",", "show_tokens", ")", ":", "client", "=", "get_entitlements_api", "(", ")", "data", "=", "{", "}", "if", "name", "is", "not", "None", ":", "data", ...
Update an entitlement in a repository.
[ "Update", "an", "entitlement", "in", "a", "repository", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/entitlements.py#L69-L90
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/api/entitlements.py
refresh_entitlement
def refresh_entitlement(owner, repo, identifier, show_tokens): """Refresh an entitlement in a repository.""" client = get_entitlements_api() with catch_raise_api_exception(): data, _, headers = client.entitlements_refresh_with_http_info( owner=owner, repo=repo, identifier=identifier, show_tokens=show_tokens ) ratelimits.maybe_rate_limit(client, headers) return data.to_dict()
python
def refresh_entitlement(owner, repo, identifier, show_tokens): """Refresh an entitlement in a repository.""" client = get_entitlements_api() with catch_raise_api_exception(): data, _, headers = client.entitlements_refresh_with_http_info( owner=owner, repo=repo, identifier=identifier, show_tokens=show_tokens ) ratelimits.maybe_rate_limit(client, headers) return data.to_dict()
[ "def", "refresh_entitlement", "(", "owner", ",", "repo", ",", "identifier", ",", "show_tokens", ")", ":", "client", "=", "get_entitlements_api", "(", ")", "with", "catch_raise_api_exception", "(", ")", ":", "data", ",", "_", ",", "headers", "=", "client", "....
Refresh an entitlement in a repository.
[ "Refresh", "an", "entitlement", "in", "a", "repository", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/entitlements.py#L93-L103
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/api/entitlements.py
sync_entitlements
def sync_entitlements(owner, repo, source, show_tokens): """Sync entitlements from another repository.""" client = get_entitlements_api() with catch_raise_api_exception(): data, _, headers = client.entitlements_sync_with_http_info( owner=owner, repo=repo, data={"source": source}, show_tokens=show_tokens ) ratelimits.maybe_rate_limit(client, headers) page_info = PageInfo.from_headers(headers) entitlements = [ent.to_dict() for ent in data.tokens] return entitlements, page_info
python
def sync_entitlements(owner, repo, source, show_tokens): """Sync entitlements from another repository.""" client = get_entitlements_api() with catch_raise_api_exception(): data, _, headers = client.entitlements_sync_with_http_info( owner=owner, repo=repo, data={"source": source}, show_tokens=show_tokens ) ratelimits.maybe_rate_limit(client, headers) page_info = PageInfo.from_headers(headers) entitlements = [ent.to_dict() for ent in data.tokens] return entitlements, page_info
[ "def", "sync_entitlements", "(", "owner", ",", "repo", ",", "source", ",", "show_tokens", ")", ":", "client", "=", "get_entitlements_api", "(", ")", "with", "catch_raise_api_exception", "(", ")", ":", "data", ",", "_", ",", "headers", "=", "client", ".", "...
Sync entitlements from another repository.
[ "Sync", "entitlements", "from", "another", "repository", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/entitlements.py#L106-L118
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/api/init.py
initialise_api
def initialise_api( debug=False, host=None, key=None, proxy=None, user_agent=None, headers=None, rate_limit=True, rate_limit_callback=None, error_retry_max=None, error_retry_backoff=None, error_retry_codes=None, ): """Initialise the API.""" config = cloudsmith_api.Configuration() config.debug = debug config.host = host if host else config.host config.proxy = proxy if proxy else config.proxy config.user_agent = user_agent config.headers = headers config.rate_limit = rate_limit config.rate_limit_callback = rate_limit_callback config.error_retry_max = error_retry_max config.error_retry_backoff = error_retry_backoff config.error_retry_codes = error_retry_codes if headers: if "Authorization" in config.headers: encoded = config.headers["Authorization"].split(" ")[1] decoded = base64.b64decode(encoded) values = decoded.decode("utf-8") config.username, config.password = values.split(":") set_api_key(config, key) return config
python
def initialise_api( debug=False, host=None, key=None, proxy=None, user_agent=None, headers=None, rate_limit=True, rate_limit_callback=None, error_retry_max=None, error_retry_backoff=None, error_retry_codes=None, ): """Initialise the API.""" config = cloudsmith_api.Configuration() config.debug = debug config.host = host if host else config.host config.proxy = proxy if proxy else config.proxy config.user_agent = user_agent config.headers = headers config.rate_limit = rate_limit config.rate_limit_callback = rate_limit_callback config.error_retry_max = error_retry_max config.error_retry_backoff = error_retry_backoff config.error_retry_codes = error_retry_codes if headers: if "Authorization" in config.headers: encoded = config.headers["Authorization"].split(" ")[1] decoded = base64.b64decode(encoded) values = decoded.decode("utf-8") config.username, config.password = values.split(":") set_api_key(config, key) return config
[ "def", "initialise_api", "(", "debug", "=", "False", ",", "host", "=", "None", ",", "key", "=", "None", ",", "proxy", "=", "None", ",", "user_agent", "=", "None", ",", "headers", "=", "None", ",", "rate_limit", "=", "True", ",", "rate_limit_callback", ...
Initialise the API.
[ "Initialise", "the", "API", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/init.py#L13-L47
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/api/init.py
get_api_client
def get_api_client(cls): """Get an API client (with configuration).""" config = cloudsmith_api.Configuration() client = cls() client.config = config client.api_client.rest_client = RestClient() user_agent = getattr(config, "user_agent", None) if user_agent: client.api_client.user_agent = user_agent headers = getattr(config, "headers", None) if headers: for k, v in six.iteritems(headers): client.api_client.set_default_header(k, v) return client
python
def get_api_client(cls): """Get an API client (with configuration).""" config = cloudsmith_api.Configuration() client = cls() client.config = config client.api_client.rest_client = RestClient() user_agent = getattr(config, "user_agent", None) if user_agent: client.api_client.user_agent = user_agent headers = getattr(config, "headers", None) if headers: for k, v in six.iteritems(headers): client.api_client.set_default_header(k, v) return client
[ "def", "get_api_client", "(", "cls", ")", ":", "config", "=", "cloudsmith_api", ".", "Configuration", "(", ")", "client", "=", "cls", "(", ")", "client", ".", "config", "=", "config", "client", ".", "api_client", ".", "rest_client", "=", "RestClient", "(",...
Get an API client (with configuration).
[ "Get", "an", "API", "client", "(", "with", "configuration", ")", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/init.py#L50-L66
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/api/init.py
set_api_key
def set_api_key(config, key): """Configure a new API key.""" if not key and "X-Api-Key" in config.api_key: del config.api_key["X-Api-Key"] else: config.api_key["X-Api-Key"] = key
python
def set_api_key(config, key): """Configure a new API key.""" if not key and "X-Api-Key" in config.api_key: del config.api_key["X-Api-Key"] else: config.api_key["X-Api-Key"] = key
[ "def", "set_api_key", "(", "config", ",", "key", ")", ":", "if", "not", "key", "and", "\"X-Api-Key\"", "in", "config", ".", "api_key", ":", "del", "config", ".", "api_key", "[", "\"X-Api-Key\"", "]", "else", ":", "config", ".", "api_key", "[", "\"X-Api-K...
Configure a new API key.
[ "Configure", "a", "new", "API", "key", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/init.py#L69-L74
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/api/files.py
validate_request_file_upload
def validate_request_file_upload(owner, repo, filepath, md5_checksum=None): """Validate parameters for requesting a file upload.""" client = get_files_api() md5_checksum = md5_checksum or calculate_file_md5(filepath) with catch_raise_api_exception(): _, _, headers = client.files_validate_with_http_info( owner=owner, repo=repo, data={"filename": os.path.basename(filepath), "md5_checksum": md5_checksum}, ) ratelimits.maybe_rate_limit(client, headers) return md5_checksum
python
def validate_request_file_upload(owner, repo, filepath, md5_checksum=None): """Validate parameters for requesting a file upload.""" client = get_files_api() md5_checksum = md5_checksum or calculate_file_md5(filepath) with catch_raise_api_exception(): _, _, headers = client.files_validate_with_http_info( owner=owner, repo=repo, data={"filename": os.path.basename(filepath), "md5_checksum": md5_checksum}, ) ratelimits.maybe_rate_limit(client, headers) return md5_checksum
[ "def", "validate_request_file_upload", "(", "owner", ",", "repo", ",", "filepath", ",", "md5_checksum", "=", "None", ")", ":", "client", "=", "get_files_api", "(", ")", "md5_checksum", "=", "md5_checksum", "or", "calculate_file_md5", "(", "filepath", ")", "with"...
Validate parameters for requesting a file upload.
[ "Validate", "parameters", "for", "requesting", "a", "file", "upload", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/files.py#L25-L38
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/api/files.py
request_file_upload
def request_file_upload(owner, repo, filepath, md5_checksum=None): """Request a new package file upload (for creating packages).""" client = get_files_api() md5_checksum = md5_checksum or calculate_file_md5(filepath) with catch_raise_api_exception(): data, _, headers = client.files_create_with_http_info( owner=owner, repo=repo, data={"filename": os.path.basename(filepath), "md5_checksum": md5_checksum}, ) # pylint: disable=no-member # Pylint detects the returned value as a tuple ratelimits.maybe_rate_limit(client, headers) return data.identifier, data.upload_url, data.upload_fields
python
def request_file_upload(owner, repo, filepath, md5_checksum=None): """Request a new package file upload (for creating packages).""" client = get_files_api() md5_checksum = md5_checksum or calculate_file_md5(filepath) with catch_raise_api_exception(): data, _, headers = client.files_create_with_http_info( owner=owner, repo=repo, data={"filename": os.path.basename(filepath), "md5_checksum": md5_checksum}, ) # pylint: disable=no-member # Pylint detects the returned value as a tuple ratelimits.maybe_rate_limit(client, headers) return data.identifier, data.upload_url, data.upload_fields
[ "def", "request_file_upload", "(", "owner", ",", "repo", ",", "filepath", ",", "md5_checksum", "=", "None", ")", ":", "client", "=", "get_files_api", "(", ")", "md5_checksum", "=", "md5_checksum", "or", "calculate_file_md5", "(", "filepath", ")", "with", "catc...
Request a new package file upload (for creating packages).
[ "Request", "a", "new", "package", "file", "upload", "(", "for", "creating", "packages", ")", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/files.py#L41-L56
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/api/files.py
upload_file
def upload_file(upload_url, upload_fields, filepath, callback=None): """Upload a pre-signed file to Cloudsmith.""" upload_fields = list(six.iteritems(upload_fields)) upload_fields.append( ("file", (os.path.basename(filepath), click.open_file(filepath, "rb"))) ) encoder = MultipartEncoder(upload_fields) monitor = MultipartEncoderMonitor(encoder, callback=callback) config = cloudsmith_api.Configuration() if config.proxy: proxies = {"http": config.proxy, "https": config.proxy} else: proxies = None headers = {"content-type": monitor.content_type} client = get_files_api() headers["user-agent"] = client.api_client.user_agent session = create_requests_session() resp = session.post(upload_url, data=monitor, headers=headers, proxies=proxies) try: resp.raise_for_status() except requests.RequestException as exc: raise ApiException( resp.status_code, headers=exc.response.headers, body=exc.response.content )
python
def upload_file(upload_url, upload_fields, filepath, callback=None): """Upload a pre-signed file to Cloudsmith.""" upload_fields = list(six.iteritems(upload_fields)) upload_fields.append( ("file", (os.path.basename(filepath), click.open_file(filepath, "rb"))) ) encoder = MultipartEncoder(upload_fields) monitor = MultipartEncoderMonitor(encoder, callback=callback) config = cloudsmith_api.Configuration() if config.proxy: proxies = {"http": config.proxy, "https": config.proxy} else: proxies = None headers = {"content-type": monitor.content_type} client = get_files_api() headers["user-agent"] = client.api_client.user_agent session = create_requests_session() resp = session.post(upload_url, data=monitor, headers=headers, proxies=proxies) try: resp.raise_for_status() except requests.RequestException as exc: raise ApiException( resp.status_code, headers=exc.response.headers, body=exc.response.content )
[ "def", "upload_file", "(", "upload_url", ",", "upload_fields", ",", "filepath", ",", "callback", "=", "None", ")", ":", "upload_fields", "=", "list", "(", "six", ".", "iteritems", "(", "upload_fields", ")", ")", "upload_fields", ".", "append", "(", "(", "\...
Upload a pre-signed file to Cloudsmith.
[ "Upload", "a", "pre", "-", "signed", "file", "to", "Cloudsmith", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/files.py#L59-L87
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/exceptions.py
handle_api_exceptions
def handle_api_exceptions( ctx, opts, context_msg=None, nl=False, exit_on_error=True, reraise_on_error=False ): """Context manager that handles API exceptions.""" # flake8: ignore=C901 # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" try: yield except ApiException as exc: if nl: click.echo(err=use_stderr) click.secho("ERROR: ", fg="red", nl=False, err=use_stderr) else: click.secho("ERROR", fg="red", err=use_stderr) context_msg = context_msg or "Failed to perform operation!" click.secho( "%(context)s (status: %(code)s - %(code_text)s)" % { "context": context_msg, "code": exc.status, "code_text": exc.status_description, }, fg="red", err=use_stderr, ) detail, fields = get_details(exc) if detail or fields: click.echo(err=use_stderr) if detail: click.secho( "Detail: %(detail)s" % {"detail": click.style(detail, fg="red", bold=False)}, bold=True, err=use_stderr, ) if fields: for k, v in six.iteritems(fields): field = "%s Field" % k.capitalize() click.secho( "%(field)s: %(message)s" % { "field": click.style(field, bold=True), "message": click.style(v, fg="red"), }, err=use_stderr, ) hint = get_error_hint(ctx, opts, exc) if hint: click.echo( "Hint: %(hint)s" % {"hint": click.style(hint, fg="yellow")}, err=use_stderr, ) if opts.verbose and not opts.debug: if exc.headers: click.echo(err=use_stderr) click.echo("Headers in Reply:", err=use_stderr) for k, v in six.iteritems(exc.headers): click.echo( "%(key)s = %(value)s" % {"key": k, "value": v}, err=use_stderr ) if reraise_on_error: six.reraise(*sys.exc_info()) if exit_on_error: ctx.exit(exc.status or 1)
python
def handle_api_exceptions( ctx, opts, context_msg=None, nl=False, exit_on_error=True, reraise_on_error=False ): """Context manager that handles API exceptions.""" # flake8: ignore=C901 # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" try: yield except ApiException as exc: if nl: click.echo(err=use_stderr) click.secho("ERROR: ", fg="red", nl=False, err=use_stderr) else: click.secho("ERROR", fg="red", err=use_stderr) context_msg = context_msg or "Failed to perform operation!" click.secho( "%(context)s (status: %(code)s - %(code_text)s)" % { "context": context_msg, "code": exc.status, "code_text": exc.status_description, }, fg="red", err=use_stderr, ) detail, fields = get_details(exc) if detail or fields: click.echo(err=use_stderr) if detail: click.secho( "Detail: %(detail)s" % {"detail": click.style(detail, fg="red", bold=False)}, bold=True, err=use_stderr, ) if fields: for k, v in six.iteritems(fields): field = "%s Field" % k.capitalize() click.secho( "%(field)s: %(message)s" % { "field": click.style(field, bold=True), "message": click.style(v, fg="red"), }, err=use_stderr, ) hint = get_error_hint(ctx, opts, exc) if hint: click.echo( "Hint: %(hint)s" % {"hint": click.style(hint, fg="yellow")}, err=use_stderr, ) if opts.verbose and not opts.debug: if exc.headers: click.echo(err=use_stderr) click.echo("Headers in Reply:", err=use_stderr) for k, v in six.iteritems(exc.headers): click.echo( "%(key)s = %(value)s" % {"key": k, "value": v}, err=use_stderr ) if reraise_on_error: six.reraise(*sys.exc_info()) if exit_on_error: ctx.exit(exc.status or 1)
[ "def", "handle_api_exceptions", "(", "ctx", ",", "opts", ",", "context_msg", "=", "None", ",", "nl", "=", "False", ",", "exit_on_error", "=", "True", ",", "reraise_on_error", "=", "False", ")", ":", "# flake8: ignore=C901", "# Use stderr for messages if the output i...
Context manager that handles API exceptions.
[ "Context", "manager", "that", "handles", "API", "exceptions", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/exceptions.py#L16-L89
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/exceptions.py
get_details
def get_details(exc): """Get the details from the exception.""" detail = None fields = collections.OrderedDict() if exc.detail: detail = exc.detail if exc.fields: for k, v in six.iteritems(exc.fields): try: field_detail = v["detail"] except (TypeError, KeyError): field_detail = v if isinstance(field_detail, (list, tuple)): field_detail = " ".join(field_detail) if k == "non_field_errors": if detail: detail += " " + field_detail else: detail = field_detail continue fields[k] = field_detail return detail, fields
python
def get_details(exc): """Get the details from the exception.""" detail = None fields = collections.OrderedDict() if exc.detail: detail = exc.detail if exc.fields: for k, v in six.iteritems(exc.fields): try: field_detail = v["detail"] except (TypeError, KeyError): field_detail = v if isinstance(field_detail, (list, tuple)): field_detail = " ".join(field_detail) if k == "non_field_errors": if detail: detail += " " + field_detail else: detail = field_detail continue fields[k] = field_detail return detail, fields
[ "def", "get_details", "(", "exc", ")", ":", "detail", "=", "None", "fields", "=", "collections", ".", "OrderedDict", "(", ")", "if", "exc", ".", "detail", ":", "detail", "=", "exc", ".", "detail", "if", "exc", ".", "fields", ":", "for", "k", ",", "...
Get the details from the exception.
[ "Get", "the", "details", "from", "the", "exception", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/exceptions.py#L92-L119
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/exceptions.py
get_error_hint
def get_error_hint(ctx, opts, exc): """Get a hint to show to the user (if any).""" module = sys.modules[__name__] get_specific_error_hint = getattr(module, "get_%s_error_hint" % exc.status, None) if get_specific_error_hint: return get_specific_error_hint(ctx, opts, exc) return None
python
def get_error_hint(ctx, opts, exc): """Get a hint to show to the user (if any).""" module = sys.modules[__name__] get_specific_error_hint = getattr(module, "get_%s_error_hint" % exc.status, None) if get_specific_error_hint: return get_specific_error_hint(ctx, opts, exc) return None
[ "def", "get_error_hint", "(", "ctx", ",", "opts", ",", "exc", ")", ":", "module", "=", "sys", ".", "modules", "[", "__name__", "]", "get_specific_error_hint", "=", "getattr", "(", "module", ",", "\"get_%s_error_hint\"", "%", "exc", ".", "status", ",", "Non...
Get a hint to show to the user (if any).
[ "Get", "a", "hint", "to", "show", "to", "the", "user", "(", "if", "any", ")", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/exceptions.py#L122-L128
kalefranz/auxlib
auxlib/configuration.py
make_env_key
def make_env_key(app_name, key): """Creates an environment key-equivalent for the given key""" key = key.replace('-', '_').replace(' ', '_') return str("_".join((x.upper() for x in (app_name, key))))
python
def make_env_key(app_name, key): """Creates an environment key-equivalent for the given key""" key = key.replace('-', '_').replace(' ', '_') return str("_".join((x.upper() for x in (app_name, key))))
[ "def", "make_env_key", "(", "app_name", ",", "key", ")", ":", "key", "=", "key", ".", "replace", "(", "'-'", ",", "'_'", ")", ".", "replace", "(", "' '", ",", "'_'", ")", "return", "str", "(", "\"_\"", ".", "join", "(", "(", "x", ".", "upper", ...
Creates an environment key-equivalent for the given key
[ "Creates", "an", "environment", "key", "-", "equivalent", "for", "the", "given", "key" ]
train
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/configuration.py#L45-L48
kalefranz/auxlib
auxlib/configuration.py
Configuration.set_env
def set_env(self, key, value): """Sets environment variables by prepending the app_name to `key`. Also registers the environment variable with the instance object preventing an otherwise-required call to `reload()`. """ os.environ[make_env_key(self.appname, key)] = str(value) # must coerce to string self._registered_env_keys.add(key) self._clear_memoization()
python
def set_env(self, key, value): """Sets environment variables by prepending the app_name to `key`. Also registers the environment variable with the instance object preventing an otherwise-required call to `reload()`. """ os.environ[make_env_key(self.appname, key)] = str(value) # must coerce to string self._registered_env_keys.add(key) self._clear_memoization()
[ "def", "set_env", "(", "self", ",", "key", ",", "value", ")", ":", "os", ".", "environ", "[", "make_env_key", "(", "self", ".", "appname", ",", "key", ")", "]", "=", "str", "(", "value", ")", "# must coerce to string", "self", ".", "_registered_env_keys"...
Sets environment variables by prepending the app_name to `key`. Also registers the environment variable with the instance object preventing an otherwise-required call to `reload()`.
[ "Sets", "environment", "variables", "by", "prepending", "the", "app_name", "to", "key", ".", "Also", "registers", "the", "environment", "variable", "with", "the", "instance", "object", "preventing", "an", "otherwise", "-", "required", "call", "to", "reload", "()...
train
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/configuration.py#L137-L144
kalefranz/auxlib
auxlib/configuration.py
Configuration.unset_env
def unset_env(self, key): """Removes an environment variable using the prepended app_name convention with `key`.""" os.environ.pop(make_env_key(self.appname, key), None) self._registered_env_keys.discard(key) self._clear_memoization()
python
def unset_env(self, key): """Removes an environment variable using the prepended app_name convention with `key`.""" os.environ.pop(make_env_key(self.appname, key), None) self._registered_env_keys.discard(key) self._clear_memoization()
[ "def", "unset_env", "(", "self", ",", "key", ")", ":", "os", ".", "environ", ".", "pop", "(", "make_env_key", "(", "self", ".", "appname", ",", "key", ")", ",", "None", ")", "self", ".", "_registered_env_keys", ".", "discard", "(", "key", ")", "self"...
Removes an environment variable using the prepended app_name convention with `key`.
[ "Removes", "an", "environment", "variable", "using", "the", "prepended", "app_name", "convention", "with", "key", "." ]
train
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/configuration.py#L146-L150
kalefranz/auxlib
auxlib/configuration.py
Configuration._reload
def _reload(self, force=False): """Reloads the configuration from the file and environment variables. Useful if using `os.environ` instead of this class' `set_env` method, or if the underlying configuration file is changed externally. """ self._config_map = dict() self._registered_env_keys = set() self.__reload_sources(force) self.__load_environment_keys() self.verify() self._clear_memoization()
python
def _reload(self, force=False): """Reloads the configuration from the file and environment variables. Useful if using `os.environ` instead of this class' `set_env` method, or if the underlying configuration file is changed externally. """ self._config_map = dict() self._registered_env_keys = set() self.__reload_sources(force) self.__load_environment_keys() self.verify() self._clear_memoization()
[ "def", "_reload", "(", "self", ",", "force", "=", "False", ")", ":", "self", ".", "_config_map", "=", "dict", "(", ")", "self", ".", "_registered_env_keys", "=", "set", "(", ")", "self", ".", "__reload_sources", "(", "force", ")", "self", ".", "__load_...
Reloads the configuration from the file and environment variables. Useful if using `os.environ` instead of this class' `set_env` method, or if the underlying configuration file is changed externally.
[ "Reloads", "the", "configuration", "from", "the", "file", "and", "environment", "variables", ".", "Useful", "if", "using", "os", ".", "environ", "instead", "of", "this", "class", "set_env", "method", "or", "if", "the", "underlying", "configuration", "file", "i...
train
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/configuration.py#L152-L162
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/move.py
move
def move( ctx, opts, owner_repo_package, destination, skip_errors, wait_interval, no_wait_for_sync, sync_attempts, yes, ): """ Move (promote) a package to another repo. This requires appropriate permissions for both the source repository/package and the destination repository. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the package itself. All separated by a slash. Example: 'your-org/awesome-repo/better-pkg'. - DEST: Specify the DEST (destination) repository to move the package to. This *must* be in the same namespace as the source repository. Example: 'other-repo' Full CLI example: $ cloudsmith mv your-org/awesome-repo/better-pkg other-repo """ owner, source, slug = owner_repo_package move_args = { "slug": click.style(slug, bold=True), "source": click.style(source, bold=True), "dest": click.style(destination, bold=True), } prompt = "move the %(slug)s from %(source)s to %(dest)s" % move_args if not utils.confirm_operation(prompt, assume_yes=yes): return click.echo( "Moving %(slug)s package from %(source)s to %(dest)s ... " % move_args, nl=False ) context_msg = "Failed to move package!" with handle_api_exceptions( ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors ): with maybe_spinner(opts): _, new_slug = move_package( owner=owner, repo=source, identifier=slug, destination=destination ) click.secho("OK", fg="green") if no_wait_for_sync: return wait_for_package_sync( ctx=ctx, opts=opts, owner=owner, repo=destination, slug=new_slug, wait_interval=wait_interval, skip_errors=skip_errors, attempts=sync_attempts, )
python
def move( ctx, opts, owner_repo_package, destination, skip_errors, wait_interval, no_wait_for_sync, sync_attempts, yes, ): """ Move (promote) a package to another repo. This requires appropriate permissions for both the source repository/package and the destination repository. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the package itself. All separated by a slash. Example: 'your-org/awesome-repo/better-pkg'. - DEST: Specify the DEST (destination) repository to move the package to. This *must* be in the same namespace as the source repository. Example: 'other-repo' Full CLI example: $ cloudsmith mv your-org/awesome-repo/better-pkg other-repo """ owner, source, slug = owner_repo_package move_args = { "slug": click.style(slug, bold=True), "source": click.style(source, bold=True), "dest": click.style(destination, bold=True), } prompt = "move the %(slug)s from %(source)s to %(dest)s" % move_args if not utils.confirm_operation(prompt, assume_yes=yes): return click.echo( "Moving %(slug)s package from %(source)s to %(dest)s ... " % move_args, nl=False ) context_msg = "Failed to move package!" with handle_api_exceptions( ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors ): with maybe_spinner(opts): _, new_slug = move_package( owner=owner, repo=source, identifier=slug, destination=destination ) click.secho("OK", fg="green") if no_wait_for_sync: return wait_for_package_sync( ctx=ctx, opts=opts, owner=owner, repo=destination, slug=new_slug, wait_interval=wait_interval, skip_errors=skip_errors, attempts=sync_attempts, )
[ "def", "move", "(", "ctx", ",", "opts", ",", "owner_repo_package", ",", "destination", ",", "skip_errors", ",", "wait_interval", ",", "no_wait_for_sync", ",", "sync_attempts", ",", "yes", ",", ")", ":", "owner", ",", "source", ",", "slug", "=", "owner_repo_p...
Move (promote) a package to another repo. This requires appropriate permissions for both the source repository/package and the destination repository. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the package itself. All separated by a slash. Example: 'your-org/awesome-repo/better-pkg'. - DEST: Specify the DEST (destination) repository to move the package to. This *must* be in the same namespace as the source repository. Example: 'other-repo' Full CLI example: $ cloudsmith mv your-org/awesome-repo/better-pkg other-repo
[ "Move", "(", "promote", ")", "a", "package", "to", "another", "repo", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/move.py#L35-L106
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/rest.py
create_requests_session
def create_requests_session( retries=None, backoff_factor=None, status_forcelist=None, pools_size=4, maxsize=4, ssl_verify=None, ssl_cert=None, proxy=None, session=None, ): """Create a requests session that retries some errors.""" # pylint: disable=too-many-branches config = Configuration() if retries is None: if config.error_retry_max is None: retries = 5 else: retries = config.error_retry_max if backoff_factor is None: if config.error_retry_backoff is None: backoff_factor = 0.23 else: backoff_factor = config.error_retry_backoff if status_forcelist is None: if config.error_retry_codes is None: status_forcelist = [500, 502, 503, 504] else: status_forcelist = config.error_retry_codes if ssl_verify is None: ssl_verify = config.verify_ssl if ssl_cert is None: if config.cert_file and config.key_file: ssl_cert = (config.cert_file, config.key_file) elif config.cert_file: ssl_cert = config.cert_file if proxy is None: proxy = Configuration().proxy session = session or requests.Session() session.verify = ssl_verify session.cert = ssl_cert if proxy: session.proxies = {"http": proxy, "https": proxy} retry = Retry( backoff_factor=backoff_factor, connect=retries, method_whitelist=False, read=retries, status_forcelist=tuple(status_forcelist), total=retries, ) adapter = HTTPAdapter( max_retries=retry, pool_connections=pools_size, pool_maxsize=maxsize, pool_block=True, ) session.mount("http://", adapter) session.mount("https://", adapter) return session
python
def create_requests_session( retries=None, backoff_factor=None, status_forcelist=None, pools_size=4, maxsize=4, ssl_verify=None, ssl_cert=None, proxy=None, session=None, ): """Create a requests session that retries some errors.""" # pylint: disable=too-many-branches config = Configuration() if retries is None: if config.error_retry_max is None: retries = 5 else: retries = config.error_retry_max if backoff_factor is None: if config.error_retry_backoff is None: backoff_factor = 0.23 else: backoff_factor = config.error_retry_backoff if status_forcelist is None: if config.error_retry_codes is None: status_forcelist = [500, 502, 503, 504] else: status_forcelist = config.error_retry_codes if ssl_verify is None: ssl_verify = config.verify_ssl if ssl_cert is None: if config.cert_file and config.key_file: ssl_cert = (config.cert_file, config.key_file) elif config.cert_file: ssl_cert = config.cert_file if proxy is None: proxy = Configuration().proxy session = session or requests.Session() session.verify = ssl_verify session.cert = ssl_cert if proxy: session.proxies = {"http": proxy, "https": proxy} retry = Retry( backoff_factor=backoff_factor, connect=retries, method_whitelist=False, read=retries, status_forcelist=tuple(status_forcelist), total=retries, ) adapter = HTTPAdapter( max_retries=retry, pool_connections=pools_size, pool_maxsize=maxsize, pool_block=True, ) session.mount("http://", adapter) session.mount("https://", adapter) return session
[ "def", "create_requests_session", "(", "retries", "=", "None", ",", "backoff_factor", "=", "None", ",", "status_forcelist", "=", "None", ",", "pools_size", "=", "4", ",", "maxsize", "=", "4", ",", "ssl_verify", "=", "None", ",", "ssl_cert", "=", "None", ",...
Create a requests session that retries some errors.
[ "Create", "a", "requests", "session", "that", "retries", "some", "errors", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/rest.py#L21-L92
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/rest.py
RestResponse.data
def data(self): """ Get the content for the response (lazily decoded). """ if self._data is None: self._data = self.response.content.decode("utf-8") return self._data
python
def data(self): """ Get the content for the response (lazily decoded). """ if self._data is None: self._data = self.response.content.decode("utf-8") return self._data
[ "def", "data", "(", "self", ")", ":", "if", "self", ".", "_data", "is", "None", ":", "self", ".", "_data", "=", "self", ".", "response", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "return", "self", ".", "_data" ]
Get the content for the response (lazily decoded).
[ "Get", "the", "content", "for", "the", "response", "(", "lazily", "decoded", ")", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/rest.py#L106-L112
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/rest.py
RestResponse.getheader
def getheader(self, name, default=None): """ Return a given response header. """ return self.response.headers.get(name, default)
python
def getheader(self, name, default=None): """ Return a given response header. """ return self.response.headers.get(name, default)
[ "def", "getheader", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "return", "self", ".", "response", ".", "headers", ".", "get", "(", "name", ",", "default", ")" ]
Return a given response header.
[ "Return", "a", "given", "response", "header", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/rest.py#L120-L124
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/rest.py
RestClient.request
def request( self, method, url, query_params=None, headers=None, body=None, post_params=None, _preload_content=True, _request_timeout=None, ): """ :param method: http request method :param url: http request url :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` :param _preload_content: if False, the response object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. """ # Based on the RESTClientObject class generated by Swagger method = method.upper() assert method in ["GET", "HEAD", "DELETE", "POST", "PUT", "PATCH", "OPTIONS"] post_params = post_params or {} headers = headers or {} if "Content-Type" not in headers: headers["Content-Type"] = "application/json" request_kwargs = {} if query_params: url += "?" + urlencode(query_params) if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]: if re.search("json", headers["Content-Type"], re.IGNORECASE): request_body = None if body: request_body = json.dumps(body) request_kwargs["data"] = request_body elif headers["Content-Type"] == "application/x-www-form-urlencoded": request_kwargs["data"] = post_params elif headers["Content-Type"] == "multipart/form-data": del headers["Content-Type"] request_kwargs["data"] = post_params elif isinstance(body, str): request_kwargs["data"] = body else: # Cannot generate the request from given parameters msg = """Cannot prepare a request message for provided arguments. Please check that your arguments match declared content type.""" raise ApiException(status=0, reason=msg) try: resp = self.session.request( method, url, timeout=_request_timeout, stream=not _preload_content, headers=headers, **request_kwargs ) except requests.exceptions.RequestException as exc: msg = "{0}\n{1}".format(type(exc).__name__, str(exc)) raise ApiException(status=0, reason=msg) resp.encoding = resp.apparent_encoding or "utf-8" rest_resp = RestResponse(resp) if _preload_content: logger.debug("response body: %s", rest_resp.data) if not 200 <= rest_resp.status <= 299: raise ApiException(http_resp=rest_resp) return rest_resp
python
def request( self, method, url, query_params=None, headers=None, body=None, post_params=None, _preload_content=True, _request_timeout=None, ): """ :param method: http request method :param url: http request url :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` :param _preload_content: if False, the response object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. """ # Based on the RESTClientObject class generated by Swagger method = method.upper() assert method in ["GET", "HEAD", "DELETE", "POST", "PUT", "PATCH", "OPTIONS"] post_params = post_params or {} headers = headers or {} if "Content-Type" not in headers: headers["Content-Type"] = "application/json" request_kwargs = {} if query_params: url += "?" + urlencode(query_params) if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]: if re.search("json", headers["Content-Type"], re.IGNORECASE): request_body = None if body: request_body = json.dumps(body) request_kwargs["data"] = request_body elif headers["Content-Type"] == "application/x-www-form-urlencoded": request_kwargs["data"] = post_params elif headers["Content-Type"] == "multipart/form-data": del headers["Content-Type"] request_kwargs["data"] = post_params elif isinstance(body, str): request_kwargs["data"] = body else: # Cannot generate the request from given parameters msg = """Cannot prepare a request message for provided arguments. Please check that your arguments match declared content type.""" raise ApiException(status=0, reason=msg) try: resp = self.session.request( method, url, timeout=_request_timeout, stream=not _preload_content, headers=headers, **request_kwargs ) except requests.exceptions.RequestException as exc: msg = "{0}\n{1}".format(type(exc).__name__, str(exc)) raise ApiException(status=0, reason=msg) resp.encoding = resp.apparent_encoding or "utf-8" rest_resp = RestResponse(resp) if _preload_content: logger.debug("response body: %s", rest_resp.data) if not 200 <= rest_resp.status <= 299: raise ApiException(http_resp=rest_resp) return rest_resp
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "query_params", "=", "None", ",", "headers", "=", "None", ",", "body", "=", "None", ",", "post_params", "=", "None", ",", "_preload_content", "=", "True", ",", "_request_timeout", "=", "None"...
:param method: http request method :param url: http request url :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` :param _preload_content: if False, the response object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts.
[ ":", "param", "method", ":", "http", "request", "method", ":", "param", "url", ":", "http", "request", "url", ":", "param", "query_params", ":", "query", "parameters", "in", "the", "url", ":", "param", "headers", ":", "http", "request", "headers", ":", "...
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/rest.py#L134-L215
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/utils.py
get_root_path
def get_root_path(): """Get the root directory for the application.""" return os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir))
python
def get_root_path(): """Get the root directory for the application.""" return os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir))
[ "def", "get_root_path", "(", ")", ":", "return", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "os", ".", "pardir", ")", ")" ]
Get the root directory for the application.
[ "Get", "the", "root", "directory", "for", "the", "application", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/utils.py#L21-L23
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/utils.py
read_file
def read_file(*path): """Read the specific file into a string in its entirety.""" real_path = os.path.realpath(os.path.join(*path)) with click.open_file(real_path, "r") as fp: return fp.read()
python
def read_file(*path): """Read the specific file into a string in its entirety.""" real_path = os.path.realpath(os.path.join(*path)) with click.open_file(real_path, "r") as fp: return fp.read()
[ "def", "read_file", "(", "*", "path", ")", ":", "real_path", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "*", "path", ")", ")", "with", "click", ".", "open_file", "(", "real_path", ",", "\"r\"", ")", "as", "...
Read the specific file into a string in its entirety.
[ "Read", "the", "specific", "file", "into", "a", "string", "in", "its", "entirety", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/utils.py#L31-L35
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/utils.py
calculate_file_md5
def calculate_file_md5(filepath, blocksize=2 ** 20): """Calculate an MD5 hash for a file.""" checksum = hashlib.md5() with click.open_file(filepath, "rb") as f: def update_chunk(): """Add chunk to checksum.""" buf = f.read(blocksize) if buf: checksum.update(buf) return bool(buf) while update_chunk(): pass return checksum.hexdigest()
python
def calculate_file_md5(filepath, blocksize=2 ** 20): """Calculate an MD5 hash for a file.""" checksum = hashlib.md5() with click.open_file(filepath, "rb") as f: def update_chunk(): """Add chunk to checksum.""" buf = f.read(blocksize) if buf: checksum.update(buf) return bool(buf) while update_chunk(): pass return checksum.hexdigest()
[ "def", "calculate_file_md5", "(", "filepath", ",", "blocksize", "=", "2", "**", "20", ")", ":", "checksum", "=", "hashlib", ".", "md5", "(", ")", "with", "click", ".", "open_file", "(", "filepath", ",", "\"rb\"", ")", "as", "f", ":", "def", "update_chu...
Calculate an MD5 hash for a file.
[ "Calculate", "an", "MD5", "hash", "for", "a", "file", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/utils.py#L38-L54
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/utils.py
get_page_kwargs
def get_page_kwargs(**kwargs): """Construct page and page size kwargs (if present).""" page_kwargs = {} page = kwargs.get("page") if page is not None and page > 0: page_kwargs["page"] = page page_size = kwargs.get("page_size") if page_size is not None and page_size > 0: page_kwargs["page_size"] = page_size return page_kwargs
python
def get_page_kwargs(**kwargs): """Construct page and page size kwargs (if present).""" page_kwargs = {} page = kwargs.get("page") if page is not None and page > 0: page_kwargs["page"] = page page_size = kwargs.get("page_size") if page_size is not None and page_size > 0: page_kwargs["page_size"] = page_size return page_kwargs
[ "def", "get_page_kwargs", "(", "*", "*", "kwargs", ")", ":", "page_kwargs", "=", "{", "}", "page", "=", "kwargs", ".", "get", "(", "\"page\"", ")", "if", "page", "is", "not", "None", "and", "page", ">", "0", ":", "page_kwargs", "[", "\"page\"", "]", ...
Construct page and page size kwargs (if present).
[ "Construct", "page", "and", "page", "size", "kwargs", "(", "if", "present", ")", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/utils.py#L63-L75
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/utils.py
get_query_kwargs
def get_query_kwargs(**kwargs): """Construct page and page size kwargs (if present).""" query_kwargs = {} query = kwargs.pop("query") if query: query_kwargs["query"] = query return query_kwargs
python
def get_query_kwargs(**kwargs): """Construct page and page size kwargs (if present).""" query_kwargs = {} query = kwargs.pop("query") if query: query_kwargs["query"] = query return query_kwargs
[ "def", "get_query_kwargs", "(", "*", "*", "kwargs", ")", ":", "query_kwargs", "=", "{", "}", "query", "=", "kwargs", ".", "pop", "(", "\"query\"", ")", "if", "query", ":", "query_kwargs", "[", "\"query\"", "]", "=", "query", "return", "query_kwargs" ]
Construct page and page size kwargs (if present).
[ "Construct", "page", "and", "page", "size", "kwargs", "(", "if", "present", ")", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/utils.py#L78-L86
kalefranz/auxlib
auxlib/packaging.py
_get_version_from_git_tag
def _get_version_from_git_tag(path): """Return a PEP440-compliant version derived from the git status. If that fails for any reason, return the changeset hash. """ m = GIT_DESCRIBE_REGEX.match(_git_describe_tags(path) or '') if m is None: return None version, post_commit, hash = m.groups() return version if post_commit == '0' else "{0}.post{1}+{2}".format(version, post_commit, hash)
python
def _get_version_from_git_tag(path): """Return a PEP440-compliant version derived from the git status. If that fails for any reason, return the changeset hash. """ m = GIT_DESCRIBE_REGEX.match(_git_describe_tags(path) or '') if m is None: return None version, post_commit, hash = m.groups() return version if post_commit == '0' else "{0}.post{1}+{2}".format(version, post_commit, hash)
[ "def", "_get_version_from_git_tag", "(", "path", ")", ":", "m", "=", "GIT_DESCRIBE_REGEX", ".", "match", "(", "_git_describe_tags", "(", "path", ")", "or", "''", ")", "if", "m", "is", "None", ":", "return", "None", "version", ",", "post_commit", ",", "hash...
Return a PEP440-compliant version derived from the git status. If that fails for any reason, return the changeset hash.
[ "Return", "a", "PEP440", "-", "compliant", "version", "derived", "from", "the", "git", "status", ".", "If", "that", "fails", "for", "any", "reason", "return", "the", "changeset", "hash", "." ]
train
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/packaging.py#L142-L150
kalefranz/auxlib
auxlib/packaging.py
get_version
def get_version(dunder_file): """Returns a version string for the current package, derived either from git or from a .version file. This function is expected to run in two contexts. In a development context, where .git/ exists, the version is pulled from git tags. Using the BuildPyCommand and SDistCommand classes for cmdclass in setup.py will write a .version file into any dist. In an installed context, the .version file written at dist build time is the source of version information. """ path = abspath(expanduser(dirname(dunder_file))) try: return _get_version_from_version_file(path) or _get_version_from_git_tag(path) except CalledProcessError as e: log.warn(repr(e)) return None except Exception as e: log.exception(e) return None
python
def get_version(dunder_file): """Returns a version string for the current package, derived either from git or from a .version file. This function is expected to run in two contexts. In a development context, where .git/ exists, the version is pulled from git tags. Using the BuildPyCommand and SDistCommand classes for cmdclass in setup.py will write a .version file into any dist. In an installed context, the .version file written at dist build time is the source of version information. """ path = abspath(expanduser(dirname(dunder_file))) try: return _get_version_from_version_file(path) or _get_version_from_git_tag(path) except CalledProcessError as e: log.warn(repr(e)) return None except Exception as e: log.exception(e) return None
[ "def", "get_version", "(", "dunder_file", ")", ":", "path", "=", "abspath", "(", "expanduser", "(", "dirname", "(", "dunder_file", ")", ")", ")", "try", ":", "return", "_get_version_from_version_file", "(", "path", ")", "or", "_get_version_from_git_tag", "(", ...
Returns a version string for the current package, derived either from git or from a .version file. This function is expected to run in two contexts. In a development context, where .git/ exists, the version is pulled from git tags. Using the BuildPyCommand and SDistCommand classes for cmdclass in setup.py will write a .version file into any dist. In an installed context, the .version file written at dist build time is the source of version information.
[ "Returns", "a", "version", "string", "for", "the", "current", "package", "derived", "either", "from", "git", "or", "from", "a", ".", "version", "file", "." ]
train
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/packaging.py#L153-L174
visualfabriq/bquery
bquery/benchmarks/bench_groupby.py
ctime
def ctime(message=None): "Counts the time spent in some context" global t_elapsed t_elapsed = 0.0 print('\n') t = time.time() yield if message: print(message + ": ", end='') t_elapsed = time.time() - t print(round(t_elapsed, 4), "sec")
python
def ctime(message=None): "Counts the time spent in some context" global t_elapsed t_elapsed = 0.0 print('\n') t = time.time() yield if message: print(message + ": ", end='') t_elapsed = time.time() - t print(round(t_elapsed, 4), "sec")
[ "def", "ctime", "(", "message", "=", "None", ")", ":", "global", "t_elapsed", "t_elapsed", "=", "0.0", "print", "(", "'\\n'", ")", "t", "=", "time", ".", "time", "(", ")", "yield", "if", "message", ":", "print", "(", "message", "+", "\": \"", ",", ...
Counts the time spent in some context
[ "Counts", "the", "time", "spent", "in", "some", "context" ]
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/benchmarks/bench_groupby.py#L29-L39
skulumani/kinematics
kinematics/attitude.py
rot1
def rot1(angle, form='c'): """Euler rotation about first axis This computes the rotation matrix associated with a rotation about the first axis. It will output matrices assuming column or row format vectors. For example, to transform a vector from reference frame b to reference frame a: Column Vectors : a = rot1(angle, 'c').dot(b) Row Vectors : a = b.dot(rot1(angle, 'r')) It should be clear that rot1(angle, 'c') = rot1(angle, 'r').T Parameters ---------- angle : float Angle of rotation about first axis. In radians form : str Flag to choose between row or column vector convention. Returns ------- mat : numpy.ndarray of shape (3,3) Rotation matrix """ cos_a = np.cos(angle) sin_a = np.sin(angle) rot_mat = np.identity(3) if form=='c': rot_mat[1, 1] = cos_a rot_mat[1, 2] = -sin_a rot_mat[2, 1] = sin_a rot_mat[2, 2] = cos_a elif form=='r': rot_mat[1, 1] = cos_a rot_mat[1, 2] = sin_a rot_mat[2, 1] = -sin_a rot_mat[2, 2] = cos_a else: print("Unknown input. 'r' or 'c' for row/column notation.") return 1 return rot_mat
python
def rot1(angle, form='c'): """Euler rotation about first axis This computes the rotation matrix associated with a rotation about the first axis. It will output matrices assuming column or row format vectors. For example, to transform a vector from reference frame b to reference frame a: Column Vectors : a = rot1(angle, 'c').dot(b) Row Vectors : a = b.dot(rot1(angle, 'r')) It should be clear that rot1(angle, 'c') = rot1(angle, 'r').T Parameters ---------- angle : float Angle of rotation about first axis. In radians form : str Flag to choose between row or column vector convention. Returns ------- mat : numpy.ndarray of shape (3,3) Rotation matrix """ cos_a = np.cos(angle) sin_a = np.sin(angle) rot_mat = np.identity(3) if form=='c': rot_mat[1, 1] = cos_a rot_mat[1, 2] = -sin_a rot_mat[2, 1] = sin_a rot_mat[2, 2] = cos_a elif form=='r': rot_mat[1, 1] = cos_a rot_mat[1, 2] = sin_a rot_mat[2, 1] = -sin_a rot_mat[2, 2] = cos_a else: print("Unknown input. 'r' or 'c' for row/column notation.") return 1 return rot_mat
[ "def", "rot1", "(", "angle", ",", "form", "=", "'c'", ")", ":", "cos_a", "=", "np", ".", "cos", "(", "angle", ")", "sin_a", "=", "np", ".", "sin", "(", "angle", ")", "rot_mat", "=", "np", ".", "identity", "(", "3", ")", "if", "form", "==", "'...
Euler rotation about first axis This computes the rotation matrix associated with a rotation about the first axis. It will output matrices assuming column or row format vectors. For example, to transform a vector from reference frame b to reference frame a: Column Vectors : a = rot1(angle, 'c').dot(b) Row Vectors : a = b.dot(rot1(angle, 'r')) It should be clear that rot1(angle, 'c') = rot1(angle, 'r').T Parameters ---------- angle : float Angle of rotation about first axis. In radians form : str Flag to choose between row or column vector convention. Returns ------- mat : numpy.ndarray of shape (3,3) Rotation matrix
[ "Euler", "rotation", "about", "first", "axis" ]
train
https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L45-L88
skulumani/kinematics
kinematics/attitude.py
dcm2body313
def dcm2body313(dcm): """Convert DCM to body Euler 3-1-3 angles """ theta = np.zeros(3) theta[0] = np.arctan2(dcm[2, 0], dcm[2, 1]) theta[1] = np.arccos(dcm[2, 2]) theta[2] = np.arctan2(dcm[0, 2], -dcm[1, 2]) return theta
python
def dcm2body313(dcm): """Convert DCM to body Euler 3-1-3 angles """ theta = np.zeros(3) theta[0] = np.arctan2(dcm[2, 0], dcm[2, 1]) theta[1] = np.arccos(dcm[2, 2]) theta[2] = np.arctan2(dcm[0, 2], -dcm[1, 2]) return theta
[ "def", "dcm2body313", "(", "dcm", ")", ":", "theta", "=", "np", ".", "zeros", "(", "3", ")", "theta", "[", "0", "]", "=", "np", ".", "arctan2", "(", "dcm", "[", "2", ",", "0", "]", ",", "dcm", "[", "2", ",", "1", "]", ")", "theta", "[", "...
Convert DCM to body Euler 3-1-3 angles
[ "Convert", "DCM", "to", "body", "Euler", "3", "-", "1", "-", "3", "angles" ]
train
https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L180-L190