text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def draw_lasers_3d(ax, lasers, name=None, distances=None, lim=None): """Draw MOT lasers in 3d.""" if distances is None: distances = [1.0 for i in range(len(lasers))] for i in range(len(lasers)): if type(lasers[i]) == PlaneWave: draw_plane_wave_3d(ax, lasers[i], distances[i]) ...
[ "def", "draw_lasers_3d", "(", "ax", ",", "lasers", ",", "name", "=", "None", ",", "distances", "=", "None", ",", "lim", "=", "None", ")", ":", "if", "distances", "is", "None", ":", "distances", "=", "[", "1.0", "for", "i", "in", "range", "(", "len"...
34
15.863636
def _import_module(self, s): """ Import a module. """ mod = __import__(s) parts = s.split('.') for part in parts[1:]: mod = getattr(mod, part) return mod
[ "def", "_import_module", "(", "self", ",", "s", ")", ":", "mod", "=", "__import__", "(", "s", ")", "parts", "=", "s", ".", "split", "(", "'.'", ")", "for", "part", "in", "parts", "[", "1", ":", "]", ":", "mod", "=", "getattr", "(", "mod", ",", ...
23.666667
9.888889
def _api_action(url, req, data=None): """Take action based on what kind of request is needed.""" requisite_headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} auth = (user, token) if req == "GET": response = requests.get(url, headers=requisite_h...
[ "def", "_api_action", "(", "url", ",", "req", ",", "data", "=", "None", ")", ":", "requisite_headers", "=", "{", "'Accept'", ":", "'application/json'", ",", "'Content-Type'", ":", "'application/json'", "}", "auth", "=", "(", "user", ",", "token", ")", "if"...
42.111111
19.666667
def plot_ticks(ax, tick_fontsize=12, xticks=None, xticks_args=None, yticks=None, yticks_args=None, zticks=None, zticks_args=None): """Function that defines the labels options of a matplotlib plot. Args: ax: matplotlib axes tick_fontsize (int): Define...
[ "def", "plot_ticks", "(", "ax", ",", "tick_fontsize", "=", "12", ",", "xticks", "=", "None", ",", "xticks_args", "=", "None", ",", "yticks", "=", "None", ",", "yticks_args", "=", "None", ",", "zticks", "=", "None", ",", "zticks_args", "=", "None", ")",...
43.6
19.933333
def cermine(pdf_file, force_api=False, override_local=None): """ Run `CERMINE <https://github.com/CeON/CERMINE>`_ to extract metadata from \ the given PDF file, to retrieve citations (and more) from the \ provided PDF file. This function returns the raw output of \ CERMINE ca...
[ "def", "cermine", "(", "pdf_file", ",", "force_api", "=", "False", ",", "override_local", "=", "None", ")", ":", "try", ":", "# Check if we want to load the local JAR from a specific path", "local", "=", "override_local", "# Else, try to stat the JAR file at the expected loca...
41.567164
20.910448
def write(self, msg, level=logging.INFO): """ method implements stream write interface, allowing to redirect stdout to logger """ if msg is not None and len(msg.strip()) > 0: self.logger.log(level, msg)
[ "def", "write", "(", "self", ",", "msg", ",", "level", "=", "logging", ".", "INFO", ")", ":", "if", "msg", "is", "not", "None", "and", "len", "(", "msg", ".", "strip", "(", ")", ")", ">", "0", ":", "self", ".", "logger", ".", "log", "(", "lev...
56.75
3.5
def build(source_dir, target_dir, package_name=None, version_number=None): ''' Create a release of a MicroDrop plugin source directory in the target directory path. Skip the following patterns: - ``bld.bat`` - ``.conda-recipe/*`` - ``.git/*`` .. versionchanged:: 0.24.1 ...
[ "def", "build", "(", "source_dir", ",", "target_dir", ",", "package_name", "=", "None", ",", "version_number", "=", "None", ")", ":", "source_dir", "=", "ph", ".", "path", "(", "source_dir", ")", ".", "realpath", "(", ")", "target_dir", "=", "ph", ".", ...
36.925532
20.989362
def delete(self, force=False, **kwargs): """ It is impossible to delete an activatable model unless force is True. This function instead sets it to inactive. """ if force: return super(BaseActivatableModel, self).delete(**kwargs) else: setattr(self, self.A...
[ "def", "delete", "(", "self", ",", "force", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "force", ":", "return", "super", "(", "BaseActivatableModel", ",", "self", ")", ".", "delete", "(", "*", "*", "kwargs", ")", "else", ":", "setattr", ...
46.111111
23.666667
def parse(cls, fptr, offset=0, length=0): """Parse a codestream box. Parameters ---------- fptr : file Open file object. offset : int Start position of box in bytes. length : int Length of the box in bytes. Returns ---...
[ "def", "parse", "(", "cls", ",", "fptr", ",", "offset", "=", "0", ",", "length", "=", "0", ")", ":", "main_header_offset", "=", "fptr", ".", "tell", "(", ")", "if", "config", ".", "get_option", "(", "'parse.full_codestream'", ")", ":", "codestream", "=...
30.111111
16.222222
def _parse_value(cls, stream_rdr, offset, value_count, value_offset): """ Return the rational (numerator / denominator) value at *value_offset* in *stream_rdr* as a floating-point number. Only supports single values at present. """ if value_count == 1: numerat...
[ "def", "_parse_value", "(", "cls", ",", "stream_rdr", ",", "offset", ",", "value_count", ",", "value_offset", ")", ":", "if", "value_count", "==", "1", ":", "numerator", "=", "stream_rdr", ".", "read_long", "(", "value_offset", ")", "denominator", "=", "stre...
45.583333
15.916667
def configure_edges(self, info): """ Handles display of the edges editor. """ if info.initialized: self.model.edit_traits(parent=info.ui.control, kind="live", view=edges_view)
[ "def", "configure_edges", "(", "self", ",", "info", ")", ":", "if", "info", ".", "initialized", ":", "self", ".", "model", ".", "edit_traits", "(", "parent", "=", "info", ".", "ui", ".", "control", ",", "kind", "=", "\"live\"", ",", "view", "=", "edg...
37
7.166667
def increase_and_check_counter(self): ''' increase counter by one and check whether a period is end ''' self.counter += 1 self.counter %= self.period if not self.counter: return True else: return False
[ "def", "increase_and_check_counter", "(", "self", ")", ":", "self", ".", "counter", "+=", "1", "self", ".", "counter", "%=", "self", ".", "period", "if", "not", "self", ".", "counter", ":", "return", "True", "else", ":", "return", "False" ]
32.25
16
def with_path(self, path): """ Return new Command object that will be run with a new addition to the PATH environment variable that will be fed to the command. """ new_command = copy.deepcopy(self) new_command._paths.append(str(path)) return new_command
[ "def", "with_path", "(", "self", ",", "path", ")", ":", "new_command", "=", "copy", ".", "deepcopy", "(", "self", ")", "new_command", ".", "_paths", ".", "append", "(", "str", "(", "path", ")", ")", "return", "new_command" ]
37.75
12
def add_pdf(self, post_data): ''' Adding the pdf file. ''' img_entity = self.request.files['file'][0] img_desc = post_data['desc'] filename = img_entity["filename"] if filename and allowed_file_pdf(filename): pass else: return Fal...
[ "def", "add_pdf", "(", "self", ",", "post_data", ")", ":", "img_entity", "=", "self", ".", "request", ".", "files", "[", "'file'", "]", "[", "0", "]", "img_desc", "=", "post_data", "[", "'desc'", "]", "filename", "=", "img_entity", "[", "\"filename\"", ...
35.027027
19.135135
def on_add_cols(self, event): """ Show simple dialog that allows user to add a new column name """ col_labels = self.grid.col_labels # do not list headers that are already column labels in the grid er_items = [head for head in self.grid_headers[self.grid_type]['er'][2] if...
[ "def", "on_add_cols", "(", "self", ",", "event", ")", ":", "col_labels", "=", "self", ".", "grid", ".", "col_labels", "# do not list headers that are already column labels in the grid", "er_items", "=", "[", "head", "for", "head", "in", "self", ".", "grid_headers", ...
49.714286
23.904762
def with_access_to(self, request, *args, **kwargs): # pylint: disable=invalid-name,unused-argument """ Returns the list of enterprise customers the user has a specified group permission access to. """ self.queryset = self.queryset.order_by('name') enterprise_id = self.request.qu...
[ "def", "with_access_to", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=invalid-name,unused-argument", "self", ".", "queryset", "=", "self", ".", "queryset", ".", "order_by", "(", "'name'", ")", "enterprise...
55.6875
24.6875
def getattr(attr, default=None): """Get a named attribute from an object. When a default argument is given, it is returned when the attribute doesn't exist. """ def getter(value): return _getattr(value, attr, default) return transform(getter)
[ "def", "getattr", "(", "attr", ",", "default", "=", "None", ")", ":", "def", "getter", "(", "value", ")", ":", "return", "_getattr", "(", "value", ",", "attr", ",", "default", ")", "return", "transform", "(", "getter", ")" ]
26.7
17.6
def reset(self): """ Reset this Layout and the Widgets it contains. """ # Ensure that the widgets are using the right values. self.update_widgets() # Reset all the widgets. for column in self._columns: for widget in column: widget.rese...
[ "def", "reset", "(", "self", ")", ":", "# Ensure that the widgets are using the right values.", "self", ".", "update_widgets", "(", ")", "# Reset all the widgets.", "for", "column", "in", "self", ".", "_columns", ":", "for", "widget", "in", "column", ":", "widget", ...
28.125
13.25
def _send(self, metric): """ Send data to gmond. """ metric_name = self.get_name_from_path(metric.path) tmax = "60" dmax = "0" slope = "both" # FIXME: Badness, shouldn't *assume* double type metric_type = "double" units = "" group =...
[ "def", "_send", "(", "self", ",", "metric", ")", ":", "metric_name", "=", "self", ".", "get_name_from_path", "(", "metric", ".", "path", ")", "tmax", "=", "\"60\"", "dmax", "=", "\"0\"", "slope", "=", "\"both\"", "# FIXME: Badness, shouldn't *assume* double type...
29.25
11.25
def get_app_name(self): """ Return the appname of the APK :rtype: string """ main_activity_name = self.get_main_activity() app_name = self.get_element('activity', 'label', name=main_activity_name) if not app_name: app_name = self.get_element(...
[ "def", "get_app_name", "(", "self", ")", ":", "main_activity_name", "=", "self", ".", "get_main_activity", "(", ")", "app_name", "=", "self", ".", "get_element", "(", "'activity'", ",", "'label'", ",", "name", "=", "main_activity_name", ")", "if", "not", "ap...
32.833333
18.75
def print_tb(tb, limit=None, file=None): """Print up to 'limit' stack trace entries from the traceback 'tb'. If 'limit' is omitted or None, all entries are printed. If 'file' is omitted or None, the output goes to sys.stderr; otherwise 'file' should be an open file or file-like object with a write() ...
[ "def", "print_tb", "(", "tb", ",", "limit", "=", "None", ",", "file", "=", "None", ")", ":", "if", "file", "is", "None", ":", "file", "=", "sys", ".", "stderr", "if", "limit", "is", "None", ":", "if", "hasattr", "(", "sys", ",", "'tracebacklimit'",...
37.928571
15.928571
def printInspectors(): """ Prints a list of inspectors """ # Imported here so this module can be imported without Qt being installed. from argos.application import ArgosApplication argosApp = ArgosApplication() argosApp.loadOrInitRegistries() for regItem in argosApp.inspectorRegistry.items:...
[ "def", "printInspectors", "(", ")", ":", "# Imported here so this module can be imported without Qt being installed.", "from", "argos", ".", "application", "import", "ArgosApplication", "argosApp", "=", "ArgosApplication", "(", ")", "argosApp", ".", "loadOrInitRegistries", "(...
34.3
13.9
def run_contamination(in_prefix, in_type, out_prefix, base_dir, options): """Runs the contamination check for samples. :param in_prefix: the prefix of the input files. :param in_type: the type of the input files. :param out_prefix: the output prefix. :param base_dir: the output directory. :para...
[ "def", "run_contamination", "(", "in_prefix", ",", "in_type", ",", "out_prefix", ",", "base_dir", ",", "options", ")", ":", "# Creating the output directory", "os", ".", "mkdir", "(", "out_prefix", ")", "# We know we need a bfile", "required_type", "=", "\"bfile\"", ...
40.64881
19.690476
def mutate(self, chromosomes, p_mutate): """ Call every chromosome's ``mutate`` method. p_mutate: probability of mutation in [0, 1] """ assert 0 <= p_mutate <= 1 for chromosome in chromosomes: chromosome.mutate(p_mutate)
[ "def", "mutate", "(", "self", ",", "chromosomes", ",", "p_mutate", ")", ":", "assert", "0", "<=", "p_mutate", "<=", "1", "for", "chromosome", "in", "chromosomes", ":", "chromosome", ".", "mutate", "(", "p_mutate", ")" ]
29.2
9.7
def cut_cross(self, x, y, radius, data): """Cut two data subarrays that have a center at (x, y) and with radius (radius) from (data). Returns the starting pixel (x0, y0) of each cut and the respective arrays (xarr, yarr). """ n = int(round(radius)) ht, wd = data.shape ...
[ "def", "cut_cross", "(", "self", ",", "x", ",", "y", ",", "radius", ",", "data", ")", ":", "n", "=", "int", "(", "round", "(", "radius", ")", ")", "ht", ",", "wd", "=", "data", ".", "shape", "x", ",", "y", "=", "int", "(", "round", "(", "x"...
44.230769
10.538462
def add_host(ip, alias): ''' Add a host to an existing entry, if the entry is not in place then create it with the given host CLI Example: .. code-block:: bash salt '*' hosts.add_host <ip> <alias> ''' hfn = _get_or_create_hostfile() if not os.path.isfile(hfn): return F...
[ "def", "add_host", "(", "ip", ",", "alias", ")", ":", "hfn", "=", "_get_or_create_hostfile", "(", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "hfn", ")", ":", "return", "False", "if", "has_pair", "(", "ip", ",", "alias", ")", ":", "ret...
24.242424
21.090909
def cached_request(self, request): """ Return a cached response if it exists in the cache, otherwise return False. """ cache_url = self.cache_url(request.url) cc = self.parse_cache_control(request.headers) # non-caching states no_cache = True if 'no-cache...
[ "def", "cached_request", "(", "self", ",", "request", ")", ":", "cache_url", "=", "self", ".", "cache_url", "(", "request", ".", "url", ")", "cc", "=", "self", ".", "parse_cache_control", "(", "request", ".", "headers", ")", "# non-caching states", "no_cache...
33.907216
19.164948
def document_path_path(cls, project, database, document_path): """Return a fully-qualified document_path string.""" return google.api_core.path_template.expand( "projects/{project}/databases/{database}/documents/{document_path=**}", project=project, database=database,...
[ "def", "document_path_path", "(", "cls", ",", "project", ",", "database", ",", "document_path", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/databases/{database}/documents/{document_path=**}\"", ",", "pro...
45.5
16.25
def update(taxids, conn, force_download, silent): """Update local UniProt database""" if not silent: click.secho("WARNING: Update is very time consuming and can take several " "hours depending which organisms you are importing!", fg="yellow") if not taxids: click...
[ "def", "update", "(", "taxids", ",", "conn", ",", "force_download", ",", "silent", ")", ":", "if", "not", "silent", ":", "click", ".", "secho", "(", "\"WARNING: Update is very time consuming and can take several \"", "\"hours depending which organisms you are importing!\"",...
49
32.3125
def compute_layout_properties( width, height, frame_width, frame_height, explicit_width, explicit_height, aspect, data_aspect, responsive, size_multiplier, logger=None): """ Utility to compute the aspect, plot width/height and sizing_mode behavior. Args: width (int): Plot ...
[ "def", "compute_layout_properties", "(", "width", ",", "height", ",", "frame_width", ",", "frame_height", ",", "explicit_width", ",", "explicit_height", ",", "aspect", ",", "data_aspect", ",", "responsive", ",", "size_multiplier", ",", "logger", "=", "None", ")", ...
37.943038
16.056962
def set_object_status(self, statusdict): """ Set statuses from a dictionary of format ``{name: status}`` """ for name, value in statusdict.items(): getattr(self.system, name).status = value return True
[ "def", "set_object_status", "(", "self", ",", "statusdict", ")", ":", "for", "name", ",", "value", "in", "statusdict", ".", "items", "(", ")", ":", "getattr", "(", "self", ".", "system", ",", "name", ")", ".", "status", "=", "value", "return", "True" ]
35.857143
10.142857
def set_bool_param(params, name, value): """ Set a boolean parameter if applicable. :param dict params: A dict containing API call parameters. :param str name: The name of the parameter to set. :param bool value: The value of the parameter. If ``None``, the field will not be set. If ...
[ "def", "set_bool_param", "(", "params", ",", "name", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "if", "value", "is", "True", ":", "params", "[", "name", "]", "=", "'true'", "elif", "value", "is", "False", ":", "params", "[", ...
29.6
22.88
def iter_content(self, chunk_size=1024): """Return the file content as an iterable stream.""" r = self._session.get(self.content, stream=True) return r.iter_content(chunk_size)
[ "def", "iter_content", "(", "self", ",", "chunk_size", "=", "1024", ")", ":", "r", "=", "self", ".", "_session", ".", "get", "(", "self", ".", "content", ",", "stream", "=", "True", ")", "return", "r", ".", "iter_content", "(", "chunk_size", ")" ]
49.25
4.25
def remove(self, id_option_pool): """Remove Option pool by identifier and all Environment related . :param id_option_pool: Identifier of the Option Pool. Integer value and greater than zero. :return: None :raise InvalidParameterError: Option Pool identifier is null and invalid. ...
[ "def", "remove", "(", "self", ",", "id_option_pool", ")", ":", "if", "not", "is_valid_int_param", "(", "id_option_pool", ")", ":", "raise", "InvalidParameterError", "(", "u'The identifier of Option Pool is invalid or was not informed.'", ")", "url", "=", "'api/pools/optio...
40.857143
26.761905
def get_objective_bank_admin_session(self, proxy, *args, **kwargs): """Gets the OsidSession associated with the objective bank administration service. :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: an ``ObjectiveBankAdminSession`` :rtype: ``osid.learning.Object...
[ "def", "get_objective_bank_admin_session", "(", "self", ",", "proxy", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "supports_objective_bank_admin", "(", ")", ":", "raise", "Unimplemented", "(", ")", "try", ":", "from", "."...
41.846154
20.346154
def table(self, header=None, rows=None, style=None): """ Return a Table instance. """ if style is not None: style = self.TABLE_STYLES[style] table = Table(style) if header: table.set_header_row(header) if rows: table.set_rows...
[ "def", "table", "(", "self", ",", "header", "=", "None", ",", "rows", "=", "None", ",", "style", "=", "None", ")", ":", "if", "style", "is", "not", "None", ":", "style", "=", "self", ".", "TABLE_STYLES", "[", "style", "]", "table", "=", "Table", ...
20.8125
17.5625
def _copyDPToClipboard(self): """Callback for item menu.""" dp = self._dp_menu_on if dp and dp.archived: path = dp.fullpath.replace(" ", "\\ ") QApplication.clipboard().setText(path, QClipboard.Clipboard) QApplication.clipboard().setText(path, QClipboard.Selec...
[ "def", "_copyDPToClipboard", "(", "self", ")", ":", "dp", "=", "self", ".", "_dp_menu_on", "if", "dp", "and", "dp", ".", "archived", ":", "path", "=", "dp", ".", "fullpath", ".", "replace", "(", "\" \"", ",", "\"\\\\ \"", ")", "QApplication", ".", "cli...
45.571429
15.142857
def delete(self, cluster): """Deletes the cluster from memory. :param cluster: cluster to delete :type cluster: :py:class:`elasticluster.cluster.Cluster` """ if cluster.name not in self.clusters: raise ClusterNotFound( "Unable to delete non-existent c...
[ "def", "delete", "(", "self", ",", "cluster", ")", ":", "if", "cluster", ".", "name", "not", "in", "self", ".", "clusters", ":", "raise", "ClusterNotFound", "(", "\"Unable to delete non-existent cluster %s\"", "%", "cluster", ".", "name", ")", "del", "self", ...
37.7
12.5
def get_cat_model(model): """ Return a class from a string or class """ try: if isinstance(model, string_types): model_class = apps.get_model(*model.split(".")) elif issubclass(model, CategoryBase): model_class = model if model_class is None: r...
[ "def", "get_cat_model", "(", "model", ")", ":", "try", ":", "if", "isinstance", "(", "model", ",", "string_types", ")", ":", "model_class", "=", "apps", ".", "get_model", "(", "*", "model", ".", "split", "(", "\".\"", ")", ")", "elif", "issubclass", "(...
31.357143
12.5
def process_directive(self, directive): """ Process a directive which either adds some files from ``allfiles`` to ``files``, or removes some files from ``files``. :param directive: The directive to process. This should be in a format compatible with distutils ``MANI...
[ "def", "process_directive", "(", "self", ",", "directive", ")", ":", "# Parse the line: split it up, make sure the right number of words", "# is there, and return the relevant words. 'action' is always", "# defined: it's the first word of the line. Which of the other", "# three are defined d...
46.959459
21.418919
def delete_description(self, lang=None): """Deletes all the `label` metadata properties on your Thing/Point for this language Raises `ValueError` containing an error message if the parameters fail validation `lang` (optional) (string) The two-character ISO 639-1 language code to use for your l...
[ "def", "delete_description", "(", "self", ",", "lang", "=", "None", ")", ":", "self", ".", "_remove_properties_by_language", "(", "self", ".", "_commentPredicate", ",", "Validation", ".", "lang_check_convert", "(", "lang", ",", "default", "=", "self", ".", "_d...
58.181818
30.636364
def handle_response (response): """ Handle a response from the newton API """ response = json.loads(response.read()) # Was the expression valid? if 'error' in response: raise ValueError(response['error']) else: # Some of the strings returned can be parsed to integer...
[ "def", "handle_response", "(", "response", ")", ":", "response", "=", "json", ".", "loads", "(", "response", ".", "read", "(", ")", ")", "# Was the expression valid?", "if", "'error'", "in", "response", ":", "raise", "ValueError", "(", "response", "[", "'err...
31.85
14.15
def plan(*args, **kwargs): ''' plan(name1=calcs1, name2=calc2...) yields a new calculation plan (object of type Plan) that is itself a constructor for the calculation dictionary that is implied by the given calc functionss given. The names that are given are used as identifiers for updating th...
[ "def", "plan", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "1", "and", "len", "(", "kwargs", ")", "==", "0", "and", "is_imap", "(", "args", "[", "0", "]", ")", ":", "return", "args", "[", "0", "...
55.3125
31.5625
def presets_dir(): """Return presets directory""" default_presets_dir = os.path.join( os.path.expanduser("~"), ".be", "presets") presets_dir = os.environ.get(BE_PRESETSDIR) or default_presets_dir if not os.path.exists(presets_dir): os.makedirs(presets_dir) return presets_dir
[ "def", "presets_dir", "(", ")", ":", "default_presets_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", ",", "\".be\"", ",", "\"presets\"", ")", "presets_dir", "=", "os", ".", "environ", ".", "get"...
38
11.25
def _xdr_read_asset(unpacker): """Reads a stellar Asset from unpacker""" asset = messages.StellarAssetType(type=unpacker.unpack_uint()) if asset.type == ASSET_TYPE_ALPHA4: asset.code = unpacker.unpack_fstring(4) asset.issuer = _xdr_read_address(unpacker) if asset.type == ASSET_TYPE_ALP...
[ "def", "_xdr_read_asset", "(", "unpacker", ")", ":", "asset", "=", "messages", ".", "StellarAssetType", "(", "type", "=", "unpacker", ".", "unpack_uint", "(", ")", ")", "if", "asset", ".", "type", "==", "ASSET_TYPE_ALPHA4", ":", "asset", ".", "code", "=", ...
33.153846
16.615385
def check_exists(self): ''' Check if resource exists, update self.exists, returns Returns: None: sets self.exists ''' response = self.repo.api.http_request('HEAD', self.uri) self.status_code = response.status_code # resource exists if self.status_code == 200: self.exists = True # resource no ...
[ "def", "check_exists", "(", "self", ")", ":", "response", "=", "self", ".", "repo", ".", "api", ".", "http_request", "(", "'HEAD'", ",", "self", ".", "uri", ")", "self", ".", "status_code", "=", "response", ".", "status_code", "# resource exists", "if", ...
22.142857
21
def setup_directories(base_dir, subdirs): """Setup directories.""" base_dir = os.path.expanduser(base_dir) tf.gfile.MakeDirs(base_dir) all_dirs = {} for subdir in subdirs: if isinstance(subdir, six.string_types): subdir_tuple = (subdir,) else: subdir_tuple = subdir dir_name = os.path....
[ "def", "setup_directories", "(", "base_dir", ",", "subdirs", ")", ":", "base_dir", "=", "os", ".", "path", ".", "expanduser", "(", "base_dir", ")", "tf", ".", "gfile", ".", "MakeDirs", "(", "base_dir", ")", "all_dirs", "=", "{", "}", "for", "subdir", "...
27.8
13.666667
def create_status_callback(self, callback=None): """ Creates a callback for the rlbot status, uses default function if callback is none. :param callback: :return: """ if callback is None: return self.callback_func def safe_wrapper(id, rlbotstatsus): ...
[ "def", "create_status_callback", "(", "self", ",", "callback", "=", "None", ")", ":", "if", "callback", "is", "None", ":", "return", "self", ".", "callback_func", "def", "safe_wrapper", "(", "id", ",", "rlbotstatsus", ")", ":", "callback", "(", "rlbotstatsus...
32.076923
18.230769
def put(self, task_id, buffer): """ TODO: docstring """ task_id_bytes = task_id.to_bytes(4, "little") message = [b"", task_id_bytes] + buffer self.zmq_socket.send_multipart(message) logger.debug("Sent task {}".format(task_id))
[ "def", "put", "(", "self", ",", "task_id", ",", "buffer", ")", ":", "task_id_bytes", "=", "task_id", ".", "to_bytes", "(", "4", ",", "\"little\"", ")", "message", "=", "[", "b\"\"", ",", "task_id_bytes", "]", "+", "buffer", "self", ".", "zmq_socket", "...
37.285714
12.571429
def schedule(self, duration, at=None, delay=None, callback=None): """ schedules the measurement (to execute asynchronously). :param duration: how long to run for. :param at: the time to start at. :param delay: the time to wait til starting (use at or delay). :param callba...
[ "def", "schedule", "(", "self", ",", "duration", ",", "at", "=", "None", ",", "delay", "=", "None", ",", "callback", "=", "None", ")", ":", "delay", "=", "self", ".", "calculateDelay", "(", "at", ",", "delay", ")", "self", ".", "callback", "=", "ca...
52
20
def update_kwargs(kwargs, *updates): """ Utility function for merging multiple keyword arguments, depending on their type: * Non-existent keys are added. * Existing lists or tuples are extended, but not duplicating entries. The keywords ``command`` and ``entrypoint`` are however simply overwritte...
[ "def", "update_kwargs", "(", "kwargs", ",", "*", "updates", ")", ":", "for", "update", "in", "updates", ":", "if", "not", "update", ":", "continue", "for", "key", ",", "val", "in", "six", ".", "iteritems", "(", "update", ")", ":", "u_item", "=", "res...
41.604167
17.270833
def set_cell_value(self, row, index, value): """Sets the value for the cell at row[index].""" if self._set_cell_value: self._set_cell_value(row, index, value) else: row[index] = value
[ "def", "set_cell_value", "(", "self", ",", "row", ",", "index", ",", "value", ")", ":", "if", "self", ".", "_set_cell_value", ":", "self", ".", "_set_cell_value", "(", "row", ",", "index", ",", "value", ")", "else", ":", "row", "[", "index", "]", "="...
33.666667
11.333333
def fromimportunreg( cls, bundle, cid, rsid, import_ref, exception, endpoint ): # type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], ImportReference, Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object...
[ "def", "fromimportunreg", "(", "cls", ",", "bundle", ",", "cid", ",", "rsid", ",", "import_ref", ",", "exception", ",", "endpoint", ")", ":", "# type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], ImportReference, Optional[Tuple[Any, Any, Any]], EndpointDescription) -> R...
38.294118
22.411765
def maximin_distance_subset1d(items, K=None, min_thresh=None, verbose=False): r""" Greedy algorithm, may be exact for 1d case. First, choose the first item, then choose the next item that is farthest away from all previously chosen items. Iterate. CommandLine: python -m utool.util_alg --exe...
[ "def", "maximin_distance_subset1d", "(", "items", ",", "K", "=", "None", ",", "min_thresh", "=", "None", ",", "verbose", "=", "False", ")", ":", "if", "False", ":", "import", "pulp", "# Formulate integer program", "prob", "=", "pulp", ".", "LpProblem", "(", ...
36.321918
20.479452
def __shpFileLength(self): """Calculates the file length of the shp file.""" # Remember starting position start = self.shp.tell() # Calculate size of all shapes self.shp.seek(0,2) size = self.shp.tell() # Calculate size as 16-bit words size //= 2 ...
[ "def", "__shpFileLength", "(", "self", ")", ":", "# Remember starting position\r", "start", "=", "self", ".", "shp", ".", "tell", "(", ")", "# Calculate size of all shapes\r", "self", ".", "shp", ".", "seek", "(", "0", ",", "2", ")", "size", "=", "self", "...
32.083333
9.583333
def _batch_load(project, workspace, headerline, entity_data, chunk_size=500): """ Submit a large number of entity updates in batches of chunk_size """ if fcconfig.verbosity: print("Batching " + str(len(entity_data)) + " updates to Firecloud...") # Parse the entity type from the first cell, e.g. "...
[ "def", "_batch_load", "(", "project", ",", "workspace", ",", "headerline", ",", "entity_data", ",", "chunk_size", "=", "500", ")", ":", "if", "fcconfig", ".", "verbosity", ":", "print", "(", "\"Batching \"", "+", "str", "(", "len", "(", "entity_data", ")",...
39.1875
24.3125
def _Sublimation_Pressure(T): """Sublimation Pressure correlation Parameters ---------- T : float Temperature, [K] Returns ------- P : float Pressure at sublimation line, [MPa] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: * ...
[ "def", "_Sublimation_Pressure", "(", "T", ")", ":", "if", "50", "<=", "T", "<=", "273.16", ":", "Tita", "=", "T", "/", "Tt", "suma", "=", "0", "a", "=", "[", "-", "0.212144006e2", ",", "0.273203819e2", ",", "-", "0.61059813e1", "]", "expo", "=", "[...
23.923077
23
def apply_to(self, x, columns=False): """Apply this rotation to the given object The argument can be several sorts of objects: * ``np.array`` with shape (3, ) * ``np.array`` with shape (N, 3) * ``np.array`` with shape (3, N), use ``columns=True`` * ``Tran...
[ "def", "apply_to", "(", "self", ",", "x", ",", "columns", "=", "False", ")", ":", "if", "isinstance", "(", "x", ",", "np", ".", "ndarray", ")", "and", "len", "(", "x", ".", "shape", ")", "==", "2", "and", "x", ".", "shape", "[", "0", "]", "==...
44.411765
20.264706
def closest(self, obj, group, defaults=True): """ This method is designed to be called from the root of the tree. Given any LabelledData object, this method will return the most appropriate Options object, including inheritance. In addition, closest supports custom options by ch...
[ "def", "closest", "(", "self", ",", "obj", ",", "group", ",", "defaults", "=", "True", ")", ":", "components", "=", "(", "obj", ".", "__class__", ".", "__name__", ",", "group_sanitizer", "(", "obj", ".", "group", ")", ",", "label_sanitizer", "(", "obj"...
45.066667
17.733333
def undo_filter(self, filter_type, scanline, previous): """ Undo the filter for a scanline. `scanline` is a sequence of bytes that does not include the initial filter type byte. `previous` is decoded previous scanline (for straightlaced images this is the previous pixel r...
[ "def", "undo_filter", "(", "self", ",", "filter_type", ",", "scanline", ",", "previous", ")", ":", "# :todo: Would it be better to update scanline in place?", "result", "=", "scanline", "if", "filter_type", "==", "0", ":", "return", "result", "if", "filter_type", "n...
40.384615
18.730769
def translate_table(data): """ Translates data where data["Type"]=="Table" """ headers = sorted(data.get("Headers", [])) table = '\\FloatBarrier \n \\section{$NAME} \n'.replace('$NAME', data.get("Title", "table")) table += '\\begin{table}[!ht] \n \\begin{center}' # Set the number of columns n_c...
[ "def", "translate_table", "(", "data", ")", ":", "headers", "=", "sorted", "(", "data", ".", "get", "(", "\"Headers\"", ",", "[", "]", ")", ")", "table", "=", "'\\\\FloatBarrier \\n \\\\section{$NAME} \\n'", ".", "replace", "(", "'$NAME'", ",", "data", ".", ...
38.952381
20.809524
def __roll(self, unrolled): """Converts parameter array back into matrices.""" rolled = [] index = 0 for count in range(len(self.__sizes) - 1): in_size = self.__sizes[count] out_size = self.__sizes[count+1] theta_unrolled = np.matrix(unrolled[index:ind...
[ "def", "__roll", "(", "self", ",", "unrolled", ")", ":", "rolled", "=", "[", "]", "index", "=", "0", "for", "count", "in", "range", "(", "len", "(", "self", ".", "__sizes", ")", "-", "1", ")", ":", "in_size", "=", "self", ".", "__sizes", "[", "...
42.916667
14.25
def set_file_encoding(self, path, encoding): """ Cache encoding for the specified file path. :param path: path of the file to cache :param encoding: encoding to cache """ try: map = json.loads(self._settings.value('cachedFileEncodings')) except TypeEr...
[ "def", "set_file_encoding", "(", "self", ",", "path", ",", "encoding", ")", ":", "try", ":", "map", "=", "json", ".", "loads", "(", "self", ".", "_settings", ".", "value", "(", "'cachedFileEncodings'", ")", ")", "except", "TypeError", ":", "map", "=", ...
33.384615
15.538462
def _validate(claims, validate_claims, expiry_seconds): """ Validate expiry related claims. If validate_claims is False, do nothing. Otherwise, validate the exp and nbf claims if they are present, and validate the iat claim if expiry_seconds is provided. """ if not validate_claims: ret...
[ "def", "_validate", "(", "claims", ",", "validate_claims", ",", "expiry_seconds", ")", ":", "if", "not", "validate_claims", ":", "return", "now", "=", "time", "(", ")", "# TODO: implement support for clock skew", "# The exp (expiration time) claim identifies the expiration ...
35.083333
24.041667
def proc_response(self, resp): """Process JSON data found in the response.""" # Try to interpret any JSON try: resp.obj = json.loads(resp.body) self._debug(" Received entity: %r", resp.obj) except ValueError: resp.obj = None self._debug("...
[ "def", "proc_response", "(", "self", ",", "resp", ")", ":", "# Try to interpret any JSON", "try", ":", "resp", ".", "obj", "=", "json", ".", "loads", "(", "resp", ".", "body", ")", "self", ".", "_debug", "(", "\" Received entity: %r\"", ",", "resp", ".", ...
35.461538
17.461538
def get_service(self, factory, svc_registration): # type: (Any, ServiceRegistration) -> Any """ Returns the service required by the bundle. The Service Factory is called only when necessary while the Prototype Service Factory is called each time :param factory: The servi...
[ "def", "get_service", "(", "self", ",", "factory", ",", "svc_registration", ")", ":", "# type: (Any, ServiceRegistration) -> Any", "svc_ref", "=", "svc_registration", ".", "get_reference", "(", ")", "if", "svc_ref", ".", "is_prototype", "(", ")", ":", "return", "s...
42.8125
19.1875
def get_client(site=None): """Get a citrination client""" if 'CITRINATION_API_KEY' not in environ: raise ValueError("'CITRINATION_API_KEY' is not set as an environment variable") if not site: site = environ.get("CITRINATION_SITE", "https://citrination.com") return CitrinationClient(envir...
[ "def", "get_client", "(", "site", "=", "None", ")", ":", "if", "'CITRINATION_API_KEY'", "not", "in", "environ", ":", "raise", "ValueError", "(", "\"'CITRINATION_API_KEY' is not set as an environment variable\"", ")", "if", "not", "site", ":", "site", "=", "environ",...
49.428571
21.142857
def _get_vswitch_name(self, network_type, physical_network): """Get the vswitch name for the received network information.""" if network_type != constants.TYPE_LOCAL: vswitch_name = self._get_vswitch_for_physical_network( physical_network) else: vswitch_na...
[ "def", "_get_vswitch_name", "(", "self", ",", "network_type", ",", "physical_network", ")", ":", "if", "network_type", "!=", "constants", ".", "TYPE_LOCAL", ":", "vswitch_name", "=", "self", ".", "_get_vswitch_for_physical_network", "(", "physical_network", ")", "el...
43.588235
18.058824
def unique_rows(data, digits=None): """ Returns indices of unique rows. It will return the first occurrence of a row that is duplicated: [[1,2], [3,4], [1,2]] will return [0,1] Parameters --------- data: (n,m) set of floating point data digits: how many digits to consider for the purpos...
[ "def", "unique_rows", "(", "data", ",", "digits", "=", "None", ")", ":", "hashes", "=", "hashable_rows", "(", "data", ",", "digits", "=", "digits", ")", "garbage", ",", "unique", ",", "inverse", "=", "np", ".", "unique", "(", "hashes", ",", "return_ind...
34.5
16.5
def frommatrix(cls, apart, dpart, src_radius, det_radius, init_matrix, det_curvature_radius=None, **kwargs): """Create an instance of `FanBeamGeometry` using a matrix. This alternative constructor uses a matrix to rotate and translate the default configuration. It is most use...
[ "def", "frommatrix", "(", "cls", ",", "apart", ",", "dpart", ",", "src_radius", ",", "det_radius", ",", "init_matrix", ",", "det_curvature_radius", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Get transformation and translation parts from `init_matrix`", "init...
42.45977
19.344828
def get_output_matrix(self): """ Get a copy of the full output matrix of a Model. This only works if the model is not quantized. """ if self.f.isQuant(): raise ValueError("Can't get quantized Matrix") return np.array(self.f.getOutputMatrix())
[ "def", "get_output_matrix", "(", "self", ")", ":", "if", "self", ".", "f", ".", "isQuant", "(", ")", ":", "raise", "ValueError", "(", "\"Can't get quantized Matrix\"", ")", "return", "np", ".", "array", "(", "self", ".", "f", ".", "getOutputMatrix", "(", ...
36.875
10.125
def plot_attribute_distribution(docgraph, elements, attribute, ignore_missing=True): ''' creates and prints a barplot (using matplotlib) for all values that an attribute can have, e.g. counts of POS tags for all token nodes in a document graph. docgraph : DiscourseDo...
[ "def", "plot_attribute_distribution", "(", "docgraph", ",", "elements", ",", "attribute", ",", "ignore_missing", "=", "True", ")", ":", "value_counts", "=", "Counter", "(", ")", "if", "isinstance", "(", "elements", ",", "GeneratorType", ")", ":", "elements", "...
38.57377
20.311475
def translate_abstract_actions_to_keys(self, abstract): """ Translates a list of tuples ([pretty mapping], [value]) to a list of tuples ([some key], [translated value]) each single item in abstract will undergo the following translation: Example1: we want: "MoveRight": 5.0 ...
[ "def", "translate_abstract_actions_to_keys", "(", "self", ",", "abstract", ")", ":", "# Solve single tuple with name and value -> should become a list (len=1) of this tuple.", "if", "len", "(", "abstract", ")", ">=", "2", "and", "not", "isinstance", "(", "abstract", "[", ...
45.083333
26.527778
def save_project(self, fname=None, pwd=None, pack=False, **kwargs): """ Save this project to a file Parameters ---------- fname: str or None If None, the dictionary will be returned. Otherwise the necessary information to load this project via the :meth:`...
[ "def", "save_project", "(", "self", ",", "fname", "=", "None", ",", "pwd", "=", "None", ",", "pack", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# store the figure informatoptions and array informations", "if", "fname", "is", "not", "None", "and", "pwd...
45.432432
17.279279
def hyperedge_cardinality_pairs_list(H): """Returns a list of 2-tuples of (\|tail\|, \|head\|) for each hyperedge in the hypergraph. :param H: the hypergraph whose cardinality ratios will be operated on. :returns: list -- list of 2-tuples for each hyperedge's cardinality. :raises: TypeE...
[ "def", "hyperedge_cardinality_pairs_list", "(", "H", ")", ":", "if", "not", "isinstance", "(", "H", ",", "DirectedHypergraph", ")", ":", "raise", "TypeError", "(", "\"Algorithm only applicable to directed hypergraphs\"", ")", "return", "[", "(", "len", "(", "H", "...
41.3125
20.375
def _get_century_code(year): """Returns the century code for a given year""" if 2000 <= year < 3000: separator = 'A' elif 1900 <= year < 2000: separator = '-' elif 1800 <= year < 1900: separator = '+' else: raise ValueError('Finnish...
[ "def", "_get_century_code", "(", "year", ")", ":", "if", "2000", "<=", "year", "<", "3000", ":", "separator", "=", "'A'", "elif", "1900", "<=", "year", "<", "2000", ":", "separator", "=", "'-'", "elif", "1800", "<=", "year", "<", "1900", ":", "separa...
37.454545
17.363636
def find_rrset(self, section, name, rdclass, rdtype, covers=dns.rdatatype.NONE, deleting=None, create=False, force_unique=False): """Find the RRset with the given attributes in the specified section. @param section: the section of the message to look in, e.g. ...
[ "def", "find_rrset", "(", "self", ",", "section", ",", "name", ",", "rdclass", ",", "rdtype", ",", "covers", "=", "dns", ".", "rdatatype", ".", "NONE", ",", "deleting", "=", "None", ",", "create", "=", "False", ",", "force_unique", "=", "False", ")", ...
41.733333
14.622222
def change_interface_id(self, interface_id): """ Change the interface ID for this interface. This can be used on any interface type. If the interface is an Inline interface, you must provide the ``interface_id`` in format '1-2' to define both interfaces in the pair. The change is...
[ "def", "change_interface_id", "(", "self", ",", "interface_id", ")", ":", "splitted", "=", "str", "(", "interface_id", ")", ".", "split", "(", "'-'", ")", "if1", "=", "splitted", "[", "0", "]", "for", "interface", "in", "self", ".", "all_interfaces", ":"...
42.12766
19.659574
def validate_mutations(self, mutations): '''This function has been refactored to use the SimpleMutation class. The parameter is a list of Mutation objects. The function has no return value but raises a PDBValidationException if the wildtype in the Mutation m does not match the residue type...
[ "def", "validate_mutations", "(", "self", ",", "mutations", ")", ":", "# Chain, ResidueID, WildTypeAA, MutantAA", "resID2AA", "=", "self", ".", "get_residue_id_to_type_map", "(", ")", "badmutations", "=", "[", "]", "for", "m", "in", "mutations", ":", "wildtype", "...
62.714286
33.428571
def process(self, pq): """ :arg PlaceQuery pq: PlaceQuery instance :returns: PlaceQuery instance with :py:attr:`query` converted to individual elements """ if pq.query != '': postcode = address = city = '' # define the vars we'll use # ...
[ "def", "process", "(", "self", ",", "pq", ")", ":", "if", "pq", ".", "query", "!=", "''", ":", "postcode", "=", "address", "=", "city", "=", "''", "# define the vars we'll use", "# global regex postcode search, pop off last result", "postcode_matches", "=", "self"...
49.702128
26.425532
def convolve(data, kernel, method='scipy'): r"""Convolve data with kernel This method convolves the input data with a given kernel using FFT and is the default convolution used for all routines Parameters ---------- data : np.ndarray Input data array, normally a 2D image kernel : n...
[ "def", "convolve", "(", "data", ",", "kernel", ",", "method", "=", "'scipy'", ")", ":", "if", "data", ".", "ndim", "!=", "kernel", ".", "ndim", ":", "raise", "ValueError", "(", "'Data and kernel must have the same dimensions.'", ")", "if", "method", "not", "...
27.591549
21.760563
def get_url(url, data=None, cached=True, cache_key=None, crawler='urllib'): """Retrieves the HTML code for a given URL. If a cached version is not available, uses phantom_retrieve to fetch the page. data - Additional data that gets passed onto the crawler. cached - If True, retrieves the URL from the ...
[ "def", "get_url", "(", "url", ",", "data", "=", "None", ",", "cached", "=", "True", ",", "cache_key", "=", "None", ",", "crawler", "=", "'urllib'", ")", ":", "if", "cache_key", "is", "None", ":", "cache_key", "=", "url", "cache_path", "=", "cache_path_...
44.586207
19.551724
def imshow_interact(self, canvas, plot_function, extent=None, label=None, vmin=None, vmax=None, **kwargs): """ This function is optional! Create an imshow controller to stream the image returned by the plot_function. There is an imshow controller written for mmatplotlib, which...
[ "def", "imshow_interact", "(", "self", ",", "canvas", ",", "plot_function", ",", "extent", "=", "None", ",", "label", "=", "None", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(...
52.076923
32.230769
def bookmark(ctx): """Bookmark build job. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon build bookmark ``` \b ```bash $ polyaxon build -b 2 bookmark ``` """ user, project_name, _build = get_build_or_local(ctx.obj.get('project'),...
[ "def", "bookmark", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_build", "=", "get_build_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'build'", ")", ")", "try", ":", "Po...
26.884615
28
def resolve_any_xref(self, env, fromdocname, builder, target, node, contnode): """Look for any references, without object type This always searches in "refspecific" mode """ prefix = node.get('dn:prefix') results = [] match = self.find_obj(env, ...
[ "def", "resolve_any_xref", "(", "self", ",", "env", ",", "fromdocname", ",", "builder", ",", "target", ",", "node", ",", "contnode", ")", ":", "prefix", "=", "node", ".", "get", "(", "'dn:prefix'", ")", "results", "=", "[", "]", "match", "=", "self", ...
38.5625
16.9375
def absent(name, region=None, key=None, keyid=None, profile=None): ''' Ensure an ELB does not exist name name of the ELB ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} exists = __salt__['boto_elb.exists'](name, region, key, keyid, profile) if exists: ...
[ "def", "absent", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''"...
35.555556
23.62963
def list_cameras(): """ List all attached USB cameras that are supported by libgphoto2. :return: All recognized cameras :rtype: list of :py:class:`Camera` """ ctx = lib.gp_context_new() camlist_p = new_gp_object("CameraList") port_list_p = new_gp_object("GPPortInfoList") lib.gp_p...
[ "def", "list_cameras", "(", ")", ":", "ctx", "=", "lib", ".", "gp_context_new", "(", ")", "camlist_p", "=", "new_gp_object", "(", "\"CameraList\"", ")", "port_list_p", "=", "new_gp_object", "(", "\"GPPortInfoList\"", ")", "lib", ".", "gp_port_info_list_load", "(...
41.567568
15.405405
def run(self): """ Blocking method that run the server. """ if self.tasks: logger.info('Registered tasks: %s' % ', '.join(self.tasks)) else: logger.info('No tasks registered') logger.info('Listening on %s ...' % self.bind) self.socket.bind(...
[ "def", "run", "(", "self", ")", ":", "if", "self", ".", "tasks", ":", "logger", ".", "info", "(", "'Registered tasks: %s'", "%", "', '", ".", "join", "(", "self", ".", "tasks", ")", ")", "else", ":", "logger", ".", "info", "(", "'No tasks registered'",...
38.646154
15.569231
def _translate_port(port): ''' Look into services and return the port value using the service name as lookup value. ''' services = _get_services_mapping() if port in services and services[port]['port']: return services[port]['port'][0] return port
[ "def", "_translate_port", "(", "port", ")", ":", "services", "=", "_get_services_mapping", "(", ")", "if", "port", "in", "services", "and", "services", "[", "port", "]", "[", "'port'", "]", ":", "return", "services", "[", "port", "]", "[", "'port'", "]",...
30.555556
15.888889
def _CCompiler_spawn_silent(cmd, dry_run=None): """Spawn a process, and eat the stdio.""" proc = Popen(cmd, stdout=PIPE, stderr=PIPE) out, err = proc.communicate() if proc.returncode: raise DistutilsExecError(err)
[ "def", "_CCompiler_spawn_silent", "(", "cmd", ",", "dry_run", "=", "None", ")", ":", "proc", "=", "Popen", "(", "cmd", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "out", ",", "err", "=", "proc", ".", "communicate", "(", ")", "if", ...
38.666667
6.833333
def _LhD(self): """ Implements Lₕ and D. Returns ------- Lh : ndarray Uₕᵀ S₁⁻½ U₁ᵀ. D : ndarray (Sₕ ⊗ Sₓ + Iₕₓ)⁻¹. """ from numpy_sugar.linalg import ddot self._init_svd() if self._cache["LhD"] is not None: ...
[ "def", "_LhD", "(", "self", ")", ":", "from", "numpy_sugar", ".", "linalg", "import", "ddot", "self", ".", "_init_svd", "(", ")", "if", "self", ".", "_cache", "[", "\"LhD\"", "]", "is", "not", "None", ":", "return", "self", ".", "_cache", "[", "\"LhD...
26.2
14.12
def process_raw_data(cls, raw_data): """Create a new model using raw API response.""" properties = raw_data.get("properties", {}) raw_ip_configuration = properties.get("backendIPConfiguration", []) if isinstance(raw_ip_configuration, dict): raw_ip_configuration = [raw_ip_con...
[ "def", "process_raw_data", "(", "cls", ",", "raw_data", ")", ":", "properties", "=", "raw_data", ".", "get", "(", "\"properties\"", ",", "{", "}", ")", "raw_ip_configuration", "=", "properties", ".", "get", "(", "\"backendIPConfiguration\"", ",", "[", "]", "...
46.947368
23.473684
def qnm_freq_decay(f_0, tau, decay): """Return the frequency at which the amplitude of the ringdown falls to decay of the peak amplitude. Parameters ---------- f_0 : float The ringdown-frequency, which gives the peak amplitude. tau : float The damping time of the sinusoid. d...
[ "def", "qnm_freq_decay", "(", "f_0", ",", "tau", ",", "decay", ")", ":", "q_0", "=", "pi", "*", "f_0", "*", "tau", "alpha", "=", "1.", "/", "decay", "alpha_sq", "=", "1.", "/", "decay", "/", "decay", "# Expression obtained analytically under the assumption",...
29.392857
19.892857
def validate_request_signature( body: str, headers: MutableMapping, signing_secret: str ) -> None: """ Validate incoming request signature using the application signing secret. Contrary to the ``team_id`` and ``verification_token`` verification this method is not called by ``slack-sansio`` when creatin...
[ "def", "validate_request_signature", "(", "body", ":", "str", ",", "headers", ":", "MutableMapping", ",", "signing_secret", ":", "str", ")", "->", "None", ":", "request_timestamp", "=", "int", "(", "headers", "[", "\"X-Slack-Request-Timestamp\"", "]", ")", "if",...
41.428571
31.485714
def consecutivegaps(n, leftmargin = 0, rightmargin = 0): """Compute all possible single consecutive gaps in any sequence of the specified length. Returns (beginindex, length) tuples. Runs in O(n(n+1) / 2) time. Argument is the length of the sequence rather than the sequence itself""" begin = leftmargin ...
[ "def", "consecutivegaps", "(", "n", ",", "leftmargin", "=", "0", ",", "rightmargin", "=", "0", ")", ":", "begin", "=", "leftmargin", "while", "begin", "<", "n", ":", "length", "=", "(", "n", "-", "rightmargin", ")", "-", "begin", "while", "length", "...
47.4
11.7
def bic(self, X): """Bayesian information criterion for the current model fit and the proposed data Parameters ---------- X : array of shape(n_samples, n_dimensions) Returns ------- bic: float (the lower the better) """ return (-2 * self....
[ "def", "bic", "(", "self", ",", "X", ")", ":", "return", "(", "-", "2", "*", "self", ".", "score", "(", "X", ")", ".", "sum", "(", ")", "+", "self", ".", "_n_parameters", "(", ")", "*", "np", ".", "log", "(", "X", ".", "shape", "[", "0", ...
27.285714
17.142857
def create_environment_file(path="~/overcloud-env.json", control_scale=1, compute_scale=1, ceph_storage_scale=0, block_storage_scale=0, swift_storage_scale=0): """Create a heat environment file Create the heat environment file ...
[ "def", "create_environment_file", "(", "path", "=", "\"~/overcloud-env.json\"", ",", "control_scale", "=", "1", ",", "compute_scale", "=", "1", ",", "ceph_storage_scale", "=", "0", ",", "block_storage_scale", "=", "0", ",", "swift_storage_scale", "=", "0", ")", ...
34.5
20.166667
def init_io(self): """Redirect input streams and set a display hook.""" if self.outstream_class: outstream_factory = import_item(str(self.outstream_class)) sys.stdout = outstream_factory(self.session, self.iopub_socket, u'stdout') sys.stderr = outstream_factory(self.s...
[ "def", "init_io", "(", "self", ")", ":", "if", "self", ".", "outstream_class", ":", "outstream_factory", "=", "import_item", "(", "str", "(", "self", ".", "outstream_class", ")", ")", "sys", ".", "stdout", "=", "outstream_factory", "(", "self", ".", "sessi...
60.222222
26
def __search_record(self, task_group_id): """ Search (iterate over) for tasks with the given task id :param task_group_id: target id :return: None """ for i in range(len(self.__records)): record = self.__records[i] if record.task_group_id() == task_group_id: yield record, i
[ "def", "__search_record", "(", "self", ",", "task_group_id", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "__records", ")", ")", ":", "record", "=", "self", ".", "__records", "[", "i", "]", "if", "record", ".", "task_group_id", ...
26
13.909091
def _filtered_data_zeroed(self): """ A 2D `~numpy.nddarray` cutout from the input ``filtered_data`` (or ``data`` if ``filtered_data`` is `None`) where any masked pixels (_segment_mask, _input_mask, or _data_mask) are set to zero. Invalid values (e.g. NaNs or infs) are set to zer...
[ "def", "_filtered_data_zeroed", "(", "self", ")", ":", "filt_data", "=", "self", ".", "_filtered_data", "[", "self", ".", "_slice", "]", "filt_data", "=", "np", ".", "where", "(", "self", ".", "_total_mask", ",", "0.", ",", "filt_data", ")", "# copy", "f...
45.764706
19.882353