text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def to_html(self, **kwargs): """Render as html Args: None Returns: Str the html representation Raises: Errors are propagated We pass the kwargs on to the base class so an exception is raised if invalid keywords were passed. See: ...
[ "def", "to_html", "(", "self", ",", "*", "*", "kwargs", ")", ":", "super", "(", "LineBreak", ",", "self", ")", ".", "__init__", "(", "*", "*", "kwargs", ")", "return", "'<br%s/>\\n'", "%", "self", ".", "html_attributes", "(", ")" ]
26.2
0.003683
def fetch( self, request: Union["HTTPRequest", str], **kwargs: Any ) -> "HTTPResponse": """Executes a request, returning an `HTTPResponse`. The request may be either a string URL or an `HTTPRequest` object. If it is a string, we construct an `HTTPRequest` using any additional ...
[ "def", "fetch", "(", "self", ",", "request", ":", "Union", "[", "\"HTTPRequest\"", ",", "str", "]", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "\"HTTPResponse\"", ":", "response", "=", "self", ".", "_io_loop", ".", "run_sync", "(", "functools", "....
40.75
0.004498
def upload_feature_value_file(self, mapobject_type_name, plate_name, well_name, well_pos_y, well_pos_x, tpoint, filename, index_col): '''Uploads feature values for the given :class:`MapobjectType <tmlib.models.mapobject.MapobjectType>` at the specified :class:`Site <tmlib.models.site...
[ "def", "upload_feature_value_file", "(", "self", ",", "mapobject_type_name", ",", "plate_name", ",", "well_name", ",", "well_pos_y", ",", "well_pos_x", ",", "tpoint", ",", "filename", ",", "index_col", ")", ":", "logger", ".", "info", "(", "'upload feature value f...
38.102564
0.001969
def parse_http_scheme(uri): """ match on http scheme if no match is found will assume http """ regex = re.compile( r'^(?:http)s?://', flags=re.IGNORECASE ) match = regex.match(uri) return match.group(0) if match else 'http://'
[ "def", "parse_http_scheme", "(", "uri", ")", ":", "regex", "=", "re", ".", "compile", "(", "r'^(?:http)s?://'", ",", "flags", "=", "re", ".", "IGNORECASE", ")", "match", "=", "regex", ".", "match", "(", "uri", ")", "return", "match", ".", "group", "(",...
23.727273
0.00369
def set_default_unit(self, twig=None, unit=None, **kwargs): """ TODO: add documentation """ if twig is not None and unit is None: # then try to support value as the first argument if no matches with twigs if isinstance(unit, u.Unit) or not isinstance(twig, str): ...
[ "def", "set_default_unit", "(", "self", ",", "twig", "=", "None", ",", "unit", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "twig", "is", "not", "None", "and", "unit", "is", "None", ":", "# then try to support value as the first argument if no matches...
39
0.006678
def to_tex(self, text_size='large', table_width=5, clear_pages = False): """ Write the program information to a .tex file, which can be rendered to .pdf running pdflatex. The program can then be printed and brought to the gym. Parameters ---------- text_size ...
[ "def", "to_tex", "(", "self", ",", "text_size", "=", "'large'", ",", "table_width", "=", "5", ",", "clear_pages", "=", "False", ")", ":", "# If rendered, find the length of the longest '6 x 75kg'-type string", "max_ex_scheme", "=", "0", "if", "self", ".", "_rendered...
33.742857
0.007407
def addDataModels(self, mods): ''' Adds a model definition (same format as input to Model.addDataModels and output of Model.getModelDef). ''' # Load all the universal properties for _, mdef in mods: for univname, _, _ in mdef.get('univs', ()): self.add...
[ "def", "addDataModels", "(", "self", ",", "mods", ")", ":", "# Load all the universal properties", "for", "_", ",", "mdef", "in", "mods", ":", "for", "univname", ",", "_", ",", "_", "in", "mdef", ".", "get", "(", "'univs'", ",", "(", ")", ")", ":", "...
36
0.003529
def find_ask(): """ Find our instance of Ask, navigating Local's and possible blueprints. Note: This only supports returning a reference to the first instance of Ask found. """ if hasattr(current_app, 'ask'): return getattr(current_app, 'ask') else: if hasattr(current_app, '...
[ "def", "find_ask", "(", ")", ":", "if", "hasattr", "(", "current_app", ",", "'ask'", ")", ":", "return", "getattr", "(", "current_app", ",", "'ask'", ")", "else", ":", "if", "hasattr", "(", "current_app", ",", "'blueprints'", ")", ":", "blueprints", "=",...
37.2
0.001748
def _classify_load_constant(self, regs_init, regs_fini, mem_fini, written_regs, read_regs): """Classify load-constant gadgets. """ matches = [] # Check for "dst_reg <- constant" pattern. for dst_reg, dst_val in regs_fini.items(): # Make sure the *dst* register was wr...
[ "def", "_classify_load_constant", "(", "self", ",", "regs_init", ",", "regs_fini", ",", "mem_fini", ",", "written_regs", ",", "read_regs", ")", ":", "matches", "=", "[", "]", "# Check for \"dst_reg <- constant\" pattern.", "for", "dst_reg", ",", "dst_val", "in", "...
33.083333
0.00612
def _read_json(self, path, name): """ Load a json into a dictionary from a file. :param path: path to file :param name: name of file :return: dict """ with open(os.path.join(path, name), 'r') as fil: output = json.load(fil) self.logger.inf...
[ "def", "_read_json", "(", "self", ",", "path", ",", "name", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "path", ",", "name", ")", ",", "'r'", ")", "as", "fil", ":", "output", "=", "json", ".", "load", "(", "fil", ")", ...
31
0.005222
def spawn_containers(addrs, env_cls=Environment, env_params=None, mgr_cls=EnvManager, *args, **kwargs): """Spawn environments in a multiprocessing :class:`multiprocessing.Pool`. Arguments and keyword arguments are passed down to the created environments at initiali...
[ "def", "spawn_containers", "(", "addrs", ",", "env_cls", "=", "Environment", ",", "env_params", "=", "None", ",", "mgr_cls", "=", "EnvManager", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pool", "=", "multiprocessing", ".", "Pool", "(", "len", ...
36.229167
0.00056
def process_text(text, save_xml_name='trips_output.xml', save_xml_pretty=True, offline=False, service_endpoint='drum'): """Return a TripsProcessor by processing text. Parameters ---------- text : str The text to be processed. save_xml_name : Optional[str] The name o...
[ "def", "process_text", "(", "text", ",", "save_xml_name", "=", "'trips_output.xml'", ",", "save_xml_pretty", "=", "True", ",", "offline", "=", "False", ",", "service_endpoint", "=", "'drum'", ")", ":", "if", "not", "offline", ":", "html", "=", "client", ".",...
38.444444
0.000805
def set_file(path, saltenv='base', **kwargs): ''' Set answers to debconf questions from a file. CLI Example: .. code-block:: bash salt '*' debconf.set_file salt://pathto/pkg.selections ''' if '__env__' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('__e...
[ "def", "set_file", "(", "path", ",", "saltenv", "=", "'base'", ",", "*", "*", "kwargs", ")", ":", "if", "'__env__'", "in", "kwargs", ":", "# \"env\" is not supported; Use \"saltenv\".", "kwargs", ".", "pop", "(", "'__env__'", ")", "path", "=", "__salt__", "[...
21.75
0.002203
def savepysyn(self,wave,flux,fname,units=None): """ Cannot ever use the .writefits() method, because the array is frequently just sampled at the synphot waveset; plus, writefits is smart and does things like tapering.""" if units is None: ytype='throughput' units=...
[ "def", "savepysyn", "(", "self", ",", "wave", ",", "flux", ",", "fname", ",", "units", "=", "None", ")", ":", "if", "units", "is", "None", ":", "ytype", "=", "'throughput'", "units", "=", "' '", "else", ":", "ytype", "=", "'flux'", "col1", "=", "py...
47
0.027816
def __global_logging_exception_handler(exc_type, exc_value, exc_traceback): ''' This function will log all un-handled python exceptions. ''' if exc_type.__name__ == "KeyboardInterrupt": # Do not log the exception or display the traceback on Keyboard Interrupt # Stop the logging queue lis...
[ "def", "__global_logging_exception_handler", "(", "exc_type", ",", "exc_value", ",", "exc_traceback", ")", ":", "if", "exc_type", ".", "__name__", "==", "\"KeyboardInterrupt\"", ":", "# Do not log the exception or display the traceback on Keyboard Interrupt", "# Stop the logging ...
41
0.002167
def array_to_hdf5(a, parent, name, **kwargs): """Write a Numpy array to an HDF5 dataset. Parameters ---------- a : ndarray Data to write. parent : string or h5py group Parent HDF5 file or group. If a string, will be treated as HDF5 file name. name : string Name o...
[ "def", "array_to_hdf5", "(", "a", ",", "parent", ",", "name", ",", "*", "*", "kwargs", ")", ":", "import", "h5py", "h5f", "=", "None", "if", "isinstance", "(", "parent", ",", "str", ")", ":", "h5f", "=", "h5py", ".", "File", "(", "parent", ",", "...
22.682927
0.001031
def _get_metadata_for_region(region_code): """The metadata needed by this class is the same for all regions sharing the same country calling code. Therefore, we return the metadata for "main" region for this country calling code.""" country_calling_code = country_code_for_region(region_code) main_co...
[ "def", "_get_metadata_for_region", "(", "region_code", ")", ":", "country_calling_code", "=", "country_code_for_region", "(", "region_code", ")", "main_country", "=", "region_code_for_country_code", "(", "country_calling_code", ")", "# Set to a default instance of the metadata. T...
62.6
0.001575
def _fix_pooling(self, op_name, inputs, new_attr): """onnx pooling operator supports asymmetrical padding Adding pad operator before pooling in mxnet to work with onnx""" pool_type = 'avg' if op_name == 'AveragePool' else 'max' stride = new_attr.get('strides') kernel = new_attr.g...
[ "def", "_fix_pooling", "(", "self", ",", "op_name", ",", "inputs", ",", "new_attr", ")", ":", "pool_type", "=", "'avg'", "if", "op_name", "==", "'AveragePool'", "else", "'max'", "stride", "=", "new_attr", ".", "get", "(", "'strides'", ")", "kernel", "=", ...
57.916667
0.004249
def get_archive_part_value(self, part): """Return archive part for today""" parts_dict = {'year': '%Y', 'month': self.month_format, 'week': self.week_format, 'day': '%d'} if self.today is None: today = timezone.now() ...
[ "def", "get_archive_part_value", "(", "self", ",", "part", ")", ":", "parts_dict", "=", "{", "'year'", ":", "'%Y'", ",", "'month'", ":", "self", ".", "month_format", ",", "'week'", ":", "self", ".", "week_format", ",", "'day'", ":", "'%d'", "}", "if", ...
40.166667
0.004057
def _compute_hamming_matrix(N): """Compute and store a Hamming matrix for |N| nodes. Hamming matrices have the following sizes:: N MBs == === 9 2 10 8 11 32 12 128 13 512 Given these sizes and the fact that large matrices are needed infrequ...
[ "def", "_compute_hamming_matrix", "(", "N", ")", ":", "possible_states", "=", "np", ".", "array", "(", "list", "(", "utils", ".", "all_states", "(", "(", "N", ")", ")", ")", ")", "return", "cdist", "(", "possible_states", ",", "possible_states", ",", "'h...
31.833333
0.001271
def _set_link_fault_signaling(self, v, load=False): """ Setter method for link_fault_signaling, mapped from YANG variable /interface/ethernet/link_fault_signaling (container) If this variable is read-only (config: false) in the source YANG file, then _set_link_fault_signaling is considered as a private ...
[ "def", "_set_link_fault_signaling", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", "...
92.318182
0.004873
def modelAdoptNextOrphan(self, jobId, maxUpdateInterval): """ Look through the models table for an orphaned model, which is a model that is not completed yet, whose _eng_last_update_time is more than maxUpdateInterval seconds ago. If one is found, change its _eng_worker_conn_id to the current worker's ...
[ "def", "modelAdoptNextOrphan", "(", "self", ",", "jobId", ",", "maxUpdateInterval", ")", ":", "@", "g_retrySQL", "def", "findCandidateModelWithRetries", "(", ")", ":", "modelID", "=", "None", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":"...
37.949367
0.006177
def update(self, client=None): """API call: update the project via a ``PUT`` request. See https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/update :type client: :class:`google.cloud.resource_manager.client.Client` or :data:`NoneType <types...
[ "def", "update", "(", "self", ",", "client", "=", "None", ")", ":", "client", "=", "self", ".", "_require_client", "(", "client", ")", "data", "=", "{", "\"name\"", ":", "self", ".", "name", ",", "\"labels\"", ":", "self", ".", "labels", ",", "\"pare...
42.823529
0.005376
def unlock(self, time=3): """ unlock the door\n thanks to https://github.com/SoftwareHouseMerida/pyzk/ :param time: define delay in seconds :return: bool """ command = const.CMD_UNLOCK command_string = pack("I",int(time)*10) cmd_response = self.__...
[ "def", "unlock", "(", "self", ",", "time", "=", "3", ")", ":", "command", "=", "const", ".", "CMD_UNLOCK", "command_string", "=", "pack", "(", "\"I\"", ",", "int", "(", "time", ")", "*", "10", ")", "cmd_response", "=", "self", ".", "__send_command", ...
31.533333
0.00616
def rename_key(d: Dict[str, Any], old: str, new: str) -> None: """ Rename a key in dictionary ``d`` from ``old`` to ``new``, in place. """ d[new] = d.pop(old)
[ "def", "rename_key", "(", "d", ":", "Dict", "[", "str", ",", "Any", "]", ",", "old", ":", "str", ",", "new", ":", "str", ")", "->", "None", ":", "d", "[", "new", "]", "=", "d", ".", "pop", "(", "old", ")" ]
34
0.005747
def config(host, seq, option, value): """Set configuration parameters of the drone.""" at(host, 'CONFIG', seq, [str(option), str(value)])
[ "def", "config", "(", "host", ",", "seq", ",", "option", ",", "value", ")", ":", "at", "(", "host", ",", "'CONFIG'", ",", "seq", ",", "[", "str", "(", "option", ")", ",", "str", "(", "value", ")", "]", ")" ]
47.666667
0.006897
def _trj_backup_trajectory(self, traj, backup_filename=None): """Backs up a trajectory. :param traj: Trajectory that should be backed up :param backup_filename: Path and filename of backup file. If None is specified the storage service defaults to `path_to_trajectory_h...
[ "def", "_trj_backup_trajectory", "(", "self", ",", "traj", ",", "backup_filename", "=", "None", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Storing backup of %s.'", "%", "traj", ".", "v_name", ")", "mypath", ",", "_", "=", "os", ".", "path", "....
37
0.006385
def _lerp(x, x0, x1, y0, y1): """Affinely map from [x0, x1] onto [y0, y1].""" return y0 + (x - x0) * float(y1 - y0) / (x1 - x0)
[ "def", "_lerp", "(", "x", ",", "x0", ",", "x1", ",", "y0", ",", "y1", ")", ":", "return", "y0", "+", "(", "x", "-", "x0", ")", "*", "float", "(", "y1", "-", "y0", ")", "/", "(", "x1", "-", "x0", ")" ]
43
0.022901
def _validate_compose_list(destination_file, file_list, files_metadata=None, number_of_files=32): """Validates the file_list and merges the file_list, files_metadata. Args: destination: Path to the file (ie. /destination_bucket/destination_file). file_list: List of files to compo...
[ "def", "_validate_compose_list", "(", "destination_file", ",", "file_list", ",", "files_metadata", "=", "None", ",", "number_of_files", "=", "32", ")", ":", "common", ".", "validate_file_path", "(", "destination_file", ")", "bucket", "=", "destination_file", "[", ...
39.704918
0.007655
def pretty_print(source, dest): """ Pretty print the XML file """ parser = etree.XMLParser(remove_blank_text=True) if not isinstance(source, str): source = str(source) tree = etree.parse(source, parser) docinfo = tree.docinfo with open(dest, 'wb') as fp: fp.writ...
[ "def", "pretty_print", "(", "source", ",", "dest", ")", ":", "parser", "=", "etree", ".", "XMLParser", "(", "remove_blank_text", "=", "True", ")", "if", "not", "isinstance", "(", "source", ",", "str", ")", ":", "source", "=", "str", "(", "source", ")",...
36.833333
0.004415
def delete(self, uuid): # type: (UUID) -> None """Delete file with given uuid. :param:uuid: :class:`UUID` instance :raises:KeyError if file does not exists """ dest = self.abs_path(uuid) if not dest.exists(): raise KeyError("No file can be found for t...
[ "def", "delete", "(", "self", ",", "uuid", ")", ":", "# type: (UUID) -> None", "dest", "=", "self", ".", "abs_path", "(", "uuid", ")", "if", "not", "dest", ".", "exists", "(", ")", ":", "raise", "KeyError", "(", "\"No file can be found for this uuid\"", ",",...
29
0.008357
def delete_repository_from_recycle_bin(self, project, repository_id): """DeleteRepositoryFromRecycleBin. [Preview API] Destroy (hard delete) a soft-deleted Git repository. :param str project: Project ID or project name :param str repository_id: The ID of the repository. """ ...
[ "def", "delete_repository_from_recycle_bin", "(", "self", ",", "project", ",", "repository_id", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'project'", "]", "=", "self", ".", "_serialize", ".", "u...
52.333333
0.005006
def _check_connectivity(self, err): ''' a method to check connectivity as source of error ''' try: import requests requests.get(self.uptime_ssl) except: from requests import Request request_object = Request(method='GET', url=self...
[ "def", "_check_connectivity", "(", "self", ",", "err", ")", ":", "try", ":", "import", "requests", "requests", ".", "get", "(", "self", ".", "uptime_ssl", ")", "except", ":", "from", "requests", "import", "Request", "request_object", "=", "Request", "(", "...
35.6
0.007299
def jstimestamp(dte): '''Convert a date or datetime object into a javsacript timestamp.''' days = date(dte.year, dte.month, 1).toordinal() - _EPOCH_ORD + dte.day - 1 hours = days*24 if isinstance(dte,datetime): hours += dte.hour minutes = hours*60 + dte.minute second...
[ "def", "jstimestamp", "(", "dte", ")", ":", "days", "=", "date", "(", "dte", ".", "year", ",", "dte", ".", "month", ",", "1", ")", ".", "toordinal", "(", ")", "-", "_EPOCH_ORD", "+", "dte", ".", "day", "-", "1", "hours", "=", "days", "*", "24",...
36.25
0.006726
def create_group(self, group): """ Creates a new group and set group privileges. :param group: The group object to be created. :type group: ``dict`` """ data = json.dumps(self._create_group_dict(group)) response = self._perform_request( u...
[ "def", "create_group", "(", "self", ",", "group", ")", ":", "data", "=", "json", ".", "dumps", "(", "self", ".", "_create_group_dict", "(", "group", ")", ")", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/um/groups'", ",", "method...
24.75
0.004866
def get_link(href, value=None, **kwargs): """ Returns a well-formed link. If href is None/empty, returns an empty string :param href: value to be set for attribute href :param value: the text to be displayed. If None, the href itself is used :param kwargs: additional attributes and values :retur...
[ "def", "get_link", "(", "href", ",", "value", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "href", ":", "return", "\"\"", "anchor_value", "=", "value", "and", "value", "or", "href", "attr", "=", "render_html_attributes", "(", "*", "*", ...
41.153846
0.001828
def _get_tokens_for_line_func(self, cli, document): """ Create a function that returns the tokens for a given line. """ # Cache using `document.text`. def get_tokens_for_line(): return self.lexer.lex_document(cli, document) return self._token_cache.get(docume...
[ "def", "_get_tokens_for_line_func", "(", "self", ",", "cli", ",", "document", ")", ":", "# Cache using `document.text`.", "def", "get_tokens_for_line", "(", ")", ":", "return", "self", ".", "lexer", ".", "lex_document", "(", "cli", ",", "document", ")", "return"...
37.888889
0.005731
def latex(self): """Return LaTeX representation of the abstract.""" s = ('{authors}, \\textit{{{title}}}, {journal}, {volissue}, ' '{pages}, ({date}). {doi}, {scopus_url}.') if len(self.authors) > 1: authors = ', '.join([str(a.given_name) + ...
[ "def", "latex", "(", "self", ")", ":", "s", "=", "(", "'{authors}, \\\\textit{{{title}}}, {journal}, {volissue}, '", "'{pages}, ({date}). {doi}, {scopus_url}.'", ")", "if", "len", "(", "self", ".", "authors", ")", ">", "1", ":", "authors", "=", "', '", ".", "join"...
41.921053
0.001227
def total_seconds(offset): """Backport of offset.total_seconds() from python 2.7+.""" seconds = offset.days * 24 * 60 * 60 + offset.seconds microseconds = seconds * 10**6 + offset.microseconds return microseconds / (10**6 * 1.0)
[ "def", "total_seconds", "(", "offset", ")", ":", "seconds", "=", "offset", ".", "days", "*", "24", "*", "60", "*", "60", "+", "offset", ".", "seconds", "microseconds", "=", "seconds", "*", "10", "**", "6", "+", "offset", ".", "microseconds", "return", ...
48
0.004098
def set_xlabels(self, label=None, **kwargs): """Label the x axis on the bottom row of the grid.""" if label is None: label = label_from_attrs(self.data[self._x_var]) for ax in self._bottom_axes: ax.set_xlabel(label, **kwargs) return self
[ "def", "set_xlabels", "(", "self", ",", "label", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "label", "is", "None", ":", "label", "=", "label_from_attrs", "(", "self", ".", "data", "[", "self", ".", "_x_var", "]", ")", "for", "ax", "in", ...
41
0.006826
def get(self, request, bot_id, id, format=None): """ Get list of source state of a handler --- serializer: StateSerializer responseMessages: - code: 401 message: Not authenticated """ return super(SourceStateList, self).get(request, bot_i...
[ "def", "get", "(", "self", ",", "request", ",", "bot_id", ",", "id", ",", "format", "=", "None", ")", ":", "return", "super", "(", "SourceStateList", ",", "self", ")", ".", "get", "(", "request", ",", "bot_id", ",", "id", ",", "format", ")" ]
32.5
0.005988
def handleException(exception): """ Handles an exception that occurs somewhere in the process of handling a request. """ serverException = exception if not isinstance(exception, exceptions.BaseServerException): with app.test_request_context(): app.log_exception(exception) ...
[ "def", "handleException", "(", "exception", ")", ":", "serverException", "=", "exception", "if", "not", "isinstance", "(", "exception", ",", "exceptions", ".", "BaseServerException", ")", ":", "with", "app", ".", "test_request_context", "(", ")", ":", "app", "...
44.08
0.000888
def simxReadProximitySensor(clientID, sensorHandle, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' detectionState = ct.c_ubyte() detectedObjectHandle = ct.c_int() detectedPoint = (ct.c_float*3)() detectedSurfaceNormalVector = (...
[ "def", "simxReadProximitySensor", "(", "clientID", ",", "sensorHandle", ",", "operationMode", ")", ":", "detectionState", "=", "ct", ".", "c_ubyte", "(", ")", "detectedObjectHandle", "=", "ct", ".", "c_int", "(", ")", "detectedPoint", "=", "(", "ct", ".", "c...
43.647059
0.007916
def replace_grist (features, new_grist): """ Replaces the grist of a string by a new one. Returns the string with the new grist. """ assert is_iterable_typed(features, basestring) or isinstance(features, basestring) assert isinstance(new_grist, basestring) # this function is used a lot in th...
[ "def", "replace_grist", "(", "features", ",", "new_grist", ")", ":", "assert", "is_iterable_typed", "(", "features", ",", "basestring", ")", "or", "isinstance", "(", "features", ",", "basestring", ")", "assert", "isinstance", "(", "new_grist", ",", "basestring",...
39.571429
0.005286
def setRoute(self, vehID, edgeList): """ setRoute(string, list) -> None changes the vehicle route to given edges list. The first edge in the list has to be the one that the vehicle is at at the moment. example usage: setRoute('1', ['1', '2', '4', '6', '7']) th...
[ "def", "setRoute", "(", "self", ",", "vehID", ",", "edgeList", ")", ":", "if", "isinstance", "(", "edgeList", ",", "str", ")", ":", "edgeList", "=", "[", "edgeList", "]", "self", ".", "_connection", ".", "_beginMessage", "(", "tc", ".", "CMD_SET_VEHICLE_...
39.388889
0.006887
def mknod(name, ntype, major=0, minor=0, user=None, group=None, mode='0600'): ''' .. versionadded:: 0.17.0 Create a block device, character device, or fifo pipe. Identical to the gnu mknod. CLI Examples: .. code-block:: bash ...
[ "def", "mknod", "(", "name", ",", "ntype", ",", "major", "=", "0", ",", "minor", "=", "0", ",", "user", "=", "None", ",", "group", "=", "None", ",", "mode", "=", "'0600'", ")", ":", "ret", "=", "False", "makedirs_", "(", "name", ",", "user", ",...
26.771429
0.00103
def copy_snapshot(kwargs=None, call=None): ''' Copy a snapshot ''' if call != 'function': log.error( 'The copy_snapshot function must be called with -f or --function.' ) return False if 'source_region' not in kwargs: log.error('A source_region must be spe...
[ "def", "copy_snapshot", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "log", ".", "error", "(", "'The copy_snapshot function must be called with -f or --function.'", ")", "return", "False", "if", "'source_re...
27.804878
0.000847
def tensor_components_to_use(mrr, mtt, mpp, mrt, mrp, mtp): ''' Converts components to Up, South, East definition:: USE = [[mrr, mrt, mrp], [mtt, mtt, mtp], [mrp, mtp, mpp]] ''' return np.array([[mrr, mrt, mrp], [mrt, mtt, mtp], [mrp, mtp, mpp]])
[ "def", "tensor_components_to_use", "(", "mrr", ",", "mtt", ",", "mpp", ",", "mrt", ",", "mrp", ",", "mtp", ")", ":", "return", "np", ".", "array", "(", "[", "[", "mrr", ",", "mrt", ",", "mrp", "]", ",", "[", "mrt", ",", "mtt", ",", "mtp", "]", ...
31.555556
0.003425
def primers(self, tm=60): '''Design primers for amplifying the assembled sequence. :param tm: melting temperature (lower than overlaps is best). :type tm: float :returns: Primer list (the output of coral.design.primers). :rtype: list ''' self.primers = coral.des...
[ "def", "primers", "(", "self", ",", "tm", "=", "60", ")", ":", "self", ".", "primers", "=", "coral", ".", "design", ".", "primers", "(", "self", ".", "template", ",", "tm", "=", "tm", ")", "return", "self", ".", "primers" ]
33.727273
0.005249
def _doCascadeFetch(obj): ''' _doCascadeFetch - Takes an object and performs a cascading fetch on all foreign links, and all theirs, and so on. @param obj <IndexedRedisModel> - A fetched model ''' obj.validateModel() if not obj.foreignFields: return # NOTE: Currently this fetches using one trans...
[ "def", "_doCascadeFetch", "(", "obj", ")", ":", "obj", ".", "validateModel", "(", ")", "if", "not", "obj", ".", "foreignFields", ":", "return", "# NOTE: Currently this fetches using one transaction per object. Implementation for actual resolution is in", "# IndexedRedisModel....
30.5
0.038411
def _check_log_scale(base, sides, scales, coord): """ Check the log transforms Parameters ---------- base : float or None Base of the logarithm in which the ticks will be calculated. If ``None``, the base of the log transform the scale will be...
[ "def", "_check_log_scale", "(", "base", ",", "sides", ",", "scales", ",", "coord", ")", ":", "def", "is_log", "(", "trans", ")", ":", "return", "(", "trans", ".", "__class__", ".", "__name__", ".", "startswith", "(", "'log'", ")", "and", "hasattr", "("...
38.820896
0.00075
def load_from_tar_or_patch(tar, image_filename, patch_images): """Do everything necessary to process an image inside a TAR. Parameters ---------- tar : `TarFile` instance The tar from which to read `image_filename`. image_filename : str Fully-qualified path inside of `tar` from whic...
[ "def", "load_from_tar_or_patch", "(", "tar", ",", "image_filename", ",", "patch_images", ")", ":", "patched", "=", "True", "image_bytes", "=", "patch_images", ".", "get", "(", "os", ".", "path", ".", "basename", "(", "image_filename", ")", ",", "None", ")", ...
36.864865
0.000714
def visit(self, node): """ Replace the placeholder if it is one or continue. """ if isinstance(node, Placeholder): return self.placeholders[node.id] else: return super(PlaceholderReplace, self).visit(node)
[ "def", "visit", "(", "self", ",", "node", ")", ":", "if", "isinstance", "(", "node", ",", "Placeholder", ")", ":", "return", "self", ".", "placeholders", "[", "node", ".", "id", "]", "else", ":", "return", "super", "(", "PlaceholderReplace", ",", "self...
41.333333
0.007905
def _resolve_children(self, ldap_user, groups): """ Generates the query result for each child. """ for child in self.children: if isinstance(child, LDAPGroupQuery): yield child.resolve(ldap_user, groups) else: yield groups.is_member...
[ "def", "_resolve_children", "(", "self", ",", "ldap_user", ",", "groups", ")", ":", "for", "child", "in", "self", ".", "children", ":", "if", "isinstance", "(", "child", ",", "LDAPGroupQuery", ")", ":", "yield", "child", ".", "resolve", "(", "ldap_user", ...
35.777778
0.006061
def get_dataset(self, key, info): """Get the dataset refered to by `key`.""" angles = self._get_coarse_dataset(key, info) if angles is None: return # Fill gaps at edges of swath darr = DataArray(angles, dims=['y', 'x']) darr = darr.bfill('x') darr = ...
[ "def", "get_dataset", "(", "self", ",", "key", ",", "info", ")", ":", "angles", "=", "self", ".", "_get_coarse_dataset", "(", "key", ",", "info", ")", "if", "angles", "is", "None", ":", "return", "# Fill gaps at edges of swath", "darr", "=", "DataArray", "...
30.2
0.00321
def _get_credentials_from_settings(self): """Get the stored credentials if any.""" remember_me = CONF.get('main', 'report_error/remember_me') remember_token = CONF.get('main', 'report_error/remember_token') username = CONF.get('main', 'report_error/username', '') if not remember_...
[ "def", "_get_credentials_from_settings", "(", "self", ")", ":", "remember_me", "=", "CONF", ".", "get", "(", "'main'", ",", "'report_error/remember_me'", ")", "remember_token", "=", "CONF", ".", "get", "(", "'main'", ",", "'report_error/remember_token'", ")", "use...
43.888889
0.004963
def get_grading_standards_for_course(self, course_id): """ List the grading standards available to a course https://canvas.instructure.com/doc/api/grading_standards.html#method.grading_standards_api.context_index """ url = COURSES_API.format(course_id) + "/grading_standards" ...
[ "def", "get_grading_standards_for_course", "(", "self", ",", "course_id", ")", ":", "url", "=", "COURSES_API", ".", "format", "(", "course_id", ")", "+", "\"/grading_standards\"", "standards", "=", "[", "]", "for", "data", "in", "self", ".", "_get_resource", "...
41.454545
0.004292
def update(self): """Update the IRQ stats.""" # Init new stats stats = self.get_init_value() # IRQ plugin only available on GNU/Linux if not LINUX: return self.stats if self.input_method == 'local': # Grab the stats stats = self.irq.g...
[ "def", "update", "(", "self", ")", ":", "# Init new stats", "stats", "=", "self", ".", "get_init_value", "(", ")", "# IRQ plugin only available on GNU/Linux", "if", "not", "LINUX", ":", "return", "self", ".", "stats", "if", "self", ".", "input_method", "==", "...
24.5
0.003021
def estimate_achievable_tmid_precision(snr, t_ingress_min=10, t_duration_hr=2.14): '''Using Carter et al. 2009's estimate, calculate the theoretical optimal precision on mid-transit time measurement possible given a transit of a particular SNR. The relation used i...
[ "def", "estimate_achievable_tmid_precision", "(", "snr", ",", "t_ingress_min", "=", "10", ",", "t_duration_hr", "=", "2.14", ")", ":", "t_ingress", "=", "t_ingress_min", "*", "u", ".", "minute", "t_duration", "=", "t_duration_hr", "*", "u", ".", "hour", "theta...
32.018182
0.001102
def step(self, action): """Repeat action, sum reward, and max over last observations.""" total_reward = 0.0 done = None for i in range(self._skip): obs, reward, done, info = self.env.step(action) if i == self._skip - 2: self._obs_buffer[0] = obs if i == self._skip - 1: ...
[ "def", "step", "(", "self", ",", "action", ")", ":", "total_reward", "=", "0.0", "done", "=", "None", "for", "i", "in", "range", "(", "self", ".", "_skip", ")", ":", "obs", ",", "reward", ",", "done", ",", "info", "=", "self", ".", "env", ".", ...
34.4375
0.010601
def context(root, project=""): """Produce the be environment The environment is an exact replica of the active environment of the current process, with a few additional variables, all of which are listed below. """ environment = os.environ.copy() environment.update({ "BE_PROJECT":...
[ "def", "context", "(", "root", ",", "project", "=", "\"\"", ")", ":", "environment", "=", "os", ".", "environ", ".", "copy", "(", ")", "environment", ".", "update", "(", "{", "\"BE_PROJECT\"", ":", "project", ",", "\"BE_PROJECTROOT\"", ":", "(", "os", ...
25.861111
0.001035
def render(self, doc, context=None, math_option=False, img_path='', css_path=CSS_PATH): """Start thread to render a given documentation""" # If the thread is already running wait for it to finish before # starting it again. if self.wait(): self.doc = doc ...
[ "def", "render", "(", "self", ",", "doc", ",", "context", "=", "None", ",", "math_option", "=", "False", ",", "img_path", "=", "''", ",", "css_path", "=", "CSS_PATH", ")", ":", "# If the thread is already running wait for it to finish before", "# starting it again."...
41.846154
0.005396
def list_security_groups(self, retrieve_all=True, **_params): """Fetches a list of all security groups for a project.""" return self.list('security_groups', self.security_groups_path, retrieve_all, **_params)
[ "def", "list_security_groups", "(", "self", ",", "retrieve_all", "=", "True", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "list", "(", "'security_groups'", ",", "self", ".", "security_groups_path", ",", "retrieve_all", ",", "*", "*", "_params"...
61.5
0.008032
def _to_dict(objects): ''' Potentially interprets a string as JSON for usage with mongo ''' try: if isinstance(objects, six.string_types): objects = salt.utils.json.loads(objects) except ValueError as err: log.error("Could not parse objects: %s", err) raise err ...
[ "def", "_to_dict", "(", "objects", ")", ":", "try", ":", "if", "isinstance", "(", "objects", ",", "six", ".", "string_types", ")", ":", "objects", "=", "salt", ".", "utils", ".", "json", ".", "loads", "(", "objects", ")", "except", "ValueError", "as", ...
27.166667
0.002967
def insert(self, song): """在当前歌曲后插入一首歌曲""" if song in self._songs: return if self._current_song is None: self._songs.append(song) else: index = self._songs.index(self._current_song) self._songs.insert(index + 1, song)
[ "def", "insert", "(", "self", ",", "song", ")", ":", "if", "song", "in", "self", ".", "_songs", ":", "return", "if", "self", ".", "_current_song", "is", "None", ":", "self", ".", "_songs", ".", "append", "(", "song", ")", "else", ":", "index", "=",...
32.111111
0.006734
def stop(self): """ Stop this WriterProcessBase, and reset the cursor. """ self.stop_flag.value = True with self.lock: ( Control().text(C(' ', style='reset_all')) .pos_restore().move_column(1).erase_line() .write(self.file) ...
[ "def", "stop", "(", "self", ")", ":", "self", ".", "stop_flag", ".", "value", "=", "True", "with", "self", ".", "lock", ":", "(", "Control", "(", ")", ".", "text", "(", "C", "(", "' '", ",", "style", "=", "'reset_all'", ")", ")", ".", "pos_restor...
34.777778
0.006231
def getReadGroupSet(self, id_): """ Returns the readgroup set with the specified ID. """ compoundId = datamodel.ReadGroupSetCompoundId.parse(id_) dataset = self.getDataset(compoundId.dataset_id) return dataset.getReadGroupSet(id_)
[ "def", "getReadGroupSet", "(", "self", ",", "id_", ")", ":", "compoundId", "=", "datamodel", ".", "ReadGroupSetCompoundId", ".", "parse", "(", "id_", ")", "dataset", "=", "self", ".", "getDataset", "(", "compoundId", ".", "dataset_id", ")", "return", "datase...
38.857143
0.007194
def __main(draft, directory, project_name, project_version, project_date, answer_yes): """ The main entry point. """ directory = os.path.abspath(directory) config = load_config(directory) to_err = draft click.echo("Loading template...", err=to_err) if config["template"] is None: ...
[ "def", "__main", "(", "draft", ",", "directory", ",", "project_name", ",", "project_version", ",", "project_date", ",", "answer_yes", ")", ":", "directory", "=", "os", ".", "path", ".", "abspath", "(", "directory", ")", "config", "=", "load_config", "(", "...
31.833333
0.001016
def _make_info(self, name, stat_result, namespaces): """Create an `Info` object from a stat result. """ info = { 'basic': { 'name': name, 'is_dir': stat.S_ISDIR(stat_result.st_mode) } } if 'details' in namespaces: ...
[ "def", "_make_info", "(", "self", ",", "name", ",", "stat_result", ",", "namespaces", ")", ":", "info", "=", "{", "'basic'", ":", "{", "'name'", ":", "name", ",", "'is_dir'", ":", "stat", ".", "S_ISDIR", "(", "stat_result", ".", "st_mode", ")", "}", ...
35.684211
0.002874
def render_source(self): """Render the sourcecode.""" return SOURCE_TABLE_HTML % u'\n'.join(line.render() for line in self.get_annotated_lines())
[ "def", "render_source", "(", "self", ")", ":", "return", "SOURCE_TABLE_HTML", "%", "u'\\n'", ".", "join", "(", "line", ".", "render", "(", ")", "for", "line", "in", "self", ".", "get_annotated_lines", "(", ")", ")" ]
51
0.009662
def avail_locations(call=None): ''' List all available locations ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) ret = {} conn = get_conn() ...
[ "def", "avail_locations", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The avail_locations function must be called with '", "'-f or --function, or with the --list-locations option'", ")", "ret", "=", "{", ...
29.65
0.004902
def stop_timer(self, timer_id): """ Stop a timer. If the timer is not active, nothing happens. """ self._logger.debug('Stop timer {} in stm {}'.format(timer_id, self.id)) self._driver._stop_timer(timer_id, self)
[ "def", "stop_timer", "(", "self", ",", "timer_id", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'Stop timer {} in stm {}'.", "f", "ormat(", "t", "imer_id,", " ", "elf.", "i", "d)", ")", "", "self", ".", "_driver", ".", "_stop_timer", "(", "timer...
31.625
0.007692
def send_media_group(self, chat_id, media, disable_notification=None, reply_to_message_id=None): """ Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned. https://core.telegram.org/bots/api#sendmediagroup Parameters: ...
[ "def", "send_media_group", "(", "self", ",", "chat_id", ",", "media", ",", "disable_notification", "=", "None", ",", "reply_to_message_id", "=", "None", ")", ":", "assert_type_or_raise", "(", "chat_id", ",", "(", "int", ",", "unicode_type", ")", ",", "paramete...
46.446154
0.006487
def register(linter): """ Registering additional checkers. """ # add all of the checkers register_checkers(linter) # register any checking fiddlers try: from pylint_django.augmentations import apply_augmentations apply_augmentations(linter) except ImportError: # ...
[ "def", "register", "(", "linter", ")", ":", "# add all of the checkers", "register_checkers", "(", "linter", ")", "# register any checking fiddlers", "try", ":", "from", "pylint_django", ".", "augmentations", "import", "apply_augmentations", "apply_augmentations", "(", "l...
29.833333
0.001805
def resolve_blobs(self, iter_blobs): """Resolve the blobs given in blob iterator. This will effectively remove the index entries of the respective path at all non-null stages and add the given blob as new stage null blob. For each path there may only be one blob, otherwise a ValueError ...
[ "def", "resolve_blobs", "(", "self", ",", "iter_blobs", ")", ":", "for", "blob", "in", "iter_blobs", ":", "stage_null_key", "=", "(", "blob", ".", "path", ",", "0", ")", "if", "stage_null_key", "in", "self", ".", "entries", ":", "raise", "ValueError", "(...
37.5
0.004587
def read_mm_uic2(fd, byte_order, dtype, count): """Read MM_UIC2 tag from file and return as dictionary.""" result = {'number_planes': count} values = numpy.fromfile(fd, byte_order+'I', 6*count) result['z_distance'] = values[0::6] // values[1::6] #result['date_created'] = tuple(values[2::6]) #res...
[ "def", "read_mm_uic2", "(", "fd", ",", "byte_order", ",", "dtype", ",", "count", ")", ":", "result", "=", "{", "'number_planes'", ":", "count", "}", "values", "=", "numpy", ".", "fromfile", "(", "fd", ",", "byte_order", "+", "'I'", ",", "6", "*", "co...
47.2
0.010395
def mission_start_date_as_string(self) -> str: """ Returns: mission start date as string """ return self._start_date_as_string(self.day, self.month, self.year)
[ "def", "mission_start_date_as_string", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_start_date_as_string", "(", "self", ".", "day", ",", "self", ".", "month", ",", "self", ".", "year", ")" ]
37.4
0.010471
def infer_typing_namedtuple_class(class_node, context=None): """Infer a subclass of typing.NamedTuple""" # Check if it has the corresponding bases annassigns_fields = [ annassign.target.name for annassign in class_node.body if isinstance(annassign, nodes.AnnAssign) ] code = d...
[ "def", "infer_typing_namedtuple_class", "(", "class_node", ",", "context", "=", "None", ")", ":", "# Check if it has the corresponding bases", "annassigns_fields", "=", "[", "annassign", ".", "target", ".", "name", "for", "annassign", "in", "class_node", ".", "body", ...
38
0.001351
def find_atoms_near_atom(self, source_atom, search_radius, atom_hit_cache = set(), atom_names_to_include = set(), atom_names_to_exclude = set(), restrict_to_CA = False): '''It is advisable to set up and use an atom hit cache object. This reduces the number of distance calculations and gives better performance. ...
[ "def", "find_atoms_near_atom", "(", "self", ",", "source_atom", ",", "search_radius", ",", "atom_hit_cache", "=", "set", "(", ")", ",", "atom_names_to_include", "=", "set", "(", ")", ",", "atom_names_to_exclude", "=", "set", "(", ")", ",", "restrict_to_CA", "=...
69.114286
0.010192
def add(event, reactors, saltenv='base', test=None): ''' Add a new reactor CLI Example: .. code-block:: bash salt-run reactor.add 'salt/cloud/*/destroyed' reactors='/srv/reactor/destroy/*.sls' ''' if isinstance(reactors, string_types): reactors = [reactors] sevent = salt....
[ "def", "add", "(", "event", ",", "reactors", ",", "saltenv", "=", "'base'", ",", "test", "=", "None", ")", ":", "if", "isinstance", "(", "reactors", ",", "string_types", ")", ":", "reactors", "=", "[", "reactors", "]", "sevent", "=", "salt", ".", "ut...
28.793103
0.002317
def _run(self, thread_n): """The thread function.""" try: logger.debug("{0!r}: entering thread #{1}" .format(self, thread_n)) resolver = self._make_resolver() while True: request = self.queue.get() ...
[ "def", "_run", "(", "self", ",", "thread_n", ")", ":", "try", ":", "logger", ".", "debug", "(", "\"{0!r}: entering thread #{1}\"", ".", "format", "(", "self", ",", "thread_n", ")", ")", "resolver", "=", "self", ".", "_make_resolver", "(", ")", "while", "...
44.368421
0.006969
def get_primitive_structure(self, tolerance=0.25, use_site_props=False, constrain_latt=None): """ This finds a smaller unit cell than the input. Sometimes it doesn"t find the smallest possible one, so this method is recursively called until it is unable to...
[ "def", "get_primitive_structure", "(", "self", ",", "tolerance", "=", "0.25", ",", "use_site_props", "=", "False", ",", "constrain_latt", "=", "None", ")", ":", "if", "constrain_latt", "is", "None", ":", "constrain_latt", "=", "[", "]", "def", "site_label", ...
44.597015
0.000982
def run(self): """ Run the server. Returns with system error code. """ normalized = os.path.normpath(self.path) + ("/" if self.path.endswith("/") else "") if self.path != normalized: sys.stderr.write("Please use full path '%s'" % (normalized,)) return -1 self.bu...
[ "def", "run", "(", "self", ")", ":", "normalized", "=", "os", ".", "path", ".", "normpath", "(", "self", ".", "path", ")", "+", "(", "\"/\"", "if", "self", ".", "path", ".", "endswith", "(", "\"/\"", ")", "else", "\"\"", ")", "if", "self", ".", ...
33.047619
0.005602
def _uninstall(action='remove', name=None, pkgs=None, **kwargs): ''' remove and purge do identical things but with different pacman commands, this function performs the common logic. ''' try: pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0] except MinionError as exc: ...
[ "def", "_uninstall", "(", "action", "=", "'remove'", ",", "name", "=", "None", ",", "pkgs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "pkg_params", "=", "__salt__", "[", "'pkg_resource.parse_targets'", "]", "(", "name", ",", "pkgs", "...
27.44898
0.000718
def getFullPathToSnapshot(self, n): """Get the full path to snapshot n.""" return os.path.join(self.snapDir, str(n))
[ "def", "getFullPathToSnapshot", "(", "self", ",", "n", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "snapDir", ",", "str", "(", "n", ")", ")" ]
39.333333
0.033333
def ufo_create_background_layer_for_all_glyphs(ufo_font): # type: (defcon.Font) -> None """Create a background layer for all glyphs in ufo_font if not present to reduce roundtrip differences.""" if "public.background" in ufo_font.layers: background = ufo_font.layers["public.background"] els...
[ "def", "ufo_create_background_layer_for_all_glyphs", "(", "ufo_font", ")", ":", "# type: (defcon.Font) -> None", "if", "\"public.background\"", "in", "ufo_font", ".", "layers", ":", "background", "=", "ufo_font", ".", "layers", "[", "\"public.background\"", "]", "else", ...
37.153846
0.00202
def _setup_tls_files(self, files): """Initiates TLSFIle objects with the paths given to this bundle""" for file_type in TLSFileType: if file_type.value in files: file_path = files[file_type.value] setattr(self, file_type.value, TLSFile...
[ "def", "_setup_tls_files", "(", "self", ",", "files", ")", ":", "for", "file_type", "in", "TLSFileType", ":", "if", "file_type", ".", "value", "in", "files", ":", "file_path", "=", "files", "[", "file_type", ".", "value", "]", "setattr", "(", "self", ","...
43.25
0.005666
def _finish_transaction_with_retry(self, command_name, explict_retry): """Run commit or abort with one retry after any retryable error. :Parameters: - `command_name`: Either "commitTransaction" or "abortTransaction". - `explict_retry`: True when this is an explict commit retry attem...
[ "def", "_finish_transaction_with_retry", "(", "self", ",", "command_name", ",", "explict_retry", ")", ":", "# This can be refactored with MongoClient._retry_with_session.", "try", ":", "return", "self", ".", "_finish_transaction", "(", "command_name", ",", "explict_retry", ...
45.103448
0.001497
def _find_next(server): """Finds the name of the next repository to run based on the *current* state of the database. """ from datetime import datetime #Re-load the database in case we have multiple instances of the script #running in memory. _load_db() result = None visited = [] ...
[ "def", "_find_next", "(", "server", ")", ":", "from", "datetime", "import", "datetime", "#Re-load the database in case we have multiple instances of the script", "#running in memory.", "_load_db", "(", ")", "result", "=", "None", "visited", "=", "[", "]", "if", "\"statu...
38.0625
0.008004
def clean(args): """ %prog clean fastafile Remove irregular chars in FASTA seqs. """ p = OptionParser(clean.__doc__) p.add_option("--fancy", default=False, action="store_true", help="Pretty print the sequence [default: %default]") p.add_option("--canonical", default=False, ...
[ "def", "clean", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "clean", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--fancy\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Pretty print the sequen...
28.939394
0.001013
async def spawn_n(self, agent_cls, n, *args, **kwargs): '''Spawn *n* agents to the managed environment. This is a convenience function so that one does not have to repeatedly make connections to the environment to spawn multiple agents with the same parameters. See :py:meth:`~creamas.mp...
[ "async", "def", "spawn_n", "(", "self", ",", "agent_cls", ",", "n", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "rets", "=", "[", "]", "for", "_", "in", "range", "(", "n", ")", ":", "ret", "=", "await", "self", ".", "spawn", "(", "ag...
42.416667
0.003846
def from_dict(d): """Transform the dict to a record object and return the record.""" query_params_match = d.get('@query_params_match') query_person_match = d.get('@query_person_match') valid_since = d.get('@valid_since') if valid_since: valid_since = str_to_datetime(v...
[ "def", "from_dict", "(", "d", ")", ":", "query_params_match", "=", "d", ".", "get", "(", "'@query_params_match'", ")", "query_person_match", "=", "d", ".", "get", "(", "'@query_person_match'", ")", "valid_since", "=", "d", ".", "get", "(", "'@valid_since'", ...
49.384615
0.007645
def run(path, code=None, params=None, **meta): """Check code with mypy. :return list: List of errors. """ args = [path, '--follow-imports=skip', '--show-column-numbers'] stdout, stderr, status = api.run(args) messages = [] for line in stdout.split('\n'): ...
[ "def", "run", "(", "path", ",", "code", "=", "None", ",", "params", "=", "None", ",", "*", "*", "meta", ")", ":", "args", "=", "[", "path", ",", "'--follow-imports=skip'", ",", "'--show-column-numbers'", "]", "stdout", ",", "stderr", ",", "status", "="...
34.809524
0.002663
async def shutdown(self, force = False, connmark = -1): ''' Can call without delegate ''' if connmark is None: connmark = self.connmark self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.SHUTDOWN, force, connmark))
[ "async", "def", "shutdown", "(", "self", ",", "force", "=", "False", ",", "connmark", "=", "-", "1", ")", ":", "if", "connmark", "is", "None", ":", "connmark", "=", "self", ".", "connmark", "self", ".", "scheduler", ".", "emergesend", "(", "ConnectionC...
41
0.023891
def batch(args): """ %prog batch all.cds *.anchors Compute Ks values for a set of anchors file. This will generate a bunch of work directories for each comparisons. The anchorsfile should be in the form of specie1.species2.anchors. """ from jcvi.apps.grid import MakeManager p = OptionP...
[ "def", "batch", "(", "args", ")", ":", "from", "jcvi", ".", "apps", ".", "grid", "import", "MakeManager", "p", "=", "OptionParser", "(", "batch", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", ...
31.363636
0.003749
def _set_igmps_static_group(self, v, load=False): """ Setter method for igmps_static_group, mapped from YANG variable /bridge_domain/ip/bd_ip_igmp/snooping/igmps_static_group (list) If this variable is read-only (config: false) in the source YANG file, then _set_igmps_static_group is considered as a pri...
[ "def", "_set_igmps_static_group", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ","...
131.454545
0.003776
def update(self, value=None): """ Update progress bar via the console or notebook accordingly. """ # Update self.value if value is None: value = self._current_value + 1 self._current_value = value # Choose the appropriate environment if self....
[ "def", "update", "(", "self", ",", "value", "=", "None", ")", ":", "# Update self.value", "if", "value", "is", "None", ":", "value", "=", "self", ".", "_current_value", "+", "1", "self", ".", "_current_value", "=", "value", "# Choose the appropriate environmen...
27.5
0.003906
def expand_curlys(s): """Takes string and returns list of options: Example ------- >>> expand_curlys("py{26, 27}") ["py26", "py27"] """ from functools import reduce curleys = list(re.finditer(r"{[^{}]*}", s)) return reduce(_replace_curly, reversed(curleys), [s])
[ "def", "expand_curlys", "(", "s", ")", ":", "from", "functools", "import", "reduce", "curleys", "=", "list", "(", "re", ".", "finditer", "(", "r\"{[^{}]*}\"", ",", "s", ")", ")", "return", "reduce", "(", "_replace_curly", ",", "reversed", "(", "curleys", ...
24.083333
0.003333
def id(self, opts_id): """Handles tracking and cleanup of custom ids.""" old_id = self._id self._id = opts_id if old_id is not None: cleanup_custom_options(old_id) if opts_id is not None and opts_id != old_id: if opts_id not in Store._weakrefs: ...
[ "def", "id", "(", "self", ",", "opts_id", ")", ":", "old_id", "=", "self", ".", "_id", "self", ".", "_id", "=", "opts_id", "if", "old_id", "is", "not", "None", ":", "cleanup_custom_options", "(", "old_id", ")", "if", "opts_id", "is", "not", "None", "...
42.818182
0.004158
def create_multi_weather(df, rename_dc): """Create a list of oemof weather objects if the given geometry is a polygon """ weather_list = [] # Create a pandas.DataFrame with the time series of the weather data set # for each data set and append them to a list. for gid in df.gid.unique(): ...
[ "def", "create_multi_weather", "(", "df", ",", "rename_dc", ")", ":", "weather_list", "=", "[", "]", "# Create a pandas.DataFrame with the time series of the weather data set", "# for each data set and append them to a list.", "for", "gid", "in", "df", ".", "gid", ".", "uni...
40.727273
0.004367