text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_smt_userid(): """Get the userid of smt server""" cmd = ["sudo", "/sbin/vmcp", "query userid"] try: userid = subprocess.check_output(cmd, close_fds=True, stderr=subprocess.STDOUT) userid = bytes.decode(u...
[ "def", "get_smt_userid", "(", ")", ":", "cmd", "=", "[", "\"sudo\"", ",", "\"/sbin/vmcp\"", ",", "\"query userid\"", "]", "try", ":", "userid", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "close_fds", "=", "True", ",", "stderr", "=", "subproce...
40.153846
0.001873
def macro_state(self, micro_state): """Translate a micro state to a macro state Args: micro_state (tuple[int]): The state of the micro nodes in this coarse-graining. Returns: tuple[int]: The state of the macro system, translated as specified ...
[ "def", "macro_state", "(", "self", ",", "micro_state", ")", ":", "assert", "len", "(", "micro_state", ")", "==", "len", "(", "self", ".", "micro_indices", ")", "# TODO: only reindex if this coarse grain is not already from 0..n?", "# make_mapping calls this in a tight loop ...
36.16129
0.001738
def makeMicroRegressionTable(out_filename, micro_data): ''' Make the micro regression or (cross section regression) table for the paper, saving it to a tex file in the tables folder. Also makes two partial tables for the slides. Parameters ---------- out_filename : str Name of the fil...
[ "def", "makeMicroRegressionTable", "(", "out_filename", ",", "micro_data", ")", ":", "coeffs", "=", "np", ".", "zeros", "(", "(", "6", ",", "2", ")", ")", "+", "np", ".", "nan", "stdevs", "=", "np", ".", "zeros", "(", "(", "6", ",", "2", ")", ")"...
54.744
0.021817
def image_running(name, system_image, kickstart_image=None, issu=True, **kwargs): ''' Ensure the NX-OS system image is running on the device. name Name of the salt state task system_image Name of the system image file on bootflash: kickstart_image Name of the kickstart ima...
[ "def", "image_running", "(", "name", ",", "system_image", ",", "kickstart_image", "=", "None", ",", "issu", "=", "True", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'changes'", ":", ...
33.014925
0.001756
def _resize_port_models_list(port_models, rel_pos_key, factor, gaphas_editor=True): """ Resize relative positions a list of (data or logical) port models """ for port_m in port_models: old_rel_pos = port_m.get_meta_data_editor(for_gaphas=gaphas_editor)[rel_pos_key] port_m.set_meta_data_editor(re...
[ "def", "_resize_port_models_list", "(", "port_models", ",", "rel_pos_key", ",", "factor", ",", "gaphas_editor", "=", "True", ")", ":", "for", "port_m", "in", "port_models", ":", "old_rel_pos", "=", "port_m", ".", "get_meta_data_editor", "(", "for_gaphas", "=", "...
78.4
0.010101
def setImembPtr(self): """Set PtrVector to point to the i_membrane_""" jseg = 0 for sec in list(self.secs.values()): hSec = sec['hObj'] for iseg, seg in enumerate(hSec): self.imembPtr.pset(jseg, seg._ref_i_membrane_) # notice the underscore at the end (i...
[ "def", "setImembPtr", "(", "self", ")", ":", "jseg", "=", "0", "for", "sec", "in", "list", "(", "self", ".", "secs", ".", "values", "(", ")", ")", ":", "hSec", "=", "sec", "[", "'hObj'", "]", "for", "iseg", ",", "seg", "in", "enumerate", "(", "...
43
0.011396
def _pyqt4(): """Initialise PyQt4""" import sip # Validation of envivornment variable. Prevents an error if # the variable is invalid since it's just a hint. try: hint = int(QT_SIP_API_HINT) except TypeError: hint = None # Variable was None, i.e. not set. except ValueError...
[ "def", "_pyqt4", "(", ")", ":", "import", "sip", "# Validation of envivornment variable. Prevents an error if", "# the variable is invalid since it's just a hint.", "try", ":", "hint", "=", "int", "(", "QT_SIP_API_HINT", ")", "except", "TypeError", ":", "hint", "=", "None...
32.018868
0.000286
def row_iter(self): """Get an iterator over all rows in the Sudoku""" for k in utils.range_(self.side): yield self.row(k)
[ "def", "row_iter", "(", "self", ")", ":", "for", "k", "in", "utils", ".", "range_", "(", "self", ".", "side", ")", ":", "yield", "self", ".", "row", "(", "k", ")" ]
36.5
0.013423
def length_from_nodelist(self, nodelist): """Returns the route length (cost) from the first to the last node in nodelist""" cost = 0 for n1, n2 in zip(nodelist[0:len(nodelist) - 1], nodelist[1:len(nodelist)]): cost += self._problem.distance(n1, n2) return cost
[ "def", "length_from_nodelist", "(", "self", ",", "nodelist", ")", ":", "cost", "=", "0", "for", "n1", ",", "n2", "in", "zip", "(", "nodelist", "[", "0", ":", "len", "(", "nodelist", ")", "-", "1", "]", ",", "nodelist", "[", "1", ":", "len", "(", ...
37.375
0.013072
def make(self): """ Evaluate the command, and write it to a file. """ eval = self.command.eval() with open(self.filename, 'w') as f: f.write(eval)
[ "def", "make", "(", "self", ")", ":", "eval", "=", "self", ".", "command", ".", "eval", "(", ")", "with", "open", "(", "self", ".", "filename", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "eval", ")" ]
35.6
0.010989
def main(): """Test program for verifying this files functionality.""" global __verbose # Parse CMD args parser = argparse.ArgumentParser(description='DFU Python Util') #parser.add_argument("path", help="file path") parser.add_argument( "-l", "--list", help="list available DFU de...
[ "def", "main", "(", ")", ":", "global", "__verbose", "# Parse CMD args", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'DFU Python Util'", ")", "#parser.add_argument(\"path\", help=\"file path\")", "parser", ".", "add_argument", "(", "\"-l\...
23.714286
0.002169
def WriteBlobsWithUnknownHashes( self, blobs_data): """Calculates hash ids and writes contents of given data blobs. Args: blobs_data: An iterable of bytes. Returns: A list of rdf_objects.BlobID objects with each blob id corresponding to an element in the original blobs_data argumen...
[ "def", "WriteBlobsWithUnknownHashes", "(", "self", ",", "blobs_data", ")", ":", "blobs_ids", "=", "[", "rdf_objects", ".", "BlobID", ".", "FromBlobData", "(", "d", ")", "for", "d", "in", "blobs_data", "]", "self", ".", "WriteBlobs", "(", "dict", "(", "zip"...
33.214286
0.002092
def tokenize_line_comment(text): r"""Process a line comment :param Buffer text: iterator over line, with current position >>> tokenize_line_comment(Buffer('hello %world')) >>> tokenize_line_comment(Buffer('%hello world')) '%hello world' >>> tokenize_line_comment(Buffer('%hello\n world')) '...
[ "def", "tokenize_line_comment", "(", "text", ")", ":", "result", "=", "TokenWithPosition", "(", "''", ",", "text", ".", "position", ")", "if", "text", ".", "peek", "(", ")", "==", "'%'", "and", "text", ".", "peek", "(", "-", "1", ")", "!=", "'\\\\'",...
33.529412
0.001706
def make_properties_list(self, field): """Fill the ``field`` into a properties list and return it. :param dict field: the content of the property list to make :return: field_list instance filled with given field :rtype: nodes.field_list """ properties_list = nodes.field...
[ "def", "make_properties_list", "(", "self", ",", "field", ")", ":", "properties_list", "=", "nodes", ".", "field_list", "(", ")", "# changing the order of elements in this list affects", "# the order in which they are displayed", "property_names", "=", "[", "'label'", ",", ...
38.765957
0.001071
def grid_to_obj(cls, file_path=None, text='', edges=None, columns=None, eval_cells=True, key_on=None): """ This will convert a grid file or grid text into a seaborn table and return it :param file_path: str of the path to the file :param text: str of ...
[ "def", "grid_to_obj", "(", "cls", ",", "file_path", "=", "None", ",", "text", "=", "''", ",", "edges", "=", "None", ",", "columns", "=", "None", ",", "eval_cells", "=", "True", ",", "key_on", "=", "None", ")", ":", "edges", "=", "edges", "if", "edg...
47.321429
0.002219
def get_dag_run_state(dag_id, execution_date): """Return the task object identified by the given dag_id and task_id.""" dagbag = DagBag() # Check DAG exists. if dag_id not in dagbag.dags: error_message = "Dag id {} not found".format(dag_id) raise DagNotFound(error_message) # Get D...
[ "def", "get_dag_run_state", "(", "dag_id", ",", "execution_date", ")", ":", "dagbag", "=", "DagBag", "(", ")", "# Check DAG exists.", "if", "dag_id", "not", "in", "dagbag", ".", "dags", ":", "error_message", "=", "\"Dag id {} not found\"", ".", "format", "(", ...
33.47619
0.001383
def diff_xIndex(self, diffs, loc): """loc is a location in text1, compute and return the equivalent location in text2. e.g. "The cat" vs "The big cat", 1->1, 5->8 Args: diffs: Array of diff tuples. loc: Location within text1. Returns: Location within text2. """ chars1 = 0 ...
[ "def", "diff_xIndex", "(", "self", ",", "diffs", ",", "loc", ")", ":", "chars1", "=", "0", "chars2", "=", "0", "last_chars1", "=", "0", "last_chars2", "=", "0", "for", "x", "in", "range", "(", "len", "(", "diffs", ")", ")", ":", "(", "op", ",", ...
28.935484
0.009709
def all(cls, start_position="", max_results=100, qb=None): """ :param start_position: :param max_results: The max number of entities that can be returned in a response is 1000. :param qb: :return: Returns list """ return cls.where("", start_position=start_position...
[ "def", "all", "(", "cls", ",", "start_position", "=", "\"\"", ",", "max_results", "=", "100", ",", "qb", "=", "None", ")", ":", "return", "cls", ".", "where", "(", "\"\"", ",", "start_position", "=", "start_position", ",", "max_results", "=", "max_result...
43.25
0.011331
def load_all_assistants(cls, superassistants): """Fills self._assistants with loaded YamlAssistant instances of requested roles. Tries to use cache (updated/created if needed). If cache is unusable, it falls back to loading all assistants. Args: roles: list of required assi...
[ "def", "load_all_assistants", "(", "cls", ",", "superassistants", ")", ":", "# mapping of assistant roles to lists of top-level assistant instances", "_assistants", "=", "{", "}", "# {'crt': CreatorAssistant, ...}", "superas_dict", "=", "dict", "(", "map", "(", "lambda", "a...
52.314286
0.008043
def _parse_process_name(name_str): """Parses the process string and returns the process name and its directives Process strings my contain directive information with the following syntax:: proc_name={'directive':'val'} This method parses this string and returns the...
[ "def", "_parse_process_name", "(", "name_str", ")", ":", "directives", "=", "None", "fields", "=", "name_str", ".", "split", "(", "\"=\"", ")", "process_name", "=", "fields", "[", "0", "]", "if", "len", "(", "fields", ")", "==", "2", ":", "_directives", ...
32
0.00129
def ip_address(self, container: Container ) -> Union[IPv4Address, IPv6Address]: """ The IP address used by a given container, or None if no IP address has been assigned to that container. """ r = self.__api.get('containers/{}/ip'.format(conta...
[ "def", "ip_address", "(", "self", ",", "container", ":", "Container", ")", "->", "Union", "[", "IPv4Address", ",", "IPv6Address", "]", ":", "r", "=", "self", ".", "__api", ".", "get", "(", "'containers/{}/ip'", ".", "format", "(", "container", ".", "uid"...
39
0.009112
def import_event_modules(): """Import all events declared for all currently installed apps This function walks through the list of installed apps and tries to import a module named `EVENTS_MODULE_NAME`. """ for installed_app in getsetting('INSTALLED_APPS'): module_name = u'{}.{}'.format(ins...
[ "def", "import_event_modules", "(", ")", ":", "for", "installed_app", "in", "getsetting", "(", "'INSTALLED_APPS'", ")", ":", "module_name", "=", "u'{}.{}'", ".", "format", "(", "installed_app", ",", "EVENTS_MODULE_NAME", ")", "try", ":", "import_module", "(", "m...
36.416667
0.002232
def match(m_templ, *m_args): """ :param m_templ: a meta template string :param m_args: all arguments :returns: template, args Here is an example of usage: >>> match('SELECT * FROM job WHERE id=?x', 1) ('SELECT * FROM job WHERE id=?', (1,)) """ # strip commented lines m_templ = ...
[ "def", "match", "(", "m_templ", ",", "*", "m_args", ")", ":", "# strip commented lines", "m_templ", "=", "'\\n'", ".", "join", "(", "line", "for", "line", "in", "m_templ", ".", "splitlines", "(", ")", "if", "not", "line", ".", "lstrip", "(", ")", ".", ...
31.714286
0.001458
def _indices(self, indices): """Turn all string indices into int indices, preserving ellipsis.""" if isinstance(indices, tuple): out = [] dim = 0 for i, index in enumerate(indices): if index is Ellipsis: out.append(index) dim = len(self.shape) - len(indices) + i ...
[ "def", "_indices", "(", "self", ",", "indices", ")", ":", "if", "isinstance", "(", "indices", ",", "tuple", ")", ":", "out", "=", "[", "]", "dim", "=", "0", "for", "i", ",", "index", "in", "enumerate", "(", "indices", ")", ":", "if", "index", "is...
30.533333
0.019068
def run(generate_pks, show_pks, host, port, uri): """Connect sandman to <URI> and start the API server/admin interface.""" app.config['SQLALCHEMY_DATABASE_URI'] = uri app.config['SANDMAN_GENERATE_PKS'] = generate_pks app.config['SANDMAN_SHOW_PKS'] = show_pks app.config['SERVER_HOST'] = host ...
[ "def", "run", "(", "generate_pks", ",", "show_pks", ",", "host", ",", "port", ",", "uri", ")", ":", "app", ".", "config", "[", "'SQLALCHEMY_DATABASE_URI'", "]", "=", "uri", "app", ".", "config", "[", "'SANDMAN_GENERATE_PKS'", "]", "=", "generate_pks", "app...
42.6
0.002299
def critical(cls, name, message, *args): """ Convenience function to log a message at the CRITICAL level. :param name: The name of the logger instance in the VSG namespace (VSG.<name>) :param message: A message format string. :param args: The arguments that are are merged ...
[ "def", "critical", "(", "cls", ",", "name", ",", "message", ",", "*", "args", ")", ":", "cls", ".", "getLogger", "(", "name", ")", ".", "critical", "(", "message", ",", "*", "args", ")" ]
50.6
0.009709
def get_anchor_labels(anchors, gt_boxes, crowd_boxes): """ Label each anchor as fg/bg/ignore. Args: anchors: Ax4 float gt_boxes: Bx4 float, non-crowd crowd_boxes: Cx4 float Returns: anchor_labels: (A,) int. Each element is {-1, 0, 1} anchor_boxes: Ax4. Contains t...
[ "def", "get_anchor_labels", "(", "anchors", ",", "gt_boxes", ",", "crowd_boxes", ")", ":", "# This function will modify labels and return the filtered inds", "def", "filter_box_label", "(", "labels", ",", "value", ",", "max_num", ")", ":", "curr_inds", "=", "np", ".",...
44.594203
0.001272
def from_csv(cls, path, folder, csv_fname, bs=64, tfms=(None,None), val_idxs=None, suffix='', test_name=None, continuous=False, skip_header=True, num_workers=8, cat_separator=' '): """ Read in images and their labels given as a CSV file. This method should be used when training image lab...
[ "def", "from_csv", "(", "cls", ",", "path", ",", "folder", ",", "csv_fname", ",", "bs", "=", "64", ",", "tfms", "=", "(", "None", ",", "None", ")", ",", "val_idxs", "=", "None", ",", "suffix", "=", "''", ",", "test_name", "=", "None", ",", "conti...
65.71875
0.010309
def getServices(self): """ Simple method that returs list of all know DBS instances, instances known to this registry """ try: conn = self.dbi.connection() result = self.serviceslist.execute(conn) return result except Exception as ex: ...
[ "def", "getServices", "(", "self", ")", ":", "try", ":", "conn", "=", "self", ".", "dbi", ".", "connection", "(", ")", "result", "=", "self", ".", "serviceslist", ".", "execute", "(", "conn", ")", "return", "result", "except", "Exception", "as", "ex", ...
38.058824
0.010558
def get_course_descriptor_content(self, courseid): """ :param courseid: the course id of the course :raise InvalidNameException, CourseNotFoundException, CourseUnreadableException :return: the content of the dict that describes the course """ path = self._get_course_descr...
[ "def", "get_course_descriptor_content", "(", "self", ",", "courseid", ")", ":", "path", "=", "self", ".", "_get_course_descriptor_path", "(", "courseid", ")", "return", "loads_json_or_yaml", "(", "path", ",", "self", ".", "_filesystem", ".", "get", "(", "path", ...
52.125
0.009434
def add_impact_layers_to_canvas(impact_function, group=None, iface=None): """Helper method to add impact layer to QGIS from impact function. :param impact_function: The impact function used. :type impact_function: ImpactFunction :param group: An existing group as a parent, optional. :type group: Q...
[ "def", "add_impact_layers_to_canvas", "(", "impact_function", ",", "group", "=", "None", ",", "iface", "=", "None", ")", ":", "layers", "=", "impact_function", ".", "outputs", "name", "=", "impact_function", ".", "name", "if", "group", ":", "group_analysis", "...
34.363636
0.000514
def replace_rep(t:str) -> str: "Replace repetitions at the character level in `t`." def _replace_rep(m:Collection[str]) -> str: c,cc = m.groups() return f' {TK_REP} {len(cc)+1} {c} ' re_rep = re.compile(r'(\S)(\1{3,})') return re_rep.sub(_replace_rep, t)
[ "def", "replace_rep", "(", "t", ":", "str", ")", "->", "str", ":", "def", "_replace_rep", "(", "m", ":", "Collection", "[", "str", "]", ")", "->", "str", ":", "c", ",", "cc", "=", "m", ".", "groups", "(", ")", "return", "f' {TK_REP} {len(cc)+1} {c} '...
40
0.013986
def send_pgroup_snapshot(self, source, **kwargs): """ Send an existing pgroup snapshot to target(s) :param source: Name of pgroup snapshot to send. :type source: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: ...
[ "def", "send_pgroup_snapshot", "(", "self", ",", "source", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "\"name\"", ":", "[", "source", "]", ",", "\"action\"", ":", "\"send\"", "}", "data", ".", "update", "(", "kwargs", ")", "return", "self", ...
33.142857
0.009777
def intersection_supplied(self, results_filenames, labels, output_fh): """Returns `output_fh` populated with CSV results giving the n-grams that are common to witnesses in every set of works in `results_sets`, using the labels in `labels`. :param results_filenames: list of results to be...
[ "def", "intersection_supplied", "(", "self", ",", "results_filenames", ",", "labels", ",", "output_fh", ")", ":", "self", ".", "_add_temporary_results_sets", "(", "results_filenames", ",", "labels", ")", "query", "=", "constants", ".", "SELECT_INTERSECT_SUPPLIED_SQL",...
47.347826
0.0018
def as_fn(self, *binding_order): """Creates a function by binding the arguments in the given order. Args: *binding_order: The unbound variables. This must include all values. Returns: A function that takes the arguments of binding_order. Raises: ValueError: If the bindings are missing...
[ "def", "as_fn", "(", "self", ",", "*", "binding_order", ")", ":", "if", "len", "(", "binding_order", ")", "!=", "len", "(", "self", ".", "unbound_vars", ")", ":", "raise", "ValueError", "(", "'All vars must be specified.'", ")", "for", "arg", "in", "bindin...
36.730769
0.008163
def _adjusted_mutual_info_score(reference_indices, estimated_indices): """Compute the mutual information between two sequence labelings, adjusted for chance. Parameters ---------- reference_indices : np.ndarray Array of reference indices estimated_indices : np.ndarray Array of ...
[ "def", "_adjusted_mutual_info_score", "(", "reference_indices", ",", "estimated_indices", ")", ":", "n_samples", "=", "len", "(", "reference_indices", ")", "ref_classes", "=", "np", ".", "unique", "(", "reference_indices", ")", "est_classes", "=", "np", ".", "uniq...
42.289157
0.000557
def dinic(graph, capacity, source, target): """Maximum flow by Dinic :param graph: directed graph in listlist or listdict format :param capacity: in matrix format or same listdict graph :param int source: vertex :param int target: vertex :returns: skew symmetric flow matrix, flow value :com...
[ "def", "dinic", "(", "graph", ",", "capacity", ",", "source", ",", "target", ")", ":", "assert", "source", "!=", "target", "add_reverse_arcs", "(", "graph", ",", "capacity", ")", "Q", "=", "deque", "(", ")", "total", "=", "0", "n", "=", "len", "(", ...
37.875
0.000805
def term_width(): """ Return the column width of the terminal, or ``None`` if it can't be determined. """ if fcntl and termios: try: winsize = fcntl.ioctl(0, termios.TIOCGWINSZ, ' ') _, width = struct.unpack('hh', winsize) return width except IO...
[ "def", "term_width", "(", ")", ":", "if", "fcntl", "and", "termios", ":", "try", ":", "winsize", "=", "fcntl", ".", "ioctl", "(", "0", ",", "termios", ".", "TIOCGWINSZ", ",", "' '", ")", "_", ",", "width", "=", "struct", ".", "unpack", "(", "'hh...
35.347826
0.001198
def combine_dictionaries(a, b): """ returns the combined dictionary. a's values preferentially chosen """ c = {} for key in list(b.keys()): c[key]=b[key] for key in list(a.keys()): c[key]=a[key] return c
[ "def", "combine_dictionaries", "(", "a", ",", "b", ")", ":", "c", "=", "{", "}", "for", "key", "in", "list", "(", "b", ".", "keys", "(", ")", ")", ":", "c", "[", "key", "]", "=", "b", "[", "key", "]", "for", "key", "in", "list", "(", "a", ...
25
0.021459
def tokenize(self, string): ''' Maps a string to an iterator over tokens. In other words: [char] -> [token] ''' new_lexer = ply.lex.lex(module=self, debug=self.debug, errorlog=logger) new_lexer.latest_newline = 0 new_lexer.string_value = None new_lexer.input(stri...
[ "def", "tokenize", "(", "self", ",", "string", ")", ":", "new_lexer", "=", "ply", ".", "lex", ".", "lex", "(", "module", "=", "self", ",", "debug", "=", "self", ".", "debug", ",", "errorlog", "=", "logger", ")", "new_lexer", ".", "latest_newline", "=...
33.555556
0.008052
def plotE(self,*args,**kwargs): """ NAME: plotE PURPOSE: plot E(.) along the orbit INPUT: bovy_plot.bovy_plot inputs OUTPUT: figure to output device HISTORY: 2014-06-16 - Written - Bovy (IAS) """ if kw...
[ "def", "plotE", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "pop", "(", "'normed'", ",", "False", ")", ":", "kwargs", "[", "'d2'", "]", "=", "'Enorm'", "else", ":", "kwargs", "[", "'d2'", "]", "=", "'E...
24.833333
0.017241
def threshold_get_color(self, value, name=None): """ Obtain color for a value using thresholds. The value will be checked against any defined thresholds. These should have been set in the i3status configuration. If more than one threshold is needed for a module then the name c...
[ "def", "threshold_get_color", "(", "self", ",", "value", ",", "name", "=", "None", ")", ":", "# If first run then process the threshold data.", "if", "self", ".", "_thresholds", "is", "None", ":", "self", ".", "_thresholds_init", "(", ")", "# allow name with differe...
37
0.000798
def _WriteFileChunk(self, chunk): """Yields binary chunks, respecting archive file headers and footers. Args: chunk: the StreamedFileChunk to be written """ if chunk.chunk_index == 0: # Make sure size of the original file is passed. It's required # when output_writer is StreamingTarWr...
[ "def", "_WriteFileChunk", "(", "self", ",", "chunk", ")", ":", "if", "chunk", ".", "chunk_index", "==", "0", ":", "# Make sure size of the original file is passed. It's required", "# when output_writer is StreamingTarWriter.", "st", "=", "os", ".", "stat_result", "(", "...
41.722222
0.010417
def in_builddir(sub='.'): """ Decorate a project phase with a local working directory change. Args: sub: An optional subdirectory to change into. """ from functools import wraps def wrap_in_builddir(func): """Wrap the function for the new build directory.""" @wraps(fun...
[ "def", "in_builddir", "(", "sub", "=", "'.'", ")", ":", "from", "functools", "import", "wraps", "def", "wrap_in_builddir", "(", "func", ")", ":", "\"\"\"Wrap the function for the new build directory.\"\"\"", "@", "wraps", "(", "func", ")", "def", "wrap_in_builddir_f...
30.107143
0.001149
def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.TornadoConnection connection: Closed connect...
[ "def", "on_connection_closed", "(", "self", ",", "connection", ",", "reply_code", ",", "reply_text", ")", ":", "start_state", "=", "self", ".", "state", "self", ".", "state", "=", "self", ".", "STATE_CLOSED", "if", "self", ".", "on_unavailable", ":", "self",...
39.434783
0.002153
def split_escape(string, sep, maxsplit=None, escape_char="\\"): """Like unicode/str/bytes.split but allows for the separator to be escaped If passed unicode/str/bytes will only return list of unicode/str/bytes. """ assert len(sep) == 1 assert len(escape_char) == 1 if isinstance(string, bytes)...
[ "def", "split_escape", "(", "string", ",", "sep", ",", "maxsplit", "=", "None", ",", "escape_char", "=", "\"\\\\\"", ")", ":", "assert", "len", "(", "sep", ")", "==", "1", "assert", "len", "(", "escape_char", ")", "==", "1", "if", "isinstance", "(", ...
27.692308
0.000894
def fetch(self, only_ref=False): """Fetch object from NIOS by _ref or searchfields Update existent object with fields returned from NIOS Return True on successful object fetch """ if self.ref: reply = self.connector.get_object( self.ref, return_fields...
[ "def", "fetch", "(", "self", ",", "only_ref", "=", "False", ")", ":", "if", "self", ".", "ref", ":", "reply", "=", "self", ".", "connector", ".", "get_object", "(", "self", ".", "ref", ",", "return_fields", "=", "self", ".", "return_fields", ")", "if...
38.681818
0.002294
def v1_stream_id_associations(tags, stream_id): '''Retrieve associations for a given stream_id. The associations returned have the exact same structure as defined in the ``v1_tag_associate`` route with one addition: a ``tag`` field contains the full tag name for the association. ''' stream_id =...
[ "def", "v1_stream_id_associations", "(", "tags", ",", "stream_id", ")", ":", "stream_id", "=", "stream_id", ".", "decode", "(", "'utf-8'", ")", ".", "strip", "(", ")", "return", "{", "'associations'", ":", "tags", ".", "assocs_by_stream_id", "(", "stream_id", ...
45.666667
0.002387
def get_available_symbols(**kwargs): """ MOVED to iexfinance.refdata.get_symbols """ import warnings warnings.warn(WNG_MSG % ("get_available_symbols", "refdata.get_symbols")) _ALL_SYMBOLS_URL = "https://api.iextrading.com/1.0/ref-data/symbols" handler = _IEXBase(**kwargs) respons...
[ "def", "get_available_symbols", "(", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", "%", "(", "\"get_available_symbols\"", ",", "\"refdata.get_symbols\"", ")", ")", "_ALL_SYMBOLS_URL", "=", "\"https://api.iextrading.com/1....
36.692308
0.002045
def read(cls, proto): """ Intercepts TemporalMemory deserialization request in order to initialize `TemporalMemoryMonitorMixin` state @param proto (DynamicStructBuilder) Proto object @return (TemporalMemory) TemporalMemory shim instance """ tm = super(TemporalMemoryMonitorMixin, cls).read(...
[ "def", "read", "(", "cls", ",", "proto", ")", ":", "tm", "=", "super", "(", "TemporalMemoryMonitorMixin", ",", "cls", ")", ".", "read", "(", "proto", ")", "# initialize `TemporalMemoryMonitorMixin` attributes", "tm", ".", "mmName", "=", "None", "tm", ".", "_...
27.833333
0.001931
def set_mask(self, kind, mask): """Writes the specified filter mask. """ logger.debug("setting mask kind %s to %s" % (kind, mask)) return self.library.Srv_SetMask(self.pointer, kind, mask)
[ "def", "set_mask", "(", "self", ",", "kind", ",", "mask", ")", ":", "logger", ".", "debug", "(", "\"setting mask kind %s to %s\"", "%", "(", "kind", ",", "mask", ")", ")", "return", "self", ".", "library", ".", "Srv_SetMask", "(", "self", ".", "pointer",...
43.2
0.009091
def ls_command( endpoint_plus_path, recursive_depth_limit, recursive, long_output, show_hidden, filter_val, ): """ Executor for `globus ls` """ endpoint_id, path = endpoint_plus_path # do autoactivation before the `ls` call so that recursive invocations # won't do this r...
[ "def", "ls_command", "(", "endpoint_plus_path", ",", "recursive_depth_limit", ",", "recursive", ",", "long_output", ",", "show_hidden", ",", "filter_val", ",", ")", ":", "endpoint_id", ",", "path", "=", "endpoint_plus_path", "# do autoactivation before the `ls` call so th...
33.835821
0.000429
def visit_WhileStatement(self, node): """Visitor for `WhileStatement` AST node.""" while self.visit(node.condition): result = self.visit(node.compound) if result is not None: return result
[ "def", "visit_WhileStatement", "(", "self", ",", "node", ")", ":", "while", "self", ".", "visit", "(", "node", ".", "condition", ")", ":", "result", "=", "self", ".", "visit", "(", "node", ".", "compound", ")", "if", "result", "is", "not", "None", ":...
39.833333
0.008197
def _add_definition(self): """Return newly-added footer part.""" footer_part, rId = self._document_part.add_footer_part() self._sectPr.add_footerReference(self._hdrftr_index, rId) return footer_part
[ "def", "_add_definition", "(", "self", ")", ":", "footer_part", ",", "rId", "=", "self", ".", "_document_part", ".", "add_footer_part", "(", ")", "self", ".", "_sectPr", ".", "add_footerReference", "(", "self", ".", "_hdrftr_index", ",", "rId", ")", "return"...
45.2
0.008696
def assign_taxonomy( data, min_confidence=0.80, output_fp=None, training_data_fp=None, fixrank=True, max_memory=None, tmp_dir=tempfile.gettempdir()): """Assign taxonomy to each sequence in data with the RDP classifier data: open fasta file object or list of fasta lines confidence: m...
[ "def", "assign_taxonomy", "(", "data", ",", "min_confidence", "=", "0.80", ",", "output_fp", "=", "None", ",", "training_data_fp", "=", "None", ",", "fixrank", "=", "True", ",", "max_memory", "=", "None", ",", "tmp_dir", "=", "tempfile", ".", "gettempdir", ...
34.578947
0.00037
def get_autoconfig_client(client_cache=_AUTOCONFIG_CLIENT): """ Creates the client as specified in the `luigi.cfg` configuration. """ try: return client_cache.client except AttributeError: configured_client = hdfs_config.get_configured_hdfs_client() if configured_client == "w...
[ "def", "get_autoconfig_client", "(", "client_cache", "=", "_AUTOCONFIG_CLIENT", ")", ":", "try", ":", "return", "client_cache", ".", "client", "except", "AttributeError", ":", "configured_client", "=", "hdfs_config", ".", "get_configured_hdfs_client", "(", ")", "if", ...
47.227273
0.001887
def integrate_dxdv(self,dxdv,t,pot,method='dopr54_c', rectIn=False,rectOut=False): """ NAME: integrate_dxdv PURPOSE: integrate the orbit and a small area of phase space INPUT: dxdv - [dR,dvR,dvT,dphi] t - list of ti...
[ "def", "integrate_dxdv", "(", "self", ",", "dxdv", ",", "t", ",", "pot", ",", "method", "=", "'dopr54_c'", ",", "rectIn", "=", "False", ",", "rectOut", "=", "False", ")", ":", "pot", "=", "flatten_potential", "(", "pot", ")", "_check_potential_dim", "(",...
31.672727
0.013363
def get(self, request, enterprise_uuid, course_id): """ Handle the enrollment of enterprise learner in the provided course. Based on `enterprise_uuid` in URL, the view will decide which enterprise customer's course enrollment record should be created. Depending on the value of ...
[ "def", "get", "(", "self", ",", "request", ",", "enterprise_uuid", ",", "course_id", ")", ":", "enrollment_course_mode", "=", "request", ".", "GET", ".", "get", "(", "'course_mode'", ")", "enterprise_catalog_uuid", "=", "request", ".", "GET", ".", "get", "("...
44.067416
0.001995
def basis(start, stop=None, dim=1, sort="G", cross_truncation=1.): """ Create an N-dimensional unit polynomial basis. Args: start (int, numpy.ndarray): the minimum polynomial to include. If int is provided, set as lowest total order. If array of int, set as lower order alon...
[ "def", "basis", "(", "start", ",", "stop", "=", "None", ",", "dim", "=", "1", ",", "sort", "=", "\"G\"", ",", "cross_truncation", "=", "1.", ")", ":", "if", "stop", "is", "None", ":", "start", ",", "stop", "=", "numpy", ".", "array", "(", "0", ...
32.216867
0.001814
def set_color_mask(self, red, green, blue, alpha): """Toggle writing of frame buffer color components Parameters ---------- red : bool Red toggle. green : bool Green toggle. blue : bool Blue toggle. alpha : bool ...
[ "def", "set_color_mask", "(", "self", ",", "red", ",", "green", ",", "blue", ",", "alpha", ")", ":", "self", ".", "glir", ".", "command", "(", "'FUNC'", ",", "'glColorMask'", ",", "bool", "(", "red", ")", ",", "bool", "(", "green", ")", ",", "bool"...
28.5
0.008493
def get_version(pep440=False): """Tracks the version number. pep440: bool When True, this function returns a version string suitable for a release as defined by PEP 440. When False, the githash (if available) will be appended to the version string. The file VERSION holds the versio...
[ "def", "get_version", "(", "pep440", "=", "False", ")", ":", "git_version", "=", "format_git_describe", "(", "call_git_describe", "(", ")", ",", "pep440", "=", "pep440", ")", "if", "git_version", "is", "None", ":", "# not a git repository", "return", "read_relea...
39.28
0.000994
def _cc(self): """ implementation of the efficient bilayer cross counting by insert-sort (see Barth & Mutzel paper "Simple and Efficient Bilayer Cross Counting") """ g=self.layout.grx P=[] for v in self: P.extend(sorted([g[x].pos for x in self._neighbo...
[ "def", "_cc", "(", "self", ")", ":", "g", "=", "self", ".", "layout", ".", "grx", "P", "=", "[", "]", "for", "v", "in", "self", ":", "P", ".", "extend", "(", "sorted", "(", "[", "g", "[", "x", "]", ".", "pos", "for", "x", "in", "self", "....
30.647059
0.018622
def read_with_columns(func): """Decorate a Table read method to use the ``columns`` keyword """ def wrapper(*args, **kwargs): # parse columns argument columns = kwargs.pop("columns", None) # read table tab = func(*args, **kwargs) # filter on columns if colum...
[ "def", "read_with_columns", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# parse columns argument", "columns", "=", "kwargs", ".", "pop", "(", "\"columns\"", ",", "None", ")", "# read table", "tab", "=", ...
25.375
0.002375
def is_subdomain(self, domain=None): """ Check if the given subdomain is a subdomain. :param domain: The domain to validate. :type domain: str :return: The validity of the subdomain. :rtype: bool """ if domain: # A domain is given. ...
[ "def", "is_subdomain", "(", "self", ",", "domain", "=", "None", ")", ":", "if", "domain", ":", "# A domain is given.", "# We set the element to test as the parsed domain.", "to_test", "=", "domain", "elif", "self", ".", "element", ":", "# A domain is globally given.", ...
28.241379
0.002361
def bodvrd(bodynm, item, maxn): """ Fetch from the kernel pool the double precision values of an item associated with a body. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodvrd_c.html :param bodynm: Body name. :type bodynm: str :param item: Item for which values...
[ "def", "bodvrd", "(", "bodynm", ",", "item", ",", "maxn", ")", ":", "bodynm", "=", "stypes", ".", "stringToCharP", "(", "bodynm", ")", "item", "=", "stypes", ".", "stringToCharP", "(", "item", ")", "dim", "=", "ctypes", ".", "c_int", "(", ")", "value...
33.08
0.001175
def generate_network(user=None, reset=False): """ Assemble the network connections for a given user """ token = collect_token() try: gh = login(token=token) root_user = gh.user(user) except Exception, e: # Failed to login using the token, github3.models.GitHubError ...
[ "def", "generate_network", "(", "user", "=", "None", ",", "reset", "=", "False", ")", ":", "token", "=", "collect_token", "(", ")", "try", ":", "gh", "=", "login", "(", "token", "=", "token", ")", "root_user", "=", "gh", ".", "user", "(", "user", "...
29.878049
0.001581
def list_extensions(): ''' List up available extensions. Note: It may not work on some platforms/environments since it depends on the directory structure of the namespace packages. Returns: list of str Names of available extensions. ''' import nnabla_ext.cpu from o...
[ "def", "list_extensions", "(", ")", ":", "import", "nnabla_ext", ".", "cpu", "from", "os", ".", "path", "import", "dirname", ",", "join", ",", "realpath", "from", "os", "import", "listdir", "ext_dir", "=", "realpath", "(", "(", "join", "(", "dirname", "(...
27.470588
0.00207
def next_frame_sv2p_cutoff(): """SV2P model with additional cutoff in L2 loss for environments like pong.""" hparams = next_frame_sv2p() hparams.video_modality_loss_cutoff = 0.4 hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 1 return hparams
[ "def", "next_frame_sv2p_cutoff", "(", ")", ":", "hparams", "=", "next_frame_sv2p", "(", ")", "hparams", ".", "video_modality_loss_cutoff", "=", "0.4", "hparams", ".", "video_num_input_frames", "=", "4", "hparams", ".", "video_num_target_frames", "=", "1", "return", ...
38.428571
0.029091
def business_query(self, id, **kwargs): """ Query the Yelp Business API. documentation: https://www.yelp.com/developers/documentation/v3/business required parameters: * id - business ID """ if not id: raise ValueError(...
[ "def", "business_query", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "if", "not", "id", ":", "raise", "ValueError", "(", "'A valid business ID (parameter \"id\") must be provided.'", ")", "return", "self", ".", "_query", "(", "BUSINESS_API_URL", "...
33.230769
0.011261
def find_by_id(self, team, params={}, **options): """Returns the full record for a single team. Parameters ---------- team : {Id} Globally unique identifier for the team. [params] : {Object} Parameters for the request """ path = "/teams/%s" % (team) retu...
[ "def", "find_by_id", "(", "self", ",", "team", ",", "params", "=", "{", "}", ",", "*", "*", "options", ")", ":", "path", "=", "\"/teams/%s\"", "%", "(", "team", ")", "return", "self", ".", "client", ".", "get", "(", "path", ",", "params", ",", "*...
35.4
0.008264
def publish_event_from_dict(self, event_type, data): """ Combine 'data' with self.additional_publish_event_data and publish an event """ for key, value in self.additional_publish_event_data.items(): if key in data: return {'result': 'error', 'message': 'Key sh...
[ "def", "publish_event_from_dict", "(", "self", ",", "event_type", ",", "data", ")", ":", "for", "key", ",", "value", "in", "self", ".", "additional_publish_event_data", ".", "items", "(", ")", ":", "if", "key", "in", "data", ":", "return", "{", "'result'",...
43.818182
0.00813
def forwards(self, orm): "Write your forwards methods here." orm.Project.objects.update(label=F('name')) orm.Cohort.objects.update(label=F('name')) orm.Sample.objects.update(name=F('label'))
[ "def", "forwards", "(", "self", ",", "orm", ")", ":", "orm", ".", "Project", ".", "objects", ".", "update", "(", "label", "=", "F", "(", "'name'", ")", ")", "orm", ".", "Cohort", ".", "objects", ".", "update", "(", "label", "=", "F", "(", "'name'...
43.6
0.009009
def _partial_subs(func, func2vars): """ Partial-bug proof substitution. Works by making the substitutions on the expression inside the derivative first, and then rebuilding the derivative safely without evaluating it using `_partial_diff`. """ if isinstance(func, sympy.Derivative): new_f...
[ "def", "_partial_subs", "(", "func", ",", "func2vars", ")", ":", "if", "isinstance", "(", "func", ",", "sympy", ".", "Derivative", ")", ":", "new_func", "=", "func", ".", "expr", ".", "xreplace", "(", "func2vars", ")", "new_variables", "=", "tuple", "(",...
43
0.001751
def _interpret_regexp(self, string, flags): '''Perform sctring escape - for regexp literals''' self.index = 0 self.length = len(string) self.source = string self.lineNumber = 0 self.lineStart = 0 octal = False st = '' inside_square = 0 whil...
[ "def", "_interpret_regexp", "(", "self", ",", "string", ",", "flags", ")", ":", "self", ".", "index", "=", "0", "self", ".", "length", "=", "len", "(", "string", ")", "self", ".", "source", "=", "string", "self", ".", "lineNumber", "=", "0", "self", ...
41.659341
0.001288
def _decode_geom(ewkb): """Decode encoded wkb into a shapely geometry """ # it's already a shapely object if hasattr(ewkb, 'geom_type'): return ewkb from shapely import wkb from shapely import wkt if ewkb: try: return wkb.loads(ba.unhexlify(ewkb)) except ...
[ "def", "_decode_geom", "(", "ewkb", ")", ":", "# it's already a shapely object", "if", "hasattr", "(", "ewkb", ",", "'geom_type'", ")", ":", "return", "ewkb", "from", "shapely", "import", "wkb", "from", "shapely", "import", "wkt", "if", "ewkb", ":", "try", "...
29.740741
0.001206
def save_to_file(filename, content): """ Save content to file. Used by node initial contact but can be used anywhere. :param str filename: name of file to save to :param str content: content to save :return: None :raises IOError: permissions issue saving, invalid directory, etc """ ...
[ "def", "save_to_file", "(", "filename", ",", "content", ")", ":", "import", "os", ".", "path", "path", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "with", "open", "(", "path", ",", "\"w\"", ")", "as", "text_file", ":", "text_file", ...
31.642857
0.002193
def color_is_forced(**envars): ''' Look for clues in environment, e.g.: - https://bixense.com/clicolors/ Arguments: envars: Additional environment variables to check for equality, i.e. ``MYAPP_COLOR_FORCED='1'`` Returns: Bool: Forced ...
[ "def", "color_is_forced", "(", "*", "*", "envars", ")", ":", "result", "=", "env", ".", "CLICOLOR_FORCE", "and", "env", ".", "CLICOLOR_FORCE", "!=", "'0'", "log", ".", "debug", "(", "'%s (CLICOLOR_FORCE=%s)'", ",", "result", ",", "env", ".", "CLICOLOR_FORCE"...
30.857143
0.001497
def get_capabilities(_, data): """http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n796. Positional arguments: data -- bytearray data to read. Returns: List. """ answers = list() for i in range(len(data)): base = i * 8 for bit in range(8): ...
[ "def", "get_capabilities", "(", "_", ",", "data", ")", ":", "answers", "=", "list", "(", ")", "for", "i", "in", "range", "(", "len", "(", "data", ")", ")", ":", "base", "=", "i", "*", "8", "for", "bit", "in", "range", "(", "8", ")", ":", "if"...
25.941176
0.002188
def p_kwl_kwl(self, p): ''' kwl : kwl SEPARATOR kwl ''' _LOGGER.debug("kwl -> kwl ; kwl") if p[3] is not None: p[0] = p[3] elif p[1] is not None: p[0] = p[1] else: p[0] = TypedClass(None, TypedClass.UNKNOWN)
[ "def", "p_kwl_kwl", "(", "self", ",", "p", ")", ":", "_LOGGER", ".", "debug", "(", "\"kwl -> kwl ; kwl\"", ")", "if", "p", "[", "3", "]", "is", "not", "None", ":", "p", "[", "0", "]", "=", "p", "[", "3", "]", "elif", "p", "[", "1", "]", "is",...
28.3
0.010274
def assert_lt(left, right, message=None, extra=None): """Raises an AssertionError if left_hand >= right_hand.""" assert left < right, _assert_fail_message(message, left, right, ">=", extra)
[ "def", "assert_lt", "(", "left", ",", "right", ",", "message", "=", "None", ",", "extra", "=", "None", ")", ":", "assert", "left", "<", "right", ",", "_assert_fail_message", "(", "message", ",", "left", ",", "right", ",", "\">=\"", ",", "extra", ")" ]
65
0.010152
def from_bin(bin_array): """ Convert binary array back a nonnegative integer. The array length is the bit width. The first input index holds the MSB and the last holds the LSB. """ width = len(bin_array) bin_wgts = 2**np.arange(width-1,-1,-1) return int(np.dot(bin_array,bin_wgts))
[ "def", "from_bin", "(", "bin_array", ")", ":", "width", "=", "len", "(", "bin_array", ")", "bin_wgts", "=", "2", "**", "np", ".", "arange", "(", "width", "-", "1", ",", "-", "1", ",", "-", "1", ")", "return", "int", "(", "np", ".", "dot", "(", ...
37.875
0.019355
def set_shutter_level(self, level=0.0): """ sets the shutter level Args: level(float): the new level of the shutter. 0.0 = open, 1.0 = closed Returns: the result of the _restCall """ data = {"channelIndex": 1, "deviceId": self.id, "shutterLevel": level} ...
[ "def", "set_shutter_level", "(", "self", ",", "level", "=", "0.0", ")", ":", "data", "=", "{", "\"channelIndex\"", ":", "1", ",", "\"deviceId\"", ":", "self", ".", "id", ",", "\"shutterLevel\"", ":", "level", "}", "return", "self", ".", "_restCall", "(",...
39.6
0.009877
def zlma(series, window=20, min_periods=None, kind="ema"): """ John Ehlers' Zero lag (exponential) moving average https://en.wikipedia.org/wiki/Zero_lag_exponential_moving_average """ min_periods = window if min_periods is None else min_periods lag = (window - 1) // 2 series = 2 * series - ...
[ "def", "zlma", "(", "series", ",", "window", "=", "20", ",", "min_periods", "=", "None", ",", "kind", "=", "\"ema\"", ")", ":", "min_periods", "=", "window", "if", "min_periods", "is", "None", "else", "min_periods", "lag", "=", "(", "window", "-", "1",...
36.428571
0.001912
def add_embed(self, embed): """ add embedded rich content :param embed: embed object or dict """ self.embeds.append(embed.__dict__ if isinstance(embed, DiscordEmbed) else embed)
[ "def", "add_embed", "(", "self", ",", "embed", ")", ":", "self", ".", "embeds", ".", "append", "(", "embed", ".", "__dict__", "if", "isinstance", "(", "embed", ",", "DiscordEmbed", ")", "else", "embed", ")" ]
35.333333
0.013825
def get_calling_prototype(acallable): """Returns actual working calling prototype This means that the prototype given can be used directly in the same way by bound method, method, function, lambda:: >>> def f1(a, b, c=1): pass >>> get_calling_prototype(f1) (['a', 'b', 'c'], (1,)) ...
[ "def", "get_calling_prototype", "(", "acallable", ")", ":", "assert", "callable", "(", "acallable", ")", "if", "inspect", ".", "ismethod", "(", "acallable", ")", "or", "inspect", ".", "isfunction", "(", "acallable", ")", ":", "args", ",", "vargs", ",", "vk...
34.107692
0.001754
def get_dimension_by_unit_measure_or_abbreviation(measure_or_unit_abbreviation,**kwargs): """ Return the physical dimension a given unit abbreviation of a measure, or the measure itself, refers to. The search key is the abbreviation or the full measure """ unit_abbreviation, factor = _parse...
[ "def", "get_dimension_by_unit_measure_or_abbreviation", "(", "measure_or_unit_abbreviation", ",", "*", "*", "kwargs", ")", ":", "unit_abbreviation", ",", "factor", "=", "_parse_unit", "(", "measure_or_unit_abbreviation", ")", "units", "=", "db", ".", "DBSession", ".", ...
45.941176
0.013802
def delete(self): """Deletes the photoset. """ method = 'flickr.photosets.delete' _dopost(method, auth=True, photoset_id=self.id) return True
[ "def", "delete", "(", "self", ")", ":", "method", "=", "'flickr.photosets.delete'", "_dopost", "(", "method", ",", "auth", "=", "True", ",", "photoset_id", "=", "self", ".", "id", ")", "return", "True" ]
25.142857
0.010989
def _preprocess(self, filehandle, metadata): "Runs all attached preprocessors on the provided filehandle." for process in self._preprocessors: filehandle = process(filehandle, metadata) return filehandle
[ "def", "_preprocess", "(", "self", ",", "filehandle", ",", "metadata", ")", ":", "for", "process", "in", "self", ".", "_preprocessors", ":", "filehandle", "=", "process", "(", "filehandle", ",", "metadata", ")", "return", "filehandle" ]
47
0.008368
def _to_stinespring(rep, data, input_dim, output_dim): """Transform a QuantumChannel to the Stinespring representation.""" if rep == 'Stinespring': return data if rep == 'Operator': return _from_operator('Stinespring', data, input_dim, output_dim) # Convert via Superoperator representati...
[ "def", "_to_stinespring", "(", "rep", ",", "data", ",", "input_dim", ",", "output_dim", ")", ":", "if", "rep", "==", "'Stinespring'", ":", "return", "data", "if", "rep", "==", "'Operator'", ":", "return", "_from_operator", "(", "'Stinespring'", ",", "data", ...
45.7
0.002146
def _validate_resources(self): """Validate the resources defined in the options.""" resources = self.options.resources for key in ['num_machines', 'num_mpiprocs_per_machine', 'tot_num_mpiprocs']: if key in resources and resources[key] != 1: raise exceptions.FeatureNo...
[ "def", "_validate_resources", "(", "self", ")", ":", "resources", "=", "self", ".", "options", ".", "resources", "for", "key", "in", "[", "'num_machines'", ",", "'num_mpiprocs_per_machine'", ",", "'tot_num_mpiprocs'", "]", ":", "if", "key", "in", "resources", ...
59.555556
0.009191
def predict(self, h=5, oos_data=None, intervals=False, **kwargs): """ Makes forecast with the estimated model Parameters ---------- h : int (default : 5) How many steps ahead would you like to forecast? oos_data : pd.DataFrame Data for the variables to b...
[ "def", "predict", "(", "self", ",", "h", "=", "5", ",", "oos_data", "=", "None", ",", "intervals", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "latent_variables", ".", "estimated", "is", "False", ":", "raise", "Exception", "("...
47.88172
0.010341
def size(self): """The size of the schema. If the underlying data source changes, it may be outdated. """ if self._size is None: self._size = 0 for csv_file in self.files: self._size += sum(1 if line else 0 for line in _util.open_local_or_gcs(csv_file, 'r')) return self._size
[ "def", "size", "(", "self", ")", ":", "if", "self", ".", "_size", "is", "None", ":", "self", ".", "_size", "=", "0", "for", "csv_file", "in", "self", ".", "files", ":", "self", ".", "_size", "+=", "sum", "(", "1", "if", "line", "else", "0", "fo...
33.888889
0.015974
def generate(declaration, headers=None, has_iterators=False): """Compile and load the reflection dictionary for a type. If the requested dictionary has already been cached, then load that instead. Parameters ---------- declaration : str A type declaration (for example "vector<int>") he...
[ "def", "generate", "(", "declaration", ",", "headers", "=", "None", ",", "has_iterators", "=", "False", ")", ":", "global", "NEW_DICTS", "# FIXME: _rootpy_dictionary_already_exists returns false positives", "# if a third-party module provides \"incomplete\" dictionaries.", "#if c...
41.573034
0.00132
def OnMeasureItemWidth(self, item): """Returns the height of the items in the popup""" item_name = self.GetItems()[item] return icons[item_name].GetWidth()
[ "def", "OnMeasureItemWidth", "(", "self", ",", "item", ")", ":", "item_name", "=", "self", ".", "GetItems", "(", ")", "[", "item", "]", "return", "icons", "[", "item_name", "]", ".", "GetWidth", "(", ")" ]
35.2
0.011111
def deactivate(self, mod): """ Set external module *mod* to inactive. """ if mod in self.active: self.active.remove(mod)
[ "def", "deactivate", "(", "self", ",", "mod", ")", ":", "if", "mod", "in", "self", ".", "active", ":", "self", ".", "active", ".", "remove", "(", "mod", ")" ]
26.5
0.012195
def get_db_session(session=None, obj=None): """ utility function that attempts to return sqlalchemy session that could have been created/passed in one of few ways: * It first tries to read session attached to instance if object argument was passed * then it tries to return session passed as...
[ "def", "get_db_session", "(", "session", "=", "None", ",", "obj", "=", "None", ")", ":", "# try to read the session from instance", "from", "ziggurat_foundations", "import", "models", "if", "obj", ":", "return", "sa", ".", "orm", ".", "session", ".", "object_ses...
28.066667
0.001148
def get_package_formats(): """Get the list of available package formats and parameters.""" # pylint: disable=fixme # HACK: This obviously isn't great, and it is subject to change as # the API changes, but it'll do for now as a interim method of # introspection to get the parameters we need. def ...
[ "def", "get_package_formats", "(", ")", ":", "# pylint: disable=fixme", "# HACK: This obviously isn't great, and it is subject to change as", "# the API changes, but it'll do for now as a interim method of", "# introspection to get the parameters we need.", "def", "get_parameters", "(", "cls...
36.175
0.000673
def convert_svg_transform(self, transform): """ Converts a string representing a SVG transform into AffineTransform fields. See https://www.w3.org/TR/SVG/coords.html#TransformAttribute for the specification of the transform strings. skewX and skewY are not supported. ...
[ "def", "convert_svg_transform", "(", "self", ",", "transform", ")", ":", "tr", ",", "args", "=", "transform", "[", ":", "-", "1", "]", ".", "split", "(", "'('", ")", "a", "=", "map", "(", "float", ",", "args", ".", "split", "(", "' '", ")", ")", ...
30.673913
0.001374
def _gather_all_deps(self, args, kwargs): """Count the number of unresolved futures on which a task depends. Args: - args (List[args]) : The list of args list to the fn - kwargs (Dict{kwargs}) : The dict of all kwargs passed to the fn Returns: - count, [list...
[ "def", "_gather_all_deps", "(", "self", ",", "args", ",", "kwargs", ")", ":", "# Check the positional args", "depends", "=", "[", "]", "count", "=", "0", "for", "dep", "in", "args", ":", "if", "isinstance", "(", "dep", ",", "Future", ")", ":", "if", "s...
32.972222
0.001637
def contains(self, key): """Does this configuration contain a given key?""" if self._jconf is not None: return self._jconf.contains(key) else: return key in self._conf
[ "def", "contains", "(", "self", ",", "key", ")", ":", "if", "self", ".", "_jconf", "is", "not", "None", ":", "return", "self", ".", "_jconf", ".", "contains", "(", "key", ")", "else", ":", "return", "key", "in", "self", ".", "_conf" ]
35
0.009302