code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''The only element (which satisfies a condition) or a default. If the predicate is omitted or is None this query returns the only element in the sequence; otherwise, it returns the only element in the sequence for which the predicate evaluates to True. A default value is return...
def single_or_default(self, default, predicate=None)
The only element (which satisfies a condition) or a default. If the predicate is omitted or is None this query returns the only element in the sequence; otherwise, it returns the only element in the sequence for which the predicate evaluates to True. A default value is returned if there...
4.614562
1.320142
3.495505
'''The last element in a sequence (optionally satisfying a predicate). 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. Exceptions are rai...
def last(self, predicate=None)
The last element in a sequence (optionally satisfying a predicate). 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. Exceptions are raised if ther...
4.386599
1.408931
3.113424
'''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...
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 th...
4.042559
1.398416
2.890812
'''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 ...
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 p...
4.096142
1.749642
2.341132
'''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 ...
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 ...
4.715683
1.900155
2.481736
'''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._it...
def to_list(self)
Convert the source sequence to a list. Note: This method uses immediate execution.
11.072576
7.518239
1.472762
'''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 = t...
def to_tuple(self)
Convert the source sequence to a tuple. Note: This method uses immediate execution.
7.845858
4.692633
1.671952
'''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(...
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().
6.055312
2.87161
2.108682
'''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)...
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.
3.333511
2.424346
1.375014
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_selec...
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...
2.212348
2.049208
1.079611
'''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 wil...
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 insert...
5.768906
1.446192
3.989031
''' 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. ...
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: ...
3.597397
1.90985
1.883602
''' 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 ...
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...
6.38733
1.450937
4.402209
''' 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. Default...
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 ...
6.716181
2.074329
3.237761
''' 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. Defaul...
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 ...
6.0913
1.789843
3.403259
'''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 ...
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 ...
5.93219
2.020807
2.935555
return super(Lookup, self).to_dictionary(key_selector, value_selector)
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...
4.364577
8.85511
0.492888
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)
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 call...
2.942603
2.792874
1.053611
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 sp...
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. Ra...
null
null
null
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. ''' ...
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.
null
null
null
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 an iterable into chunks. Returns an iterator over partitions.
null
null
null
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...
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 th...
null
null
null
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 ...
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. ...
null
null
null
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...
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 ...
null
null
null
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...
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 th...
null
null
null
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 ...
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 sup...
null
null
null
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]
add with carry returns a two element tuple of the form (result, carry)
4.141492
4.387313
0.94397
def convert(self, value, *args, **kwargs): # pylint: disable=arguments-differ value = os.path.expanduser(value) return super(ExpandPath, self).convert(value, *args, **kwargs)
Take a path with $HOME variables and resolve it to full path.
null
null
null
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 = [r...
def make_table(headers=None, rows=None)
Make a table from headers and rows.
2.042592
2.021423
1.010472
@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 callabl...
def _dual_decorator(func)
This is a decorator that converts a paramaterized decorator for no-param use. source: http://stackoverflow.com/questions/3888158
2.402858
2.407242
0.998179
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, _)
Usage: help [<command>] With no arguments, print the form of all supported commands. With an argument, print a detailed explanation of a command.
3.585571
4.105865
0.87328
# 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] ...
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 st...
3.330084
3.29793
1.00975
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'....
def help_text(cls)
Return a slack-formatted list of commands with their usage.
4.63961
4.32004
1.073974
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_ment...
def run_forever(self)
Run the bot, blocking forever.
2.557544
2.408933
1.061692
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 identi...
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.
4.93189
4.644651
1.061843
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: re...
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.
3.38786
2.823947
1.19969
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: ...
def _handle_long_response(self, res)
Splits messages that are too long into multiple events :param res: a slack response string or dict
2.730892
2.49529
1.094419
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)
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>`__.
2.246493
2.535723
0.885938
self.slack.chat.post_message(**message) self.log.debug("sent api message %r", 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.
7.542798
6.333869
1.190867
for validator in self.__validators__.values(): yield validator if self.validators: for validator in self.validators: yield validator
def _validators(self)
Iterate across the complete set of child validators.
4.362237
3.416689
1.276744
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)
Get a suitable user agent for identifying the CLI process.
4.272002
3.741296
1.141851
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" % {...
def pretty_print_list_info(num_results, page_info=None, suffix=None)
Pretty print list info, with pagination, for user display.
1.888311
1.857656
1.016502
table = make_table(headers=headers, rows=rows) pretty_print_table_instance(table)
def pretty_print_table(headers, rows)
Pretty print a table from headers and rows.
5.56936
5.551692
1.003182
assert isinstance(table, Table) def pretty_print_row(styled, plain): click.secho( " | ".join( v + " " * (table.column_widths[k] - len(plain[k])) for k, v in enumerate(styled) ) ) pretty_print_row(table.headers, table.pla...
def pretty_print_table_instance(table)
Pretty print a table instance.
3.308611
3.273329
1.010779
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 ....
def print_rate_limit_info(opts, rate_info, atexit=False)
Tell the user when we're being rate limited.
4.737605
4.445999
1.065588
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.d...
def maybe_print_as_json(opts, data, page_info=None)
Maybe print data as JSON.
2.678748
2.595949
1.031895
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.ec...
def confirm_operation(prompt, prefix=None, assume_yes=False, err=False)
Prompt the user for confirmation for dangerous actions.
4.125529
4.056183
1.017096
# 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)
Ensure that login is not blank.
3.977664
2.992561
1.329184
# 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() ...
def create_config_files(ctx, opts, api_key)
Create default config files.
2.774162
2.720346
1.019783
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): ...
def token(ctx, opts, login, password)
Retrieve your API authentication token/key.
3.607535
3.509756
1.027859
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...
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'.
2.462421
2.628096
0.93696
# 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) )) # ...
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.
2.868277
2.76734
1.036474
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)
Usage: import_and_wrap_deprecated('conda.common.connection', locals()) # looks for conda.common.connection.__all__
3.54851
3.570168
0.993934
def _ModuleProxy(module, depr): # 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 get...
def deprecate_module_with_proxy(module_name, module_dict, deprecated_attributes=None)
Usage: deprecate_module_with_proxy(__name__, locals()) # at bottom of module
2.857168
2.800245
1.020328
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 ...
def native(self, value, context=None)
Convert a foreign value to a native boolean.
3.170758
2.80582
1.130065
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: retu...
def foreign(self, value, context=None)
Convert a native value to a textual boolean.
6.112002
5.50491
1.110282
root_path = __file__ return os.path.dirname(os.path.realpath(root_path))
def get_root_path()
Get the root path for the application.
3.359626
2.993196
1.122421
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)
Read the specific file into a string in its entirety.
2.339635
2.313446
1.01132
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()
Grok the readme, turn it into whine (rst).
3.454983
3.479411
0.992979
rvec = np.random.randn(3) rvec = rvec / np.linalg.norm(rvec) return rvec
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 ...
3.812425
3.660586
1.041479
# 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.linal...
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
2.943998
2.630059
1.119366
r 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 ...
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...
3.923179
4.450315
0.881551
@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 sy...
def common_package_action_options(f)
Add common options for package actions.
2.670927
2.563211
1.042024
@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="CLOUDS...
def common_cli_config_options(f)
Add common CLI config options to commands.
1.966887
1.90896
1.030345
@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"]), ...
def common_cli_output_options(f)
Add common CLI output options to commands.
2.491078
2.372654
1.049912
@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=...
def common_cli_list_options(f)
Add common list options to commands.
2.517193
2.366664
1.063604
@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 ...
def common_api_auth_options(f)
Add common API authentication options to commands.
2.751166
2.480729
1.109015
@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="CL...
def initialise_api(f)
Initialise the Cloudsmith API for use.
2.406286
2.364902
1.017499
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...
def list_entitlements(owner, repo, page, page_size, show_tokens)
Get a list of entitlements on a repository.
3.092397
3.078719
1.004443
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...
def create_entitlement(owner, repo, name, token, show_tokens)
Create an entitlement in a repository.
3.521568
3.490401
1.008929
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)
Delete an entitlement from a repository.
5.496064
5.152373
1.066705
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, ...
def update_entitlement(owner, repo, identifier, name, token, show_tokens)
Update an entitlement in a repository.
3.236351
3.210062
1.00819
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)
Refresh an entitlement in a repository.
4.560652
4.347036
1.049141
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.fr...
def sync_entitlements(owner, repo, source, show_tokens)
Sync entitlements from another repository.
4.330822
4.291417
1.009182
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_cal...
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.
1.932423
1.895113
1.019687
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) i...
def get_api_client(cls)
Get an API client (with configuration).
2.71659
2.536165
1.071141
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)
Configure a new API key.
2.550923
2.565747
0.994222
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":...
def validate_request_file_upload(owner, repo, filepath, md5_checksum=None)
Validate parameters for requesting a file upload.
4.478097
4.519207
0.990903
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"...
def request_file_upload(owner, repo, filepath, md5_checksum=None)
Request a new package file upload (for creating packages).
5.258687
5.00002
1.051733
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.Configu...
def upload_file(upload_url, upload_fields, filepath, callback=None)
Upload a pre-signed file to Cloudsmith.
2.912233
2.750705
1.058722
# 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=us...
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.
2.430359
2.394999
1.014764
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 ...
def get_details(exc)
Get the details from the exception.
2.446302
2.315411
1.056531
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)
Get a hint to show to the user (if any).
2.542249
2.530165
1.004776
key = key.replace('-', '_').replace(' ', '_') return str("_".join((x.upper() for x in (app_name, key))))
def make_env_key(app_name, key)
Creates an environment key-equivalent for the given key
4.855369
4.717243
1.029281
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)
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()`.
7.516796
6.444967
1.166305
os.environ.pop(make_env_key(self.appname, key), None) self._registered_env_keys.discard(key) self._clear_memoization()
def unset_env(self, key)
Removes an environment variable using the prepended app_name convention with `key`.
6.312657
5.4167
1.165406
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)
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.
10.432885
8.985599
1.161067
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.confi...
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 ...
2.778157
3.078034
0.902575
# 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: back...
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.
1.637791
1.621879
1.00981
if self._data is None: self._data = self.response.content.decode("utf-8") return self._data
def data(self)
Get the content for the response (lazily decoded).
3.980421
2.402385
1.656862
return self.response.headers.get(name, default)
def getheader(self, name, default=None)
Return a given response header.
5.250336
3.724944
1.409507
# 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: ...
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, `a...
2.377231
2.411271
0.985883
return os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir))
def get_root_path()
Get the root directory for the application.
2.433242
2.109681
1.15337
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)
Read the specific file into a string in its entirety.
2.990326
2.873445
1.040676
checksum = hashlib.md5() with click.open_file(filepath, "rb") as f: def update_chunk(): buf = f.read(blocksize) if buf: checksum.update(buf) return bool(buf) while update_chunk(): pass return checksum.hexdi...
def calculate_file_md5(filepath, blocksize=2 ** 20)
Calculate an MD5 hash for a file.
3.082067
2.903409
1.061534
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)
Construct page and page size kwargs (if present).
1.801902
1.562836
1.152969
query_kwargs = {} query = kwargs.pop("query") if query: query_kwargs["query"] = query return query_kwargs
def get_query_kwargs(**kwargs)
Construct page and page size kwargs (if present).
3.353712
3.093843
1.083996
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)
Return a PEP440-compliant version derived from the git status. If that fails for any reason, return the changeset hash.
4.43832
3.955071
1.122185
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)
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 s...
3.222565
3.527201
0.913632
"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)
Counts the time spent in some context
5.578517
4.645269
1.200903