text
stringlengths
18
773k
def decode_arr(data): """Extract a numpy array from a base64 buffer""" data = data.encode('utf-8') return frombuffer(base64.b64decode(data), float64)
def run_func(self, func_path, *func_args, **kwargs): """Run a function in Matlab and return the result. Parameters ---------- func_path: str Name of function to run or a path to an m-file. func_args: object, optional Function args to send to the function....
def _bind_method(self, name, unconditionally=False): """Generate a Matlab function and bind it to the instance This is where the magic happens. When an unknown attribute of the Matlab class is requested, it is assumed to be a call to a Matlab function, and is generated and bound to the ...
def format_line(line): """ Format a line of Matlab into either a markdown line or a code line. Parameters ---------- line : str The line of code to be formatted. Formatting occurs according to the following rules: - If the line starts with (at least) two %% signs, a new cel...
def lines_to_notebook(lines, name=None): """ Convert the lines of an m file into an IPython notebook Parameters ---------- lines : list A list of strings. Each element is a line in the m file Returns ------- notebook : an IPython NotebookNode class instance, containing the ...
def convert_mfile(mfile, outfile=None): """ Convert a Matlab m-file into a Matlab notebook in ipynb format Parameters ---------- mfile : string Full path to a matlab m file to convert outfile : string (optional) Full path to the output ipynb file """ lines = mfile_to_l...
def load_ipython_extension(ip, **kwargs): """Load the extension in IPython.""" global _loaded if not _loaded: ip.register_magics(MatlabMagics(ip, **kwargs)) _loaded = True
def post_gist(content, description='', filename='file', auth=False): """Post some text to a Gist, and return the URL.""" post_data = json.dumps({ "description": description, "public": True, "files": { filename: { "content": content } } }).encode('utf-8') ...
def get_pull_request(project, num, auth=False): """get pull request info by number """ url = "https://api.github.com/repos/{project}/pulls/{num}".format(project=project, num=num) if auth: header = make_auth_header() else: header = None response = requests.get(url, headers=header...
def get_pull_request_files(project, num, auth=False): """get list of files in a pull request""" url = "https://api.github.com/repos/{project}/pulls/{num}/files".format(project=project, num=num) if auth: header = make_auth_header() else: header = None return get_paged_request(url, hea...
def get_paged_request(url, headers=None, **params): """get a full list, handling APIv3's paging""" results = [] params.setdefault("per_page", 100) while True: if '?' in url: params = None print("fetching %s" % url, file=sys.stderr) else: print("fetchin...
def get_pulls_list(project, auth=False, **params): """get pull request list""" params.setdefault("state", "closed") url = "https://api.github.com/repos/{project}/pulls".format(project=project) if auth: headers = make_auth_header() else: headers = None pages = get_paged_request(ur...
def encode_multipart_formdata(fields, boundary=None): """ Encode a dictionary of ``fields`` using the multipart/form-data mime format. :param fields: Dictionary of fields or list of (key, value) field tuples. The key is treated as the field name, and the value as the body of the form-data ...
def post_download(project, filename, name=None, description=""): """Upload a file to the GitHub downloads area""" if name is None: name = os.path.basename(filename) with open(filename, 'rb') as f: filedata = f.read() url = "https://api.github.com/repos/{project}/downloads".format(projec...
def is_executable_file(path): """Checks that path is an executable regular file (or a symlink to a file). This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``, but on some platforms :func:`os.access` gives us the wrong answer, so this checks permission bits directly. Note ----...
def which(filename): '''This takes a given filename; tries to find it in the environment path; then checks if it is executable. This returns the full path to the filename if found and executable. Otherwise this returns None. Note ---- This function is taken from the pexpect module, see module d...
def build_matlab(static=False): """build the messenger mex for MATLAB static : bool Determines if the zmq library has been statically linked. If so, it will append the command line option -DZMQ_STATIC when compiling the mex so it matches libzmq. """ cfg = get_config() # To d...
def add_method(function, klass, name=None): '''Add an existing function to a class as a method. Note: Consider using the extend decorator as a more readable alternative to using this function directly. Args: function: The function to be added to the class klass. klass: Th...
def extend(klass, name=None): '''A function decorator for extending an existing class. Use as a decorator for functions to add to an existing class. Args: klass: The class to be decorated. name: The name the new method is to be given in the klass class. Returns: A ...
def select( self, selector): '''Transforms each element of a sequence into a new form. Each element of the source is transformed through a selector function to produce a corresponding element in teh result sequence. If the selector is identity the method will re...
def select_with_index( self, selector=IndexedElement, transform=identity): '''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 elem...
def select_with_correspondence( self, selector, result_selector=KeyedElement): '''Apply a callable to each element in an input sequence, generating a new sequence of 2-tuples where the first element is the input value and the second is the transformed input va...
def select_many( self, collection_selector=identity, result_selector=identity): '''Projects each element of a sequence to an intermediate new sequence, flattens the resulting sequences into one sequence and optionally transforms the flattened sequence using a ...
def select_many_with_index( self, collection_selector=IndexedElement, result_selector=lambda source_element, collection_element: collection_element): '''Projects each element of a sequence to an intermediate new sequence, incorporati...
def select_many_with_correspondence( self, collection_selector=identity, result_selector=KeyedElement): '''Projects each element of a sequence to an intermediate new sequence, and flattens the resulting sequence, into one sequence and uses a selector function ...
def group_by(self, key_selector=identity, element_selector=identity, result_selector=lambda key, grouping: grouping): '''Groups the elements according to the value of a key extracted by a selector function. Note: This method has different behaviour to itertools...
def where(self, predicate): '''Filters elements according to whether they match a predicate. Note: This method uses deferred execution. Args: predicate: A unary function which is applied to each element in the source sequence. Source elements for which the predicate...
def of_type(self, classinfo): '''Filters elements according to whether they are of a certain type. Note: This method uses deferred execution. Args: classinfo: If classinfo is neither a class object nor a type object it may be a tuple of class or type objects, or may...
def order_by(self, key_selector=identity): '''Sorts by a key in ascending order. Introduces a primary sorting order to the sequence. Additional sort criteria should be specified by subsequent calls to then_by() and then_by_descending(). Calling order_by() or order_by_descending() on ...
def take(self, count=1): '''Returns a specified number of elements from the start of a sequence. If the source sequence contains fewer elements than requested only the available elements will be returned and no exception will be raised. Note: This method uses deferred execution. ...
def take_while(self, predicate): '''Returns elements from the start while the predicate is True. Note: This method uses deferred execution. Args: predicate: A function returning True or False with which elements will be tested. Returns: A Querya...
def skip(self, count=1): '''Skip the first count contiguous elements of the source sequence. If the source sequence contains fewer than count elements returns an empty sequence and does not raise an exception. Note: This method uses deferred execution. Args: count:...
def skip_while(self, predicate): '''Omit elements from the start for which a predicate is True. Note: This method uses deferred execution. Args: predicate: A single argument predicate function. Returns: A Queryable over the sequence of elements beginning with t...
def concat(self, second_iterable): '''Concatenates two sequences. Note: This method uses deferred execution. Args: second_iterable: The sequence to concatenate on to the sequence. Returns: A Queryable over the concatenated sequences. Raises: ...
def reverse(self): '''Returns the sequence reversed. Note: This method uses deferred execution, but the whole source sequence is consumed once execution commences. Returns: The source sequence in reverse order. Raises: ValueError: If the Queryable i...
def element_at(self, index): '''Return the element at ordinal index. Note: This method uses immediate execution. Args: index: The index of the element to be returned. Returns: The element at ordinal index in the source sequence. Raises: Val...
def count(self, predicate=None): '''Return the number of elements (which match an optional predicate). Note: This method uses immediate execution. Args: predicate: An optional unary predicate function used to identify elements which will be counted. The single posit...
def any(self, predicate=None): '''Determine if the source sequence contains any elements which satisfy the predicate. Only enough of the sequence to satisfy the predicate once is consumed. Note: This method uses immediate execution. Args: predicate: An optional sin...
def all(self, predicate=bool): '''Determine if all elements in the source sequence satisfy a condition. All of the source sequence will be consumed. Note: This method uses immediate execution. Args: predicate (callable): An optional single argument function used to ...
def sum(self, selector=identity): '''Return the arithmetic sum of the values in the sequence.. All of the source sequence will be consumed. Note: This method uses immediate execution. Args: selector: An optional single argument function which will be used t...
def average(self, selector=identity): '''Return the arithmetic mean of the values in the sequence.. All of the source sequence will be consumed. Note: This method uses immediate execution. Args: selector: An optional single argument function which will be used ...
def contains(self, value, equality_comparer=operator.eq): '''Determines whether the sequence contains a particular value. Execution is immediate. Depending on the type of the sequence, all or none of the sequence may be consumed by this operation. Note: This method uses immediate execu...
def default_if_empty(self, default): '''If the source sequence is empty return a single element sequence containing the supplied default value, otherwise return the source sequence unchanged. Note: This method uses deferred execution. Args: default: The element to b...
def distinct(self, selector=identity): '''Eliminate duplicate elements from a sequence. Note: This method uses deferred execution. Args: selector: An optional single argument function the result of which is the value compared for uniqueness against elements already ...
def difference(self, second_iterable, selector=identity): '''Returns those elements which are in the source sequence which are not in the second_iterable. This method is equivalent to the Except() LINQ operator, renamed to a valid Python identifier. Note: This method uses defer...
def intersect(self, second_iterable, selector=identity): '''Returns those elements which are both in the source sequence and in the second_iterable. Note: This method uses deferred execution. Args: second_iterable: Elements are returned if they are also in the ...
def union(self, second_iterable, selector=identity): '''Returns those elements which are either in the source sequence or in the second_iterable, or in both. Note: This method uses deferred execution. Args: second_iterable: Elements from this sequence are returns if they ...
def join(self, inner_iterable, outer_key_selector=identity, inner_key_selector=identity, result_selector=lambda outer, inner: (outer, inner)): '''Perform an inner join with a second sequence using selected keys. The order of elements from outer is maintained. For each of these...
def group_join(self, inner_iterable, outer_key_selector=identity, inner_key_selector=identity, result_selector=lambda outer, grouping: grouping): '''Match elements of two sequences using keys and group the results. The group_join() query produces a hierarchical result, with all of the ...
def first(self, predicate=None): '''The first element in a sequence (optionally satisfying a predicate). If the predicate is omitted or is None this query returns the first element in the sequence; otherwise, it returns the first element in the sequence for which the predicate evaluates...
def first_or_default(self, default, predicate=None): '''The first element (optionally satisfying a predicate) or a default. If the predicate is omitted or is None this query returns the first element in the sequence; otherwise, it returns the first element in the sequence for which the ...
def single(self, predicate=None): '''The only element (which satisfies a condition). 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. Exceptions a...
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 predicat...
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 ...
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 pred...
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 immed...
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...
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 ...
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._iter...
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(): ...
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...
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...
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 ...
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 ...
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 m...
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...
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...
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 func...
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. ...
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 si...
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...
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. ''' ...
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 ="...
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...
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 ...
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...
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...
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 ...
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...
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 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) p...
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]) an...
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: ...
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...
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(...
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'] ...
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 " % ...
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. """ re...
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 ...
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/...
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 _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 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_v...
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...
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_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])) ...
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: retu...
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_dic...
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 = "%(...
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