signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def sum(self, func=lambda x: x): | return sum(self.select(func))<EOL> | Returns the sum of af data elements
:param func: lambda expression to transform data
:return: sum of selected elements | f15480:c0:m7 |
def min(self, func=lambda x: x): | if self.count() == <NUM_LIT:0>:<EOL><INDENT>raise NoElementsError(u"<STR_LIT>")<EOL><DEDENT>return min(self.select(func))<EOL> | Returns the min value of data elements
:param func: lambda expression to transform data
:return: minimum value | f15480:c0:m8 |
def max(self, func=lambda x: x): | if self.count() == <NUM_LIT:0>:<EOL><INDENT>raise NoElementsError(u"<STR_LIT>")<EOL><DEDENT>return max(self.select(func))<EOL> | Returns the max value of data elements
:param func: lambda expression to transform data
:return: maximum value | f15480:c0:m9 |
def avg(self, func=lambda x: x): | count = self.count()<EOL>if count == <NUM_LIT:0>:<EOL><INDENT>raise NoElementsError(u"<STR_LIT>")<EOL><DEDENT>return float(self.sum(func)) / float(count)<EOL> | Returns the average value of data elements
:param func: lambda expression to transform data
:return: average value as float object | f15480:c0:m10 |
def median(self, func=lambda x: x): | if self.count() == <NUM_LIT:0>:<EOL><INDENT>raise NoElementsError(u"<STR_LIT>")<EOL><DEDENT>result = self.order_by(func).select(func).to_list()<EOL>length = len(result)<EOL>i = int(length / <NUM_LIT:2>)<EOL>return result[i] if length % <NUM_LIT:2> == <NUM_LIT:1> else (float(result[i - <NUM_LIT:1>]) + float(result[i])) / float(<NUM_LIT:2>)<EOL> | Return the median value of data elements
:param func: lambda expression to project and sort data
:return: median value | f15480:c0:m11 |
def element_at(self, n): | result = list(itertools.islice(self.to_list(), max(<NUM_LIT:0>, n), n + <NUM_LIT:1>, <NUM_LIT:1>))<EOL>if len(result) == <NUM_LIT:0>:<EOL><INDENT>raise NoElementsError(u"<STR_LIT>".format(n))<EOL><DEDENT>return result[<NUM_LIT:0>]<EOL> | Returns element at given index.
* Raises NoElementsError if no element found at specified position
:param n: index as int object
:return: Element at given index | f15480:c0:m12 |
def element_at_or_default(self, n): | try:<EOL><INDENT>return self.element_at(n)<EOL><DEDENT>except NoElementsError:<EOL><INDENT>return None<EOL><DEDENT> | Returns element at given index or None if no element found
* Raises IndexError if n is greater than the number of elements in
enumerable
:param n: index as int object
:return: Element at given index | f15480:c0:m13 |
def first(self): | return self.element_at(<NUM_LIT:0>)<EOL> | Returns the first element
:return: data element as object or NoElementsError if transformed data
contains no elements | f15480:c0:m14 |
def first_or_default(self): | return self.element_at_or_default(<NUM_LIT:0>)<EOL> | Return the first element
:return: data element as object or None if transformed data contains no
elements | f15480:c0:m15 |
def last(self): | return self.element_at(self.count() - <NUM_LIT:1>)<EOL> | Return the last element
:return: data element as object or NoElementsError if transformed data
contains no elements | f15480:c0:m16 |
def last_or_default(self): | return self.element_at_or_default(self.count() - <NUM_LIT:1>)<EOL> | Return the last element
:return: data element as object or None if transformed data contains no
elements | f15480:c0:m17 |
def order_by(self, key): | if key is None:<EOL><INDENT>raise NullArgumentError(u"<STR_LIT>")<EOL><DEDENT>kf = [OrderingDirection(key, reverse=False)]<EOL>return SortedEnumerable(key_funcs=kf, data=self._data)<EOL> | Returns new Enumerable sorted in ascending order by given key
:param key: key to sort by as lambda expression
:return: new Enumerable object | f15480:c0:m18 |
def order_by_descending(self, key): | if key is None:<EOL><INDENT>raise NullArgumentError(u"<STR_LIT>")<EOL><DEDENT>kf = [OrderingDirection(key, reverse=True)]<EOL>return SortedEnumerable(key_funcs=kf, data=self._data)<EOL> | Returns new Enumerable sorted in descending order by given key
:param key: key to sort by as lambda expression
:return: new Enumerable object | f15480:c0:m19 |
def skip(self, n): | return Enumerable(itertools.islice(self, n, None, <NUM_LIT:1>))<EOL> | Returns new Enumerable where n elements have been skipped
:param n: Number of elements to skip as int
:return: new Enumerable object | f15480:c0:m20 |
def take(self, n): | return Enumerable(itertools.islice(self, <NUM_LIT:0>, n, <NUM_LIT:1>))<EOL> | Return new Enumerable where first n elements are taken
:param n: Number of elements to take
:return: new Enumerable object | f15480:c0:m21 |
def where(self, predicate): | if predicate is None:<EOL><INDENT>raise NullArgumentError("<STR_LIT>")<EOL><DEDENT>return Enumerable(itertools.ifilter(predicate, self))<EOL> | Returns new Enumerable where elements matching predicate are selected
:param predicate: predicate as a lambda expression
:return: new Enumerable object | f15480:c0:m22 |
def single(self, predicate): | result = self.where(predicate).to_list()<EOL>count = len(result)<EOL>if count == <NUM_LIT:0>:<EOL><INDENT>raise NoMatchingElement("<STR_LIT>")<EOL><DEDENT>if count > <NUM_LIT:1>:<EOL><INDENT>raise MoreThanOneMatchingElement(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>return result[<NUM_LIT:0>]<EOL> | Returns single element that matches given predicate.
Raises:
* NoMatchingElement error if no matching elements are found
* MoreThanOneMatchingElement error if more than one matching
element is found
:param predicate: predicate as a lambda expression
:return: Matching element as object | f15480:c0:m23 |
def single_or_default(self, predicate): | try:<EOL><INDENT>return self.single(predicate)<EOL><DEDENT>except NoMatchingElement:<EOL><INDENT>return None<EOL><DEDENT> | Return single element that matches given predicate. If no matching
element is found, returns None
Raises:
* MoreThanOneMatchingElement error if more than one matching
element is found
:param predicate: predicate as a lambda expression
:return: Matching element as object or None if no matches are found | f15480:c0:m24 |
def select_many(self, func=lambda x: x): | return Enumerable(itertools.chain.from_iterable(self.select(func)))<EOL> | Flattens an iterable of iterables returning a new Enumerable
:param func: selector as lambda expression
:return: new Enumerable object | f15480:c0:m25 |
def add(self, element): | if element is None:<EOL><INDENT>return self<EOL><DEDENT>return self.concat(Enumerable([element]))<EOL> | Adds an element to the enumerable.
:param element: An element
:return: new Enumerable object | f15480:c0:m26 |
def concat(self, enumerable): | if not isinstance(enumerable, Enumerable):<EOL><INDENT>raise TypeError(<EOL>u"<STR_LIT>"<EOL>)<EOL><DEDENT>return Enumerable(itertools.chain(self._data, enumerable.data))<EOL> | Adds enumerable to an enumerable
:param enumerable: An iterable object
:return: new Enumerable object | f15480:c0:m27 |
def group_by(self, key_names=[], key=lambda x: x, result_func=lambda x: x): | result = []<EOL>ordered = sorted(self, key=key)<EOL>grouped = itertools.groupby(ordered, key)<EOL>for k, g in grouped:<EOL><INDENT>can_enumerate = isinstance(k, list) or isinstance(k, tuple)and len(k) > <NUM_LIT:0><EOL>key_prop = {}<EOL>for i, prop in enumerate(key_names):<EOL><INDENT>key_prop.setdefault(prop, k[i] if can_enumerate else k)<EOL><DEDENT>key_object = Key(key_prop)<EOL>result.append(Grouping(key_object, list(g)))<EOL><DEDENT>return Enumerable(result).select(result_func)<EOL> | Groups an enumerable on given key selector. Index of key name
corresponds to index of key lambda function.
Usage:
Enumerable([1,2,3]).group_by(key_names=['id'], key=lambda x: x) _
.to_list() -->
Enumerable object [
Grouping object {
key.id: 1,
_data: [1]
},
Grouping object {
key.id: 2,
_data: [2]
},
Grouping object {
key.id: 3,
_data: [3]
}
]
Thus the key names for each grouping object can be referenced
through the key property. Using the above example:
Enumerable([1,2,3]).group_by(key_names=['id'], key=lambda x: x) _
.select(lambda g: { 'key': g.key.id, 'count': g.count() }
:param key_names: list of key names
:param key: key selector as lambda expression
:param result_func: transformation function as lambda expression
:return: Enumerable of grouping objects | f15480:c0:m28 |
def distinct(self, key=lambda x: x): | return Enumerable(self.group_by(key=key).select(lambda g: g.first()).to_list())<EOL> | Returns enumerable containing elements that are distinct based on
given key selector
:param key: key selector as lambda expression
:return: new Enumerable object | f15480:c0:m29 |
def join(<EOL>self,<EOL>inner_enumerable,<EOL>outer_key=lambda x: x,<EOL>inner_key=lambda x: x,<EOL>result_func=lambda x: x<EOL>): | if not isinstance(inner_enumerable, Enumerable):<EOL><INDENT>raise TypeError(<EOL>u"<STR_LIT>"<EOL>)<EOL><DEDENT>return Enumerable(<EOL>itertools.product(<EOL>itertools.ifilter(<EOL>lambda x: outer_key(x) in itertools.imap(<EOL>inner_key,<EOL>inner_enumerable<EOL>), self<EOL>),<EOL>itertools.ifilter(<EOL>lambda y: inner_key(y) in itertools.imap(<EOL>outer_key,<EOL>self),<EOL>inner_enumerable<EOL>)<EOL>)<EOL>).where(lambda x: outer_key(x[<NUM_LIT:0>]) == inner_key(x[<NUM_LIT:1>])).select(<EOL>result_func)<EOL> | Return enumerable of inner equi-join between two enumerables
:param inner_enumerable: inner enumerable to join to self
:param outer_key: key selector of outer enumerable as lambda expression
:param inner_key: key selector of inner enumerable as lambda expression
:param result_func: lambda expression to transform result of join
:return: new Enumerable object | f15480:c0:m30 |
def default_if_empty(self, value=None): | if self.count() == <NUM_LIT:0>:<EOL><INDENT>return Enumerable([value])<EOL><DEDENT>return self<EOL> | Returns an enumerable containing a single None element if enumerable is
empty, otherwise the enumerable itself
:return: an Enumerable object | f15480:c0:m31 |
def group_join(<EOL>self,<EOL>inner_enumerable,<EOL>outer_key=lambda x: x,<EOL>inner_key=lambda x: x,<EOL>result_func=lambda x: x<EOL>): | if not isinstance(inner_enumerable, Enumerable):<EOL><INDENT>raise TypeError(<EOL>u"<STR_LIT>"<EOL>)<EOL><DEDENT>return Enumerable(<EOL>itertools.product(<EOL>self,<EOL>inner_enumerable.default_if_empty()<EOL>)<EOL>).group_by(<EOL>key_names=['<STR_LIT:id>'],<EOL>key=lambda x: outer_key(x[<NUM_LIT:0>]),<EOL>result_func=lambda g: (<EOL>g.first()[<NUM_LIT:0>],<EOL>g.where(<EOL>lambda x: inner_key(x[<NUM_LIT:1>]) == g.key.id).select(<EOL>lambda x: x[<NUM_LIT:1>]<EOL>)<EOL>)<EOL>).select(result_func)<EOL> | Return enumerable of group join between two enumerables
:param inner_enumerable: inner enumerable to join to self
:param outer_key: key selector of outer enumerable as lambda expression
:param inner_key: key selector of inner enumerable as lambda expression
:param result_func: lambda expression to transform the result of group
join
:return: new Enumerable object | f15480:c0:m32 |
def any(self, predicate): | if predicate is None:<EOL><INDENT>raise NullArgumentError(<EOL>u"<STR_LIT>")<EOL><DEDENT>return self.where(predicate).count() > <NUM_LIT:0><EOL> | Returns true if any elements that satisfy predicate are found
:param predicate: condition to satisfy as lambda expression
:return: boolean True or False | f15480:c0:m33 |
def intersect(self, enumerable, key=lambda x: x): | if not isinstance(enumerable, Enumerable):<EOL><INDENT>raise TypeError(<EOL>u"<STR_LIT>")<EOL><DEDENT>return self.join(enumerable, key, key).select(lambda x: x[<NUM_LIT:0>])<EOL> | Returns enumerable that is the intersection between given enumerable
and self
:param enumerable: enumerable object
:param key: key selector as lambda expression
:return: new Enumerable object | f15480:c0:m34 |
def aggregate(self, func, seed=None): | if self.count() == <NUM_LIT:0>:<EOL><INDENT>raise NoElementsError("<STR_LIT>")<EOL><DEDENT>result = seed if seed is not None else self.first()<EOL>for i, e in enumerate(self):<EOL><INDENT>if i == <NUM_LIT:0> and seed is None:<EOL><INDENT>continue<EOL><DEDENT>result = func(result, e)<EOL><DEDENT>return result<EOL> | Perform a calculation over a given enumerable using the initial seed
value
:param func: calculation to perform over every the enumerable.
This function will ingest (aggregate_result, next element) as parameters
:param seed: initial seed value for the calculation. If None, then the
first element is used as the seed
:return: result of the calculation | f15480:c0:m35 |
def union(self, enumerable, key=lambda x: x): | if not isinstance(enumerable, Enumerable):<EOL><INDENT>raise TypeError(<EOL>u"<STR_LIT>")<EOL><DEDENT>return self.concat(enumerable).distinct(key)<EOL> | Returns enumerable that is a union of elements between self and given
enumerable
:param enumerable: enumerable to union self to
:param key: key selector used to determine uniqueness
:return: new Enumerable object | f15480:c0:m36 |
def except_(self, enumerable, key=lambda x: x): | if not isinstance(enumerable, Enumerable):<EOL><INDENT>raise TypeError(<EOL>u"<STR_LIT>")<EOL><DEDENT>membership = [<EOL><NUM_LIT:0> if key(element) in enumerable.intersect(self, key).select(key) else <NUM_LIT:1><EOL>for element in self<EOL>]<EOL>return Enumerable(itertools.compress(self, membership))<EOL> | Returns enumerable that subtracts given enumerable elements from self
:param enumerable: enumerable object
:param key: key selector as lambda expression
:return: new Enumerable object | f15480:c0:m37 |
def contains(self, element, key=lambda x: x): | return self.select(key).any(lambda x: x == key(element))<EOL> | Returns True if element is found in enumerable, otherwise False
:param element: the element being tested for membership in enumerable
:param key: key selector to use for membership comparison
:return: boolean True or False | f15480:c0:m38 |
def all(self, predicate): | return self.where(predicate).count() == self.count()<EOL> | Determines whether all elements in an enumerable satisfy the given
predicate
:param predicate: the condition to test each element as lambda function
:return: boolean True or False | f15480:c0:m39 |
def append(self, element): | return self.concat(Enumerable([element]))<EOL> | Appends an element to the end of an enumerable
:param element: the element to append to the enumerable
:return: Enumerable object with appended element | f15480:c0:m40 |
def prepend(self, element): | return Enumerable([element]).concat(self)<EOL> | Prepends an element to the beginning of an enumerable
:param element: the element to prepend to the enumerable
:return: Enumerable object with the prepended element | f15480:c0:m41 |
@staticmethod<EOL><INDENT>def empty():<DEDENT> | return Enumerable()<EOL> | Returns an empty enumerable
:return: Enumerable object that contains no elements | f15480:c0:m42 |
@staticmethod<EOL><INDENT>def range(start, length):<DEDENT> | return Enumerable(xrange(start, start + length, <NUM_LIT:1>))<EOL> | Generates a sequence of integers starting from start with length of length
:param start: the starting value of the sequence
:param length: the number of integers in the sequence
:return: Enumerable of the generated sequence | f15480:c0:m43 |
@staticmethod<EOL><INDENT>def repeat(element, length):<DEDENT> | return Enumerable(itertools.repeat(element, length))<EOL> | Generates an enumerable containing an element repeated length times
:param element: the element to repeat
:param length: the number of times to repeat the element
:return: Enumerable of the repeated elements | f15480:c0:m44 |
def reverse(self): | return self.aggregate(lambda *args: args[<NUM_LIT:0>].prepend(args[<NUM_LIT:1>]), Enumerable())<EOL> | Inverts the order of the elements in a sequence
:return: Enumerable with elements in reversed order | f15480:c0:m45 |
def skip_last(self, n): | return self.take(self.count() - n)<EOL> | Skips the last n elements in a sequence
:param n: the number of elements to skip
:return: Enumerable with n last elements removed | f15480:c0:m46 |
def skip_while(self, predicate): | return Enumerable(itertools.dropwhile(predicate, self))<EOL> | Bypasses elements in a sequence while the predicate is True. After predicate fails
remaining elements in sequence are returned
:param predicate: a predicate as a lambda expression
:return: Enumerable | f15480:c0:m47 |
def take_last(self, n): | return self.skip(self.count() - n)<EOL> | Takes the last n elements in a sequence
:param n: the number of elements to take
:return: Enumerable containing last n elements | f15480:c0:m48 |
def take_while(self, predicate): | return Enumerable(itertools.takewhile(predicate, self))<EOL> | Includes elements in a sequence while the predicate is True. After predicate fails
remaining elements in a sequence are removed
:param predicate: a predicate as a lambda expression
:return: Enumerable | f15480:c0:m49 |
def zip(self, enumerable, func): | if not isinstance(enumerable, Enumerable):<EOL><INDENT>raise TypeError()<EOL><DEDENT>return Enumerable(itertools.izip(self, enumerable)).select(lambda x: func(x))<EOL> | Merges 2 Enumerables using the given function. If the 2 collections are of unequal length, then
merging continues until the end of one of the collections is reached
:param enumerable: Enumerable collection to merge with
:param func: a function to perform the merging
:return: Enumerable | f15480:c0:m50 |
def __init__(self, key, data): | if not isinstance(key, Key):<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>self.key = key<EOL>super(Grouping, self).__init__(data)<EOL> | Constructor of Grouping class used for group by operations of
Enumerable class
:param key: Key instance
:param data: iterable object
:return: void | f15480:c1:m0 |
def __init__(self, key_funcs, data): | if key_funcs is None:<EOL><INDENT>raise NullArgumentError(u"<STR_LIT>")<EOL><DEDENT>if not isinstance(key_funcs, list):<EOL><INDENT>raise TypeError(u"<STR_LIT>")<EOL><DEDENT>self._key_funcs = [<EOL>f for f in key_funcs if isinstance(f, OrderingDirection)<EOL>]<EOL>super(SortedEnumerable, self).__init__(data)<EOL> | Constructor
:param key_funcs: list of OrderingDirection instances in order of
primary key
--> less important keys
:param data: data as iterable | f15480:c2:m0 |
def then_by(self, func): | if func is None:<EOL><INDENT>raise NullArgumentError(u"<STR_LIT>")<EOL><DEDENT>self._key_funcs.append(OrderingDirection(key=func, reverse=False))<EOL>return SortedEnumerable(self._key_funcs, self._data)<EOL> | Subsequent sorting function in ascending order
:param func: lambda expression for secondary sort key
:return: SortedEnumerable instance | f15480:c2:m2 |
def then_by_descending(self, func): | if func is None:<EOL><INDENT>raise NullArgumentError(<EOL>u"<STR_LIT>")<EOL><DEDENT>self._key_funcs.append(OrderingDirection(key=func, reverse=True))<EOL>return SortedEnumerable(self._key_funcs, self._data)<EOL> | Subsequent sorting function in descending order
:param func: lambda function for secondary sort key
:return: SortedEnumerable instance | f15480:c2:m3 |
def __init__(self, key, **kwargs): | key = key if key is not None else kwargs<EOL>self.__dict__.update(key)<EOL> | Constructor for Key class. Autogenerates key properties in object
given dict or kwargs
:param key: dict of name-values
:param kwargs: optional keyword arguments
:return: void | f15482:c0:m0 |
def __init__(self, key, reverse): | self.key = key<EOL>self.descending = reverse<EOL> | A container to hold the lambda key and sorting direction
:param key: lambda function
:param reverse: boolean. True for reverse sort | f15482:c1:m0 |
def deprecated(reason): | def deprecated_decorator(func):<EOL><INDENT>@functools.wraps(func)<EOL>def new_func(*args, **kwargs):<EOL><INDENT>warnings.simplefilter('<STR_LIT>', DeprecationWarning)<EOL>warnings.warn(<EOL>u"<STR_LIT>".format(func.__name__, reason),<EOL>category=DeprecationWarning, stacklevel=<NUM_LIT:2><EOL>)<EOL>return func(*args, **kwargs)<EOL><DEDENT>return new_func<EOL><DEDENT>return deprecated_decorator<EOL> | This is a decorator which can be used to mark function as deprecated. It
will result in a warning being emitted when the function is used.
:param reason: a reason as a string
:return: decorated function | f15483:m0 |
def massage_keys(keys): | m_keys = []<EOL>for key in keys:<EOL><INDENT>if key.startswith('<STR_LIT>'):<EOL><INDENT>m_keys.append(cryptorito.key_from_keybase(key[<NUM_LIT:8>:])['<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>m_keys.append(key)<EOL><DEDENT><DEDENT>return m_keys<EOL> | Goes through list of GPG/Keybase keys. For the keybase keys
it will attempt to look up the GPG key | f15491:m0 |
def encrypt_file(src, dest, csv_keys): | keys = massage_keys(csv_keys.split('<STR_LIT:U+002C>'))<EOL>cryptorito.encrypt(src, dest, keys)<EOL> | Encrypt a file with the specific GPG keys and write out
to the specified path | f15491:m1 |
def decrypt_file(src, dest): | cryptorito.decrypt(src, dest)<EOL> | Decrypt a file and write it out to the specified path | f15491:m2 |
def encrypt_var(csv_keys): | keys = massage_keys(csv_keys.split('<STR_LIT:U+002C>'))<EOL>data = sys.stdin.read()<EOL>encrypted = cryptorito.encrypt_var(data, keys)<EOL>print(cryptorito.portable_b64encode(encrypted))<EOL> | Encrypt what comes in from stdin and return base64
encrypted against the specified keys, returning on stdout | f15491:m3 |
def decrypt_var(passphrase=None): | encrypted = cryptorito.portable_b64decode(sys.stdin.read())<EOL>print(cryptorito.decrypt_var(encrypted, passphrase))<EOL> | Decrypt what comes in from stdin (base64'd) and
write it out to stdout | f15491:m4 |
def has_key(key): | if not cryptorito.has_gpg_key(key):<EOL><INDENT>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>sys.exit(<NUM_LIT:0>)<EOL> | Checks to see if we actually have a key installed | f15491:m5 |
def import_keybase(useropt): | public_key = None<EOL>u_bits = useropt.split('<STR_LIT::>')<EOL>username = u_bits[<NUM_LIT:0>]<EOL>if len(u_bits) == <NUM_LIT:1>:<EOL><INDENT>public_key = cryptorito.key_from_keybase(username)<EOL><DEDENT>else:<EOL><INDENT>fingerprint = u_bits[<NUM_LIT:1>]<EOL>public_key = cryptorito.key_from_keybase(username, fingerprint)<EOL><DEDENT>if cryptorito.has_gpg_key(public_key['<STR_LIT>']):<EOL><INDENT>sys.exit(<NUM_LIT:2>)<EOL><DEDENT>cryptorito.import_gpg_key(public_key['<STR_LIT>'].encode('<STR_LIT:ascii>'))<EOL>sys.exit(<NUM_LIT:0>)<EOL> | Imports a public GPG key from Keybase | f15491:m6 |
def export_key(key_id): | print(cryptorito.export_gpg_key(key_id))<EOL>sys.exit(<NUM_LIT:0>)<EOL> | Export a GPG key. Note this will be binary. | f15491:m7 |
def do_thing(): | if len(sys.argv) == <NUM_LIT:5> and sys.argv[<NUM_LIT:1>] == "<STR_LIT>":<EOL><INDENT>encrypt_file(sys.argv[<NUM_LIT:2>], sys.argv[<NUM_LIT:3>], sys.argv[<NUM_LIT:4>])<EOL><DEDENT>elif len(sys.argv) == <NUM_LIT:4> and sys.argv[<NUM_LIT:1>] == "<STR_LIT>":<EOL><INDENT>decrypt_file(sys.argv[<NUM_LIT:2>], sys.argv[<NUM_LIT:3>])<EOL><DEDENT>elif len(sys.argv) == <NUM_LIT:3> and sys.argv[<NUM_LIT:1>] == "<STR_LIT>":<EOL><INDENT>encrypt_var(sys.argv[<NUM_LIT:2>])<EOL><DEDENT>elif len(sys.argv) == <NUM_LIT:2> and sys.argv[<NUM_LIT:1>] == "<STR_LIT>":<EOL><INDENT>decrypt_var()<EOL><DEDENT>elif len(sys.argv) == <NUM_LIT:3> and sys.argv[<NUM_LIT:1>] == "<STR_LIT>":<EOL><INDENT>decrypt_var(passphrase=sys.argv[<NUM_LIT:2>])<EOL><DEDENT>elif len(sys.argv) == <NUM_LIT:3> and sys.argv[<NUM_LIT:1>] == "<STR_LIT>":<EOL><INDENT>has_key(sys.argv[<NUM_LIT:2>])<EOL><DEDENT>elif len(sys.argv) == <NUM_LIT:3> and sys.argv[<NUM_LIT:1>] == "<STR_LIT>":<EOL><INDENT>import_keybase(sys.argv[<NUM_LIT:2>])<EOL><DEDENT>elif len(sys.argv) == <NUM_LIT:3> and sys.argv[<NUM_LIT:1>] == "<STR_LIT>":<EOL><INDENT>export_key(sys.argv[<NUM_LIT:2>])<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>",<EOL>file=sys.stderr)<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT> | Execute command line cryptorito actions | f15491:m8 |
def main(): | try:<EOL><INDENT>do_thing()<EOL><DEDENT>except Exception: <EOL><INDENT>traceback.print_exc(sys.stderr)<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT> | My entrypoint, let me show it to you | f15491:m9 |
def clean_tmpdir(path): | if os.path.exists(path) andos.path.isdir(path):<EOL><INDENT>rmtree(path)<EOL><DEDENT> | Invoked atexit, this removes our tmpdir | f15492:m0 |
def ensure_tmpdir(): | path = mkdtemp('<STR_LIT>')<EOL>atexit.register(clean_tmpdir, path)<EOL>return path<EOL> | Ensures a temporary directory exists | f15492:m1 |
def gpg_version(): | cmd = flatten([gnupg_bin(), "<STR_LIT>"])<EOL>output = stderr_output(cmd)<EOL>output = output.split('<STR_LIT:\n>')[<NUM_LIT:0>].split("<STR_LIT:U+0020>")[<NUM_LIT:2>].split('<STR_LIT:.>')<EOL>return tuple([int(x) for x in output])<EOL> | Returns the GPG version | f15492:m2 |
def is_py3(): | return sys.version_info >= (<NUM_LIT:3>, <NUM_LIT:0>)<EOL> | Returns true if this is actually in the future that will
be running entierly on Python 3 | f15492:m3 |
def polite_string(a_string): | if is_py3() and hasattr(a_string, '<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>return a_string.decode('<STR_LIT:utf-8>')<EOL><DEDENT>except UnicodeDecodeError:<EOL><INDENT>return a_string<EOL><DEDENT><DEDENT>return a_string<EOL> | Returns a "proper" string that should work in both Py3/Py2 | f15492:m4 |
def polite_bytes(a_string): | if is_py3():<EOL><INDENT>try:<EOL><INDENT>return bytes(a_string, '<STR_LIT:utf-8>')<EOL><DEDENT>except TypeError:<EOL><INDENT>return a_string<EOL><DEDENT><DEDENT>return a_string<EOL> | Returns "proper" utf-8 bytestring that should work as expected in Py3.
In Py2 it's just gonna be a string because that's all that's needed. | f15492:m5 |
def not_a_string(obj): | my_type = str(type(obj))<EOL>if is_py3():<EOL><INDENT>is_str = my_type.find('<STR_LIT>') < <NUM_LIT:0> and my_type.find('<STR_LIT:str>') < <NUM_LIT:0><EOL>return is_str<EOL><DEDENT>return my_type.find('<STR_LIT:str>') < <NUM_LIT:0> andmy_type.find('<STR_LIT>') < <NUM_LIT:0><EOL> | It's probably not a string, in the sense
that Python2/3 get confused about these things | f15492:m6 |
def actually_flatten(iterable): | remainder = iter(iterable)<EOL>while True:<EOL><INDENT>first = next(remainder) <EOL>is_iter = isinstance(first, collections.Iterable)<EOL>try:<EOL><INDENT>basestring<EOL><DEDENT>except NameError:<EOL><INDENT>basestring = str <EOL><DEDENT>if is_py3() and is_iter and not_a_string(first):<EOL><INDENT>remainder = IT.chain(first, remainder)<EOL><DEDENT>elif (not is_py3()) and is_iter and not isinstance(first, basestring):<EOL><INDENT>remainder = IT.chain(first, remainder)<EOL><DEDENT>else:<EOL><INDENT>yield polite_string(first)<EOL><DEDENT><DEDENT> | Flatten iterables
This is super ugly. There must be a cleaner py2/3 way
of handling this. | f15492:m7 |
def flatten(iterable): | return [x for x in actually_flatten(iterable)]<EOL> | Ensure we are returning an actual list, as that's all we
are ever going to flatten within our little domain | f15492:m8 |
def passphrase_file(passphrase=None): | cmd = []<EOL>pass_file = None<EOL>if not passphrase and '<STR_LIT>' in os.environ:<EOL><INDENT>pass_file = os.environ['<STR_LIT>']<EOL>if not os.path.isfile(pass_file):<EOL><INDENT>raise CryptoritoError('<STR_LIT>')<EOL><DEDENT><DEDENT>elif passphrase:<EOL><INDENT>tmpdir = ensure_tmpdir()<EOL>pass_file = "<STR_LIT>" % tmpdir<EOL>p_handle = open(pass_file, '<STR_LIT:w>')<EOL>p_handle.write(passphrase)<EOL>p_handle.close()<EOL><DEDENT>if pass_file:<EOL><INDENT>cmd = cmd + ["<STR_LIT>", "<STR_LIT>", pass_file]<EOL>vsn = gpg_version()<EOL>if vsn[<NUM_LIT:0>] >= <NUM_LIT:2> and vsn[<NUM_LIT:1>] >= <NUM_LIT:1>:<EOL><INDENT>cmd = cmd + ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT><DEDENT>return cmd<EOL> | Read passphrase from a file. This should only ever be
used by our built in integration tests. At this time,
during normal operation, only pinentry is supported for
entry of passwords. | f15492:m9 |
def gnupg_home(): | if '<STR_LIT>' in os.environ:<EOL><INDENT>gnupghome = os.environ['<STR_LIT>']<EOL>if not os.path.isdir(gnupghome):<EOL><INDENT>raise CryptoritoError("<STR_LIT>")<EOL><DEDENT>return ["<STR_LIT>", gnupghome]<EOL><DEDENT>else:<EOL><INDENT>return []<EOL><DEDENT> | Returns appropriate arguments if GNUPGHOME is set | f15492:m10 |
def gnupg_verbose(): | if LOGGER.getEffectiveLevel() == logging.DEBUG:<EOL><INDENT>return ["<STR_LIT>"]<EOL><DEDENT>return ["<STR_LIT>"]<EOL> | Maybe return the verbose option, maybe do not | f15492:m11 |
def which_bin(cmd): | cmd = ["<STR_LIT>", cmd]<EOL>try:<EOL><INDENT>return stderr_output(cmd).strip().split('<STR_LIT:\n>')[<NUM_LIT:0>]<EOL><DEDENT>except CryptoritoError:<EOL><INDENT>return None<EOL><DEDENT> | Returns the path to a thing, or None | f15492:m12 |
def gnupg_bin(): | for a_bin in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>gpg_output = which_bin(a_bin)<EOL>if gpg_output:<EOL><INDENT>return gpg_output<EOL><DEDENT><DEDENT>raise CryptoritoError("<STR_LIT>")<EOL> | Return the path to the gpg binary.
Note that on some systems this is gpg, and others gpg2. We
try to support both. | f15492:m13 |
def massage_key(key): | return {<EOL>'<STR_LIT>': key['<STR_LIT>'].lower(),<EOL>'<STR_LIT>': key['<STR_LIT>']<EOL>}<EOL> | Massage the keybase return for only what we care about | f15492:m14 |
def keybase_lookup_url(username): | return "<STR_LIT>"% username<EOL> | Returns the URL for looking up a user in Keybase | f15492:m15 |
def fingerprint_from_keybase(fingerprint, kb_obj): | if '<STR_LIT>' in kb_obj and'<STR_LIT>' in kb_obj['<STR_LIT>']:<EOL><INDENT>for key in kb_obj['<STR_LIT>']['<STR_LIT>']:<EOL><INDENT>keyprint = fingerprint_from_var(key).lower()<EOL>fingerprint = fingerprint.lower()<EOL>if fingerprint == keyprint orkeyprint.startswith(fingerprint) orkeyprint.endswith(fingerprint):<EOL><INDENT>return {<EOL>'<STR_LIT>': keyprint,<EOL>'<STR_LIT>': key<EOL>}<EOL><DEDENT><DEDENT><DEDENT>return None<EOL> | Extracts a key matching a specific fingerprint from a
Keybase API response | f15492:m16 |
def key_from_keybase(username, fingerprint=None): | url = keybase_lookup_url(username)<EOL>resp = requests.get(url)<EOL>if resp.status_code == <NUM_LIT:200>:<EOL><INDENT>j_resp = json.loads(polite_string(resp.content))<EOL>if '<STR_LIT>' in j_resp and len(j_resp['<STR_LIT>']) == <NUM_LIT:1>:<EOL><INDENT>kb_obj = j_resp['<STR_LIT>'][<NUM_LIT:0>]<EOL>if fingerprint:<EOL><INDENT>return fingerprint_from_keybase(fingerprint, kb_obj)<EOL><DEDENT>else:<EOL><INDENT>if '<STR_LIT>' in kb_objand '<STR_LIT>' in kb_obj['<STR_LIT>']:<EOL><INDENT>key = kb_obj['<STR_LIT>']['<STR_LIT>']<EOL>return massage_key(key)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return None<EOL> | Look up a public key from a username | f15492:m17 |
def has_gpg_key(fingerprint): | if len(fingerprint) > <NUM_LIT:8>:<EOL><INDENT>fingerprint = fingerprint[-<NUM_LIT:8>:]<EOL><DEDENT>fingerprint = fingerprint.upper()<EOL>cmd = flatten([gnupg_bin(), gnupg_home(), "<STR_LIT>"])<EOL>lines = stderr_output(cmd).split('<STR_LIT:\n>')<EOL>return len([key for key in lines if key.find(fingerprint) > -<NUM_LIT:1>]) == <NUM_LIT:1><EOL> | Checks to see if we have this gpg fingerprint | f15492:m18 |
def fingerprint_from_var(var): | vsn = gpg_version()<EOL>cmd = flatten([gnupg_bin(), gnupg_home()])<EOL>if vsn[<NUM_LIT:0>] >= <NUM_LIT:2> and vsn[<NUM_LIT:1>] < <NUM_LIT:1>:<EOL><INDENT>cmd.append("<STR_LIT>")<EOL><DEDENT>output = polite_string(stderr_with_input(cmd, var)).split('<STR_LIT:\n>')<EOL>if not output[<NUM_LIT:0>].startswith('<STR_LIT>'):<EOL><INDENT>raise CryptoritoError('<STR_LIT>')<EOL><DEDENT>if vsn[<NUM_LIT:0>] >= <NUM_LIT:2> and vsn[<NUM_LIT:1>] < <NUM_LIT:1>:<EOL><INDENT>return output[<NUM_LIT:1>].split('<STR_LIT:=>')[<NUM_LIT:1>].replace('<STR_LIT:U+0020>', '<STR_LIT>')<EOL><DEDENT>return output[<NUM_LIT:1>].strip()<EOL> | Extract a fingerprint from a GPG public key | f15492:m19 |
def fingerprint_from_file(filename): | cmd = flatten([gnupg_bin(), gnupg_home(), filename])<EOL>outp = stderr_output(cmd).split('<STR_LIT:\n>')<EOL>if not outp[<NUM_LIT:0>].startswith('<STR_LIT>'):<EOL><INDENT>raise CryptoritoError('<STR_LIT>')<EOL><DEDENT>return outp[<NUM_LIT:1>].strip()<EOL> | Extract a fingerprint from a GPG public key file | f15492:m20 |
def stderr_handle(): | gpg_stderr = None<EOL>handle = None<EOL>if LOGGER.getEffectiveLevel() > logging.DEBUG:<EOL><INDENT>handle = open(os.devnull, '<STR_LIT:wb>')<EOL>gpg_stderr = handle<EOL><DEDENT>return handle, gpg_stderr<EOL> | Generate debug-level appropriate stderr context for
executing things through subprocess. Normally stderr gets
sent to dev/null but when debugging it is sent to stdout. | f15492:m21 |
def stderr_output(cmd): | handle, gpg_stderr = stderr_handle()<EOL>try:<EOL><INDENT>output = subprocess.check_output(cmd, stderr=gpg_stderr) <EOL>if handle:<EOL><INDENT>handle.close()<EOL><DEDENT>return str(polite_string(output))<EOL><DEDENT>except subprocess.CalledProcessError as exception:<EOL><INDENT>LOGGER.debug("<STR_LIT>", '<STR_LIT:U+0020>'.join(exception.cmd))<EOL>LOGGER.debug("<STR_LIT>", exception.output)<EOL>raise CryptoritoError('<STR_LIT>')<EOL><DEDENT> | Wraps the execution of check_output in a way that
ignores stderr when not in debug mode | f15492:m22 |
def stderr_with_input(cmd, stdin): | handle, gpg_stderr = stderr_handle()<EOL>LOGGER.debug("<STR_LIT>", '<STR_LIT:U+0020>'.join(cmd))<EOL>try:<EOL><INDENT>gpg_proc = subprocess.Popen(cmd, <EOL>stdout=subprocess.PIPE,<EOL>stdin=subprocess.PIPE,<EOL>stderr=gpg_stderr)<EOL>output, _err = gpg_proc.communicate(polite_bytes(stdin))<EOL>if handle:<EOL><INDENT>handle.close()<EOL><DEDENT>return output<EOL><DEDENT>except subprocess.CalledProcessError as exception:<EOL><INDENT>return gpg_error(exception, '<STR_LIT>')<EOL><DEDENT>except OSError as exception:<EOL><INDENT>raise CryptoritoError("<STR_LIT>" % exception.filename)<EOL><DEDENT> | Runs a command, passing something in stdin, and returning
whatever came out from stdout | f15492:m23 |
def import_gpg_key(key): | if not key:<EOL><INDENT>raise CryptoritoError('<STR_LIT>')<EOL><DEDENT>key_fd, key_filename = mkstemp("<STR_LIT>")<EOL>key_handle = os.fdopen(key_fd, '<STR_LIT:w>')<EOL>key_handle.write(polite_string(key))<EOL>key_handle.close()<EOL>cmd = flatten([gnupg_bin(), gnupg_home(), "<STR_LIT>", key_filename])<EOL>output = stderr_output(cmd)<EOL>msg = '<STR_LIT>'<EOL>output_bits = polite_string(output).split('<STR_LIT:\n>')<EOL>return len([line for line in output_bits if line == msg]) == <NUM_LIT:1><EOL> | Imports a GPG key | f15492:m24 |
def export_gpg_key(key): | cmd = flatten([gnupg_bin(), gnupg_verbose(), gnupg_home(),<EOL>"<STR_LIT>", key])<EOL>handle, gpg_stderr = stderr_handle()<EOL>try:<EOL><INDENT>gpg_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, <EOL>stderr=gpg_stderr)<EOL>output, _err = gpg_proc.communicate()<EOL>if handle:<EOL><INDENT>handle.close()<EOL><DEDENT>return portable_b64encode(output)<EOL><DEDENT>except subprocess.CalledProcessError as exception:<EOL><INDENT>LOGGER.debug("<STR_LIT>", '<STR_LIT:U+0020>'.join(exception.cmd))<EOL>LOGGER.debug("<STR_LIT>", exception.output)<EOL>raise CryptoritoError('<STR_LIT>')<EOL><DEDENT> | Exports a GPG key and returns it | f15492:m25 |
def recipients_args(keys): | return [["<STR_LIT>", key.encode('<STR_LIT>')] for key in keys]<EOL> | Returns the list representation of a set of GPG
keys to be used as recipients when encrypting. | f15492:m26 |
def encrypt(source, dest, keys): | cmd = flatten([gnupg_bin(), "<STR_LIT>", "<STR_LIT>", dest, gnupg_verbose(),<EOL>gnupg_home(), recipients_args(keys),<EOL>"<STR_LIT>", source])<EOL>stderr_output(cmd)<EOL>return True<EOL> | Encrypts a file using the given keys | f15492:m27 |
def encrypt_var(source, keys): | cmd = flatten([gnupg_bin(), "<STR_LIT>", "<STR_LIT>", gnupg_verbose(),<EOL>recipients_args(keys)])<EOL>output = stderr_with_input(cmd, source)<EOL>return output<EOL> | Attempts to encrypt a variable | f15492:m28 |
def gpg_error(exception, message): | LOGGER.debug("<STR_LIT>", '<STR_LIT:U+0020>'.join([str(x) for x in exception.cmd]))<EOL>LOGGER.debug("<STR_LIT>", exception.output)<EOL>raise CryptoritoError(message)<EOL> | Handles the output of subprocess errors
in a way that is compatible with the log level | f15492:m29 |
def decrypt_var(source, passphrase=None): | cmd = [gnupg_bin(), "<STR_LIT>", gnupg_home(), gnupg_verbose(),<EOL>passphrase_file(passphrase)]<EOL>return stderr_with_input(flatten(cmd), source)<EOL> | Attempts to decrypt a variable | f15492:m30 |
def decrypt(source, dest=None, passphrase=None): | if not os.path.exists(source):<EOL><INDENT>raise CryptoritoError("<STR_LIT>" % source)<EOL><DEDENT>cmd = [gnupg_bin(), gnupg_verbose(), "<STR_LIT>", gnupg_home(),<EOL>passphrase_file(passphrase)]<EOL>if dest:<EOL><INDENT>cmd.append(["<STR_LIT>", dest])<EOL><DEDENT>cmd.append([source])<EOL>stderr_output(flatten(cmd))<EOL>return True<EOL> | Attempts to decrypt a file | f15492:m31 |
def is_base64(string): | return (not re.match('<STR_LIT>', string)) and(len(string) % <NUM_LIT:4> == <NUM_LIT:0>) andre.match('<STR_LIT>', string)<EOL> | Determines whether or not a string is likely to
be base64 encoded binary nonsense | f15492:m32 |
def portable_b64encode(thing): | if is_py3():<EOL><INDENT>try:<EOL><INDENT>some_bits = bytes(thing, '<STR_LIT:utf-8>')<EOL><DEDENT>except TypeError:<EOL><INDENT>some_bits = thing<EOL><DEDENT>return polite_string(b64encode(some_bits).decode('<STR_LIT:utf-8>'))<EOL><DEDENT>return polite_string(b64encode(thing))<EOL> | Wrap b64encode for Python 2 & 3 | f15492:m33 |
def portable_b64decode(thing): | return b64decode(polite_string(thing))<EOL> | Consistent b64decode in Python 2 & 3 | f15492:m34 |
def __init__(self, message=None): | if message is not None:<EOL><INDENT>super(CryptoritoError, self).__init__(message)<EOL><DEDENT>else:<EOL><INDENT>super(CryptoritoError, self).__init__()<EOL><DEDENT> | The only thing you can pass is a message, but
even that is optional | f15492:c0:m0 |
def analog_linear2_ramp(ramp_data, start_time, end_time, value_final,<EOL>time_subarray): | value_initial = ramp_data["<STR_LIT:value>"]<EOL>value_final2 = ramp_data["<STR_LIT>"]<EOL>interp = (time_subarray - start_time)/(end_time - start_time)<EOL>return value_initial*(<NUM_LIT:1.0> - interp) + value_final2*interp<EOL> | Use this when you want a discontinuous jump at the end of the linear ramp. | f15494:m1 |
def bake(self): | self.unbake()<EOL>for key in self.dct:<EOL><INDENT>self.get_absolute_time(key)<EOL><DEDENT>self.is_baked = True<EOL> | Find absolute times for all keys.
Absolute time is stored in the KeyFrame dictionary as the variable
__abs_time__. | f15494:c0:m1 |
def unbake(self): | for key in self.dct:<EOL><INDENT>self.dct[key].pop('<STR_LIT>', None)<EOL><DEDENT>self.is_baked = False<EOL> | Remove absolute times for all keys. | f15494:c0:m2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.