text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def transform(self, X): """Transform X into the existing embedded space and return that transformed output. Parameters ---------- X : array, shape (n_samples, n_features) New data to be transformed. Returns ------- X_new : array, shape (n_sam...
[ "def", "transform", "(", "self", ",", "X", ")", ":", "# If we fit just a single instance then error", "if", "self", ".", "embedding_", ".", "shape", "[", "0", "]", "==", "1", ":", "raise", "ValueError", "(", "'Transform unavailable when model was fit with'", "'only ...
36.338843
0.001107
def _post_response(self, params): """ wrap a post call to the requests package """ return self._session.post( self._api_url, data=params, timeout=self._timeout ).json(encoding="utf8")
[ "def", "_post_response", "(", "self", ",", "params", ")", ":", "return", "self", ".", "_session", ".", "post", "(", "self", ".", "_api_url", ",", "data", "=", "params", ",", "timeout", "=", "self", ".", "_timeout", ")", ".", "json", "(", "encoding", ...
43
0.009132
def to_json(self): """ Returns the options as JSON. :return: the object as string :rtype: str """ return json.dumps(self.to_dict(), sort_keys=True, indent=2, separators=(',', ': '))
[ "def", "to_json", "(", "self", ")", ":", "return", "json", ".", "dumps", "(", "self", ".", "to_dict", "(", ")", ",", "sort_keys", "=", "True", ",", "indent", "=", "2", ",", "separators", "=", "(", "','", ",", "': '", ")", ")" ]
27.875
0.013043
def add_to_manifest(self, manifest): """ Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry...
[ "def", "add_to_manifest", "(", "self", ",", "manifest", ")", ":", "# Add this service to list of services", "manifest", ".", "add_service", "(", "self", ".", "service", ".", "name", ")", "# Add environment variables", "uri", "=", "predix", ".", "config", ".", "get...
39.153846
0.001918
def one_step(self, current_state, previous_kernel_results): """Runs one iteration of NeuTra. Args: current_state: `Tensor` or Python `list` of `Tensor`s representing the current state(s) of the Markov chain(s). The first `r` dimensions index independent chains, `r = tf.rank(target_log_pro...
[ "def", "one_step", "(", "self", ",", "current_state", ",", "previous_kernel_results", ")", ":", "@", "tfp", ".", "mcmc", ".", "internal", ".", "util", ".", "make_innermost_setter", "def", "set_num_leapfrog_steps", "(", "kernel_results", ",", "num_leapfrog_steps", ...
46
0.001331
def run(self): """ Drain the process output streams. """ read_stdout = partial(self._read_output, stream=self._process.stdout, callback=self._callback_stdout, output_file=self._stdout_file) read_stderr = partial(self._read_output, stre...
[ "def", "run", "(", "self", ")", ":", "read_stdout", "=", "partial", "(", "self", ".", "_read_output", ",", "stream", "=", "self", ".", "_process", ".", "stdout", ",", "callback", "=", "self", ".", "_callback_stdout", ",", "output_file", "=", "self", ".",...
35.642857
0.001951
def load_auth(configfile): """Get authentication data from the AUTH_CONF file.""" logging.debug('Loading habitica auth data from %s' % configfile) try: cf = open(configfile) except IOError: logging.error("Unable to find '%s'." % configfile) exit(1) config = configparser.Sa...
[ "def", "load_auth", "(", "configfile", ")", ":", "logging", ".", "debug", "(", "'Loading habitica auth data from %s'", "%", "configfile", ")", "try", ":", "cf", "=", "open", "(", "configfile", ")", "except", "IOError", ":", "logging", ".", "error", "(", "\"U...
28.657143
0.000964
def node_hist_fig( node_color_distribution, title="Graph Node Distribution", width=400, height=300, top=60, left=25, bottom=60, right=25, bgcolor="rgb(240,240,240)", y_gridcolor="white", ): """Define the plotly plot representing the node histogram Param...
[ "def", "node_hist_fig", "(", "node_color_distribution", ",", "title", "=", "\"Graph Node Distribution\"", ",", "width", "=", "400", ",", "height", "=", "300", ",", "top", "=", "60", ",", "left", "=", "25", ",", "bottom", "=", "60", ",", "right", "=", "25...
30.358491
0.002408
def _get_changes(self): '''Get all changed values.''' result = dict( (f['id'], f.get('value','')) for f in self._data if f.get('changed', False) ) self._clear_changes return result
[ "def", "_get_changes", "(", "self", ")", ":", "result", "=", "dict", "(", "(", "f", "[", "'id'", "]", ",", "f", ".", "get", "(", "'value'", ",", "''", ")", ")", "for", "f", "in", "self", ".", "_data", "if", "f", ".", "get", "(", "'changed'", ...
41.6
0.028302
def main(): '''The main function. Instantiates a GameState object and then enters a REPL-like main loop, waiting for input, updating the state based on the input, then outputting the new state.''' state = GameState() print(state) while state.running: input = get_single_char() s...
[ "def", "main", "(", ")", ":", "state", "=", "GameState", "(", ")", "print", "(", "state", ")", "while", "state", ".", "running", ":", "input", "=", "get_single_char", "(", ")", "state", ",", "should_advance", "=", "state", ".", "handle_input", "(", "in...
28.444444
0.00189
def _unlock(self): ''' Unlocks the index ''' if self._devel: self.logger.debug("Unlocking Index") if self._is_locked(): os.remove(self._lck) return True else: return True
[ "def", "_unlock", "(", "self", ")", ":", "if", "self", ".", "_devel", ":", "self", ".", "logger", ".", "debug", "(", "\"Unlocking Index\"", ")", "if", "self", ".", "_is_locked", "(", ")", ":", "os", ".", "remove", "(", "self", ".", "_lck", ")", "re...
24.5
0.011811
def create_integration_alert_and_call_send(alert, configured_integration): """Create an IntegrationAlert object and send it to Integration.""" integration_alert = IntegrationAlert( alert=alert, configured_integration=configured_integration, status=IntegrationAlertStatuses.PENDING.name, ...
[ "def", "create_integration_alert_and_call_send", "(", "alert", ",", "configured_integration", ")", ":", "integration_alert", "=", "IntegrationAlert", "(", "alert", "=", "alert", ",", "configured_integration", "=", "configured_integration", ",", "status", "=", "Integration...
44.4
0.002208
def object_merge(old, new, unique=False): """ Recursively merge two data structures. :param unique: When set to True existing list items are not set. """ if isinstance(old, list) and isinstance(new, list): if old == new: return for item in old[::-1]: if uniqu...
[ "def", "object_merge", "(", "old", ",", "new", ",", "unique", "=", "False", ")", ":", "if", "isinstance", "(", "old", ",", "list", ")", "and", "isinstance", "(", "new", ",", "list", ")", ":", "if", "old", "==", "new", ":", "return", "for", "item", ...
31.578947
0.001618
def write_relative_abundance(rel_abd, biomf, out_fn, sort_by=None): """ Given a BIOM table, calculate per-sample relative abundance for each OTU and write out to a tab-separated file listing OTUs as rows and Samples as columns. :type biom: biom object :param biom: BIOM-formatted OTU/Sample abund...
[ "def", "write_relative_abundance", "(", "rel_abd", ",", "biomf", ",", "out_fn", ",", "sort_by", "=", "None", ")", ":", "with", "open", "(", "out_fn", ",", "'w'", ")", "as", "out_f", ":", "sids", "=", "sorted", "(", "set", "(", "biomf", ".", "ids", "(...
46.4
0.000845
def create_analysisrequest(client, request, values, analyses=None, partitions=None, specifications=None, prices=None): """This is meant for general use and should do everything necessary to create and initialise an AR and any other required auxilliary objects (Sample, SamplePartit...
[ "def", "create_analysisrequest", "(", "client", ",", "request", ",", "values", ",", "analyses", "=", "None", ",", "partitions", "=", "None", ",", "specifications", "=", "None", ",", "prices", "=", "None", ")", ":", "# Don't pollute the dict param passed in", "va...
41.608108
0.000635
def _get_params(self): """ Generate SOAP parameters. """ params = {'accountNumber': self._service.accountNumber} # Include object variables that are in field_order for key, val in self.__dict__.iteritems(): if key in self.field_order: ...
[ "def", "_get_params", "(", "self", ")", ":", "params", "=", "{", "'accountNumber'", ":", "self", ".", "_service", ".", "accountNumber", "}", "# Include object variables that are in field_order", "for", "key", ",", "val", "in", "self", ".", "__dict__", ".", "iter...
31.666667
0.009362
def submitQuest(self): """ Submits the active quest, returns result Returns bool - True if successful, otherwise False """ form = pg.form(action="kitchen2.phtml") pg = form.submit() if "Woohoo" in pg.content: try: ...
[ "def", "submitQuest", "(", "self", ")", ":", "form", "=", "pg", ".", "form", "(", "action", "=", "\"kitchen2.phtml\"", ")", "pg", "=", "form", ".", "submit", "(", ")", "if", "\"Woohoo\"", "in", "pg", ".", "content", ":", "try", ":", "self", ".", "p...
37.857143
0.013497
def register_lookup(self, lookup): """Register lookup.""" if lookup.operator in self._lookups: raise KeyError("Lookup for operator '{}' is already registered".format(lookup.operator)) self._lookups[lookup.operator] = lookup()
[ "def", "register_lookup", "(", "self", ",", "lookup", ")", ":", "if", "lookup", ".", "operator", "in", "self", ".", "_lookups", ":", "raise", "KeyError", "(", "\"Lookup for operator '{}' is already registered\"", ".", "format", "(", "lookup", ".", "operator", ")...
42.833333
0.01145
def _morph(self): """Turn a file system node into a File object.""" self.scanner_paths = {} if not hasattr(self, '_local'): self._local = 0 if not hasattr(self, 'released_target_info'): self.released_target_info = False self.store_info = 1 self._f...
[ "def", "_morph", "(", "self", ")", ":", "self", ".", "scanner_paths", "=", "{", "}", "if", "not", "hasattr", "(", "self", ",", "'_local'", ")", ":", "self", ".", "_local", "=", "0", "if", "not", "hasattr", "(", "self", ",", "'released_target_info'", ...
45.535714
0.001536
def make_repo(repodir, keyid=None, env=None, use_passphrase=False, gnupghome='/etc/salt/gpgkeys', runas='root', timeout=15.0): ''' Make a package repository and optionally sign packages present Given the repodir, create a `...
[ "def", "make_repo", "(", "repodir", ",", "keyid", "=", "None", ",", "env", "=", "None", ",", "use_passphrase", "=", "False", ",", "gnupghome", "=", "'/etc/salt/gpgkeys'", ",", "runas", "=", "'root'", ",", "timeout", "=", "15.0", ")", ":", "SIGN_PROMPT_RE",...
36.347032
0.001223
def convert_text(text, input_format='markdown', output_format='panflute', standalone=False, extra_args=None): """ Convert formatted text (usually markdown) by calling Pandoc internally The default output format ('panflute') will return a t...
[ "def", "convert_text", "(", "text", ",", "input_format", "=", "'markdown'", ",", "output_format", "=", "'panflute'", ",", "standalone", "=", "False", ",", "extra_args", "=", "None", ")", ":", "if", "input_format", "==", "'panflute'", ":", "# Problem:", "# We ...
37.443182
0.001774
def _handle_response(response, server_config, synchronous=False, timeout=None): """Handle a server's response in a typical fashion. Do the following: 1. Check the server's response for an HTTP status code indicating an error. 2. Poll the server for a foreman task to complete if an HTTP 202 (accepted) ...
[ "def", "_handle_response", "(", "response", ",", "server_config", ",", "synchronous", "=", "False", ",", "timeout", "=", "None", ")", ":", "response", ".", "raise_for_status", "(", ")", "if", "synchronous", "is", "True", "and", "response", ".", "status_code", ...
46.212121
0.000642
def _generate_noise_system(dimensions_tr, spatial_sd, temporal_sd, spatial_noise_type='gaussian', temporal_noise_type='gaussian', ): """Generate the scanner noise Generate syst...
[ "def", "_generate_noise_system", "(", "dimensions_tr", ",", "spatial_sd", ",", "temporal_sd", ",", "spatial_noise_type", "=", "'gaussian'", ",", "temporal_noise_type", "=", "'gaussian'", ",", ")", ":", "def", "noise_volume", "(", "dimensions", ",", "noise_type", ","...
39.393617
0.000263
def _getDataBatch(self, inputData): """ Returns an array of dimensions (filterDim, batchSize), to be used as batch for training data. This implementation uses random sub-patches as training batch. Images are flattened to get a 2-dimensional batch. """ if not hasattr(self, 'numImages'): ...
[ "def", "_getDataBatch", "(", "self", ",", "inputData", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'numImages'", ")", ":", "self", ".", "_initializeDimensions", "(", "inputData", ")", "batch", "=", "np", ".", "zeros", "(", "(", "self", ".", "f...
33.196078
0.012048
def get_chunk_meta(self, meta_file): """Get chunk meta table""" chunks = self.envs["CHUNKS"] if cij.nvme.get_meta(0, chunks * self.envs["CHUNK_META_SIZEOF"], meta_file): raise RuntimeError("cij.liblight.get_chunk_meta: fail") chunk_meta = cij.bin.Buffer(types=self.envs["CHUN...
[ "def", "get_chunk_meta", "(", "self", ",", "meta_file", ")", ":", "chunks", "=", "self", ".", "envs", "[", "\"CHUNKS\"", "]", "if", "cij", ".", "nvme", ".", "get_meta", "(", "0", ",", "chunks", "*", "self", ".", "envs", "[", "\"CHUNK_META_SIZEOF\"", "]...
44.888889
0.009709
def is_supported(value, check_all=False, filters=None, iterate=False): """Return True if the value is supported, False otherwise""" assert filters is not None if value is None: return True if not is_editable_type(value): return False elif not isinstance(value, filters): retur...
[ "def", "is_supported", "(", "value", ",", "check_all", "=", "False", ",", "filters", "=", "None", ",", "iterate", "=", "False", ")", ":", "assert", "filters", "is", "not", "None", "if", "value", "is", "None", ":", "return", "True", "if", "not", "is_edi...
38.074074
0.000949
def _read(self, ti, try_number, metadata=None): """ Endpoint for streaming log. :param ti: task instance object :param try_number: try_number of the task instance :param metadata: log metadata, can be used for steaming log reading and auto-tailing. ...
[ "def", "_read", "(", "self", ",", "ti", ",", "try_number", ",", "metadata", "=", "None", ")", ":", "if", "not", "metadata", ":", "metadata", "=", "{", "'offset'", ":", "0", "}", "if", "'offset'", "not", "in", "metadata", ":", "metadata", "[", "'offse...
39.5
0.001176
def harmonics_2d(harmonic_out, x, freqs, h_range, kind='linear', fill_value=0, axis=0): '''Populate a harmonic tensor from a time-frequency representation with time-varying frequencies. Parameters ---------- harmonic_out : np.ndarray The output array to store harmonics ...
[ "def", "harmonics_2d", "(", "harmonic_out", ",", "x", ",", "freqs", ",", "h_range", ",", "kind", "=", "'linear'", ",", "fill_value", "=", "0", ",", "axis", "=", "0", ")", ":", "idx_in", "=", "[", "slice", "(", "None", ")", "]", "*", "x", ".", "nd...
29.942308
0.001244
def anonymous_required(view, redirect_to=None): """ Only allow if user is NOT authenticated. """ if redirect_to is None: redirect_to = settings.LOGIN_REDIRECT_URL @wraps(view) def wrapper(request, *a, **k): if request.user and request.user.is_authenticated(): return ...
[ "def", "anonymous_required", "(", "view", ",", "redirect_to", "=", "None", ")", ":", "if", "redirect_to", "is", "None", ":", "redirect_to", "=", "settings", ".", "LOGIN_REDIRECT_URL", "@", "wraps", "(", "view", ")", "def", "wrapper", "(", "request", ",", "...
30.615385
0.002439
def format_terminal_row(headers, example_row): """Uses headers and a row of example data to generate a format string for printing a single row of data. Args: headers (tuple of strings): The headers for each column of data example_row (tuple): A representative tuple of strings or ints R...
[ "def", "format_terminal_row", "(", "headers", ",", "example_row", ")", ":", "def", "format_column", "(", "col", ")", ":", "if", "isinstance", "(", "col", ",", "str", ")", ":", "return", "'{{:{w}.{w}}}'", "return", "'{{:<{w}}}'", "widths", "=", "[", "max", ...
32.852941
0.00087
def set_lock(i): """ Input: { path - path to be locked (get_lock) - if 'yes', lock this entry (lock_retries) - number of retries to aquire lock (default=11) (lock_retry_delay) - delay in seconds before trying to aquire lock agai...
[ "def", "set_lock", "(", "i", ")", ":", "p", "=", "i", "[", "'path'", "]", "gl", "=", "i", ".", "get", "(", "'get_lock'", ",", "''", ")", "uuid", "=", "i", ".", "get", "(", "'unlock_uid'", ",", "''", ")", "exp", "=", "float", "(", "i", ".", ...
30.5625
0.037636
def _get_object(data, position, obj_end, opts, dummy): """Decode a BSON subdocument to opts.document_class or bson.dbref.DBRef.""" obj_size, end = _get_object_size(data, position, obj_end) if _raw_document_class(opts.document_class): return (opts.document_class(data[position:end + 1], opts), ...
[ "def", "_get_object", "(", "data", ",", "position", ",", "obj_end", ",", "opts", ",", "dummy", ")", ":", "obj_size", ",", "end", "=", "_get_object_size", "(", "data", ",", "position", ",", "obj_end", ")", "if", "_raw_document_class", "(", "opts", ".", "d...
42.142857
0.001658
def upload(resume, message): """ Upload files in the current dir to FloydHub. """ data_config = DataConfigManager.get_config() if not upload_is_resumable(data_config) or not opt_to_resume(resume): abort_previous_upload(data_config) access_token = AuthConfigManager.get_access_token()...
[ "def", "upload", "(", "resume", ",", "message", ")", ":", "data_config", "=", "DataConfigManager", ".", "get_config", "(", ")", "if", "not", "upload_is_resumable", "(", "data_config", ")", "or", "not", "opt_to_resume", "(", "resume", ")", ":", "abort_previous_...
34.083333
0.002381
def _validate_attrs(dataset): """`attrs` must have a string key and a value which is either: a number, a string, an ndarray or a list/tuple of numbers/strings. """ def check_attr(name, value): if isinstance(name, str): if not name: raise ValueError('Invalid name for a...
[ "def", "_validate_attrs", "(", "dataset", ")", ":", "def", "check_attr", "(", "name", ",", "value", ")", ":", "if", "isinstance", "(", "name", ",", "str", ")", ":", "if", "not", "name", ":", "raise", "ValueError", "(", "'Invalid name for attr: string must be...
44.103448
0.000765
def replace_refs(cls, obj, _recursive=False, **kwargs): """ Returns a deep copy of `obj` with all contained JSON reference objects replaced with :class:`JsonRef` instances. :param obj: If this is a JSON reference object, a :class:`JsonRef` instance will be created. If `obj` ...
[ "def", "replace_refs", "(", "cls", ",", "obj", ",", "_recursive", "=", "False", ",", "*", "*", "kwargs", ")", ":", "store", "=", "kwargs", ".", "setdefault", "(", "\"_store\"", ",", "_URIDict", "(", ")", ")", "base_uri", ",", "frag", "=", "urlparse", ...
43.360656
0.000739
def ensure_all_columns_are_used(num_vars_accounted_for, dataframe, data_title='long_data'): """ Ensure that all of the columns from dataframe are in the list of used_cols. Will raise a helpful UserWarning if otherwise. Parameters -----...
[ "def", "ensure_all_columns_are_used", "(", "num_vars_accounted_for", ",", "dataframe", ",", "data_title", "=", "'long_data'", ")", ":", "dataframe_vars", "=", "set", "(", "dataframe", ".", "columns", ".", "tolist", "(", ")", ")", "num_dataframe_vars", "=", "len", ...
37.318182
0.000593
def __add_callback(self, type_, func, serialised_if_crud=True): """sync_if_crud indicates whether to serialise this callback (applies only to CRUD)""" Validation.callable_check(func) with self.__callbacks: self.__callbacks[type_].append((func, serialised_if_crud))
[ "def", "__add_callback", "(", "self", ",", "type_", ",", "func", ",", "serialised_if_crud", "=", "True", ")", ":", "Validation", ".", "callable_check", "(", "func", ")", "with", "self", ".", "__callbacks", ":", "self", ".", "__callbacks", "[", "type_", "]"...
59.2
0.01
def mavlink_packet(self, m): '''handle and incoming mavlink packet''' if m.get_type() == "FENCE_STATUS": self.last_fence_breach = m.breach_time self.last_fence_status = m.breach_status elif m.get_type() in ['SYS_STATUS']: bits = mavutil.mavlink.MAV_SYS_STATUS_...
[ "def", "mavlink_packet", "(", "self", ",", "m", ")", ":", "if", "m", ".", "get_type", "(", ")", "==", "\"FENCE_STATUS\"", ":", "self", ".", "last_fence_breach", "=", "m", ".", "breach_time", "self", ".", "last_fence_status", "=", "m", ".", "breach_status",...
46.394737
0.011111
def _initActions(self): """Init shortcuts for text editing """ def createAction(text, shortcut, slot, iconFileName=None): """Create QAction with given parameters and add to the widget """ action = QAction(text, self) if iconFileName is not None: ...
[ "def", "_initActions", "(", "self", ")", ":", "def", "createAction", "(", "text", ",", "shortcut", ",", "slot", ",", "iconFileName", "=", "None", ")", ":", "\"\"\"Create QAction with given parameters and add to the widget\n \"\"\"", "action", "=", "QAction", ...
60.970149
0.011563
def update(self, u): ''' Works like dict.update(dict) but handles nested dicts. From http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth. ''' for k, v in u.iteritems(): if isinstance(v, collections.Mapping): r = ...
[ "def", "update", "(", "self", ",", "u", ")", ":", "for", "k", ",", "v", "in", "u", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "v", ",", "collections", ".", "Mapping", ")", ":", "r", "=", "nested_dict", ".", "from_dict", "(", "self"...
42.615385
0.008834
def _maintain_dep_graph(self, p_todo): """ Makes sure that the dependency graph is consistent according to the given todo. """ dep_id = p_todo.tag_value('id') # maintain dependency graph if dep_id: self._parentdict[dep_id] = p_todo self._de...
[ "def", "_maintain_dep_graph", "(", "self", ",", "p_todo", ")", ":", "dep_id", "=", "p_todo", ".", "tag_value", "(", "'id'", ")", "# maintain dependency graph", "if", "dep_id", ":", "self", ".", "_parentdict", "[", "dep_id", "]", "=", "p_todo", "self", ".", ...
33.208333
0.002439
def make_data(n,m): """make_data: prepare matrix of m times n random processing times""" p = {} for i in range(1,m+1): for j in range(1,n+1): p[i,j] = random.randint(1,10) return p
[ "def", "make_data", "(", "n", ",", "m", ")", ":", "p", "=", "{", "}", "for", "i", "in", "range", "(", "1", ",", "m", "+", "1", ")", ":", "for", "j", "in", "range", "(", "1", ",", "n", "+", "1", ")", ":", "p", "[", "i", ",", "j", "]", ...
30
0.027778
def crawl_legend(self, ax, legend): """ Recursively look through objects in legend children """ legendElements = list(utils.iter_all_children(legend._legend_box, skipContainers=True)) legendElements.append(legend.legendPatch) ...
[ "def", "crawl_legend", "(", "self", ",", "ax", ",", "legend", ")", ":", "legendElements", "=", "list", "(", "utils", ".", "iter_all_children", "(", "legend", ".", "_legend_box", ",", "skipContainers", "=", "True", ")", ")", "legendElements", ".", "append", ...
51.678571
0.001357
def plot_job_history(jobs, interval='year'): """Plots the job history of the user from the given list of jobs. Args: jobs (list): A list of jobs with type IBMQjob. interval (str): Interval over which to examine. Returns: fig: A Matplotlib figure instance. """ def get_date(j...
[ "def", "plot_job_history", "(", "jobs", ",", "interval", "=", "'year'", ")", ":", "def", "get_date", "(", "job", ")", ":", "\"\"\"Returns a datetime object from a IBMQJob instance.\n\n Args:\n job (IBMQJob): A job.\n\n Returns:\n dt: A datetime obj...
32.506494
0.001551
def _get_ln_y_ref(self, rup, dists, C): """ Get an intensity on a reference soil. Implements eq. 13a. """ # reverse faulting flag Frv = 1. if 30 <= rup.rake <= 150 else 0. # normal faulting flag Fnm = 1. if -120 <= rup.rake <= -60 else 0. # hangin...
[ "def", "_get_ln_y_ref", "(", "self", ",", "rup", ",", "dists", ",", "C", ")", ":", "# reverse faulting flag", "Frv", "=", "1.", "if", "30", "<=", "rup", ".", "rake", "<=", "150", "else", "0.", "# normal faulting flag", "Fnm", "=", "1.", "if", "-", "120...
36.622951
0.000872
def delete_role(role_id,**kwargs): """ Delete a role """ #check_perm(kwargs.get('user_id'), 'edit_role') try: role_i = db.DBSession.query(Role).filter(Role.id==role_id).one() db.DBSession.delete(role_i) except InvalidRequestError: raise ResourceNotFoundError("Role (ro...
[ "def", "delete_role", "(", "role_id", ",", "*", "*", "kwargs", ")", ":", "#check_perm(kwargs.get('user_id'), 'edit_role')", "try", ":", "role_i", "=", "db", ".", "DBSession", ".", "query", "(", "Role", ")", ".", "filter", "(", "Role", ".", "id", "==", "rol...
30.166667
0.016086
def getActiveProperties(self): """ Returns the non-zero accidental dignities. """ score = self.getScoreProperties() return {key: value for (key, value) in score.items() if value != 0}
[ "def", "getActiveProperties", "(", "self", ")", ":", "score", "=", "self", ".", "getScoreProperties", "(", ")", "return", "{", "key", ":", "value", "for", "(", "key", ",", "value", ")", "in", "score", ".", "items", "(", ")", "if", "value", "!=", "0",...
43.8
0.008969
def erase_in_display(self, how=0, *args, **kwargs): """Erases display in a specific way. Character attributes are set to cursor attributes. :param int how: defines the way the line should be erased in: * ``0`` -- Erases from cursor to end of screen, including cursor ...
[ "def", "erase_in_display", "(", "self", ",", "how", "=", "0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "how", "==", "0", ":", "interval", "=", "range", "(", "self", ".", "cursor", ".", "y", "+", "1", ",", "self", ".", "lines",...
37.578947
0.001365
def norms(df, col_names = None,row_names = None,style = 'mean', as_group = False, axis = 0): """ Returns a normalized version of the input Dataframe Parameters: df - pandas DataFrame The input data to normalize col_names - list or string, default None The column(s) to use when computing ...
[ "def", "norms", "(", "df", ",", "col_names", "=", "None", ",", "row_names", "=", "None", ",", "style", "=", "'mean'", ",", "as_group", "=", "False", ",", "axis", "=", "0", ")", ":", "if", "col_names", "is", "None", ":", "if", "row_names", "is", "no...
46.583333
0.018692
def conv_act_layer(from_layer, name, num_filter, kernel=(1,1), pad=(0,0), \ stride=(1,1), act_type="relu", use_batchnorm=False): """ wrapper for a small Convolution group Parameters: ---------- from_layer : mx.symbol continue on which layer name : str base name of the new la...
[ "def", "conv_act_layer", "(", "from_layer", ",", "name", ",", "num_filter", ",", "kernel", "=", "(", "1", ",", "1", ")", ",", "pad", "=", "(", "0", ",", "0", ")", ",", "stride", "=", "(", "1", ",", "1", ")", ",", "act_type", "=", "\"relu\"", ",...
31.314286
0.009735
def select_segments_by_definer(segment_file, segment_name=None, ifo=None): """ Return the list of segments that match the segment name Parameters ---------- segment_file: str path to segment xml file segment_name: str Name of segment ifo: str, optional Returns ------- ...
[ "def", "select_segments_by_definer", "(", "segment_file", ",", "segment_name", "=", "None", ",", "ifo", "=", "None", ")", ":", "from", "glue", ".", "ligolw", ".", "ligolw", "import", "LIGOLWContentHandler", "as", "h", "lsctables", ".", "use_in", "(", "h", ")...
35.244444
0.002454
def insert_surface(self, position, name, surface, alpha=1.): ''' Insert Cairo surface as new layer. Args ---- position (int) : Index position to insert layer at. name (str) : Name of layer. surface (cairo.Context) : Surface to render. al...
[ "def", "insert_surface", "(", "self", ",", "position", ",", "name", ",", "surface", ",", "alpha", "=", "1.", ")", ":", "if", "name", "in", "self", ".", "df_surfaces", ".", "index", ":", "raise", "NameError", "(", "'Surface already exists with `name=\"{}\"`.'",...
39.333333
0.001838
def delta(self, signature): "Generates delta for remote file via API using local file's signature." return self.api.post('path/sync/delta', self.path, signature=signature)
[ "def", "delta", "(", "self", ",", "signature", ")", ":", "return", "self", ".", "api", ".", "post", "(", "'path/sync/delta'", ",", "self", ".", "path", ",", "signature", "=", "signature", ")" ]
61.666667
0.010695
def _subdivide_nodes(nodes, degree): """Subdivide a surface into four sub-surfaces. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Does so by taking the unit triangle (i.e. the domain of the surface) and splitting it into four s...
[ "def", "_subdivide_nodes", "(", "nodes", ",", "degree", ")", ":", "if", "degree", "==", "1", ":", "nodes_a", "=", "_helpers", ".", "matrix_product", "(", "nodes", ",", "LINEAR_SUBDIVIDE_A", ")", "nodes_b", "=", "_helpers", ".", "matrix_product", "(", "nodes"...
36.771429
0.000378
def monkeypatch_es(): """Monkey patch for elasticsearch-py 1.0+ to make it work with ES 0.90 1. tweaks elasticsearch.client.bulk to normalize return status codes .. Note:: We can nix this whe we drop support for ES 0.90. """ if _monkeypatched_es: return def normalize_bulk_ret...
[ "def", "monkeypatch_es", "(", ")", ":", "if", "_monkeypatched_es", ":", "return", "def", "normalize_bulk_return", "(", "fun", ")", ":", "\"\"\"Set's \"ok\" based on \"status\" if \"status\" exists\"\"\"", "@", "wraps", "(", "fun", ")", "def", "_fixed_bulk", "(", "self...
31.71875
0.000956
def rget(self, key, replica_index=None, quiet=None): """Get an item from a replica node :param string key: The key to fetch :param int replica_index: The replica index to fetch. If this is ``None`` then this method will return once any replica responds. Use :attr:`config...
[ "def", "rget", "(", "self", ",", "key", ",", "replica_index", "=", "None", ",", "quiet", "=", "None", ")", ":", "if", "replica_index", "is", "not", "None", ":", "return", "_Base", ".", "_rgetix", "(", "self", ",", "key", ",", "replica", "=", "replica...
40.538462
0.001854
def normalize_request_headers(request): r"""Function used to transform header, replacing 'HTTP\_' to '' and replace '_' to '-' :param request: A HttpRequest that will be transformed :returns: A dictionary with the normalized headers """ norm_headers = {} for header, value in request...
[ "def", "normalize_request_headers", "(", "request", ")", ":", "norm_headers", "=", "{", "}", "for", "header", ",", "value", "in", "request", ".", "META", ".", "items", "(", ")", ":", "if", "required_header", "(", "header", ")", ":", "norm_header", "=", "...
36.285714
0.001919
def padding(value): """int or dict : Padding around visualization The padding defines the distance between the edge of the visualization canvas to the visualization box. It does not count as part of the visualization width/height. Values cannot be negative. If a dict, padding m...
[ "def", "padding", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "required_keys", "=", "[", "'top'", ",", "'left'", ",", "'right'", ",", "'bottom'", "]", "for", "key", "in", "required_keys", ":", "if", "key", "not", ...
45.730769
0.001647
def mget(self, *keys): """ -> #list of values at the specified @keys """ keys = list(map(self.get_key, keys)) return list(map(self._loads, self._client.mget(*keys)))
[ "def", "mget", "(", "self", ",", "*", "keys", ")", ":", "keys", "=", "list", "(", "map", "(", "self", ".", "get_key", ",", "keys", ")", ")", "return", "list", "(", "map", "(", "self", ".", "_loads", ",", "self", ".", "_client", ".", "mget", "("...
46.5
0.010582
def implementation_std(vals_std, vals_std_u, bs_std, bs_std_u, **kwargs): r"""Estimates varaition of results due to implementation-specific effects. See 'nestcheck: diagnostic tests for nested sampling calculations' (Higson et al. 2019) for more details. Uncertainties on the output are calculated numer...
[ "def", "implementation_std", "(", "vals_std", ",", "vals_std_u", ",", "bs_std", ",", "bs_std_u", ",", "*", "*", "kwargs", ")", ":", "nsim", "=", "kwargs", ".", "pop", "(", "'nsim'", ",", "1000000", ")", "random_seed", "=", "kwargs", ".", "pop", "(", "'...
43.606061
0.00034
def getAttributeNames(self): '''returns a list of anames representing the parts of the message. ''' return map(lambda e: self.getAttributeName(e.name), self.tcListElements)
[ "def", "getAttributeNames", "(", "self", ")", ":", "return", "map", "(", "lambda", "e", ":", "self", ".", "getAttributeName", "(", "e", ".", "name", ")", ",", "self", ".", "tcListElements", ")" ]
40
0.014706
def _get_flags(osm_obj): """Create element independent flags output. Args: osm_obj (Node): Object with OSM-style metadata Returns: list: Human readable flags output """ flags = [] if osm_obj.visible: flags.append('visible') if osm_obj.user: flags.append('use...
[ "def", "_get_flags", "(", "osm_obj", ")", ":", "flags", "=", "[", "]", "if", "osm_obj", ".", "visible", ":", "flags", ".", "append", "(", "'visible'", ")", "if", "osm_obj", ".", "user", ":", "flags", ".", "append", "(", "'user: %s'", "%", "osm_obj", ...
29
0.001669
def reinitialize_command(self, command, reinit_subcommands): """ Monkeypatch distutils.Distribution.reinitialize_command() to match behavior of Distribution.get_command_obj() This fixes a problem where 'pip install -e' does not reinitialise options using the setup(options={...}) variable for the bui...
[ "def", "reinitialize_command", "(", "self", ",", "command", ",", "reinit_subcommands", ")", ":", "cmd_obj", "=", "_DISTUTILS_REINIT", "(", "self", ",", "command", ",", "reinit_subcommands", ")", "options", "=", "self", ".", "command_options", ".", "get", "(", ...
37.125
0.001642
def _startSchedulesNode(self, name, attrs): """Process the start of a node under xtvd/schedules""" if name == 'schedule': self._programId = attrs.get('program') self._stationId = attrs.get('station') self._time = self._parseDateTime(attrs.get('time')) sel...
[ "def", "_startSchedulesNode", "(", "self", ",", "name", ",", "attrs", ")", ":", "if", "name", "==", "'schedule'", ":", "self", ".", "_programId", "=", "attrs", ".", "get", "(", "'program'", ")", "self", ".", "_stationId", "=", "attrs", ".", "get", "(",...
45.809524
0.008147
def path2fsn(path): """ Args: path (pathlike): The path to convert Returns: `fsnative` Raises: TypeError: In case the type can't be converted to a `fsnative` ValueError: In case conversion fails Returns a `fsnative` path for a `pathlike`. """ # allow mbcs st...
[ "def", "path2fsn", "(", "path", ")", ":", "# allow mbcs str on py2+win and bytes on py3", "if", "PY2", ":", "if", "is_win", ":", "if", "isinstance", "(", "path", ",", "bytes", ")", ":", "path", "=", "path", ".", "decode", "(", "_encoding", ")", "else", ":"...
31.888889
0.000676
def send_reset_password_instructions(user): """Sends the reset password instructions email for the specified user. :param user: The user to send the instructions to """ token = generate_reset_password_token(user) reset_link = url_for_security( 'reset_password', token=token, _external=True ...
[ "def", "send_reset_password_instructions", "(", "user", ")", ":", "token", "=", "generate_reset_password_token", "(", "user", ")", "reset_link", "=", "url_for_security", "(", "'reset_password'", ",", "token", "=", "token", ",", "_external", "=", "True", ")", "if",...
36.888889
0.001468
def construct(key_data, algorithm=None): """ Construct a Key object for the given algorithm with the given key_data. """ # Allow for pulling the algorithm off of the passed in jwk. if not algorithm and isinstance(key_data, dict): algorithm = key_data.get('alg', None) if not algorit...
[ "def", "construct", "(", "key_data", ",", "algorithm", "=", "None", ")", ":", "# Allow for pulling the algorithm off of the passed in jwk.", "if", "not", "algorithm", "and", "isinstance", "(", "key_data", ",", "dict", ")", ":", "algorithm", "=", "key_data", ".", "...
32.882353
0.001739
async def create(cls, host, *args, **kwargs): """Asynchronously create a :class:`Proxy` object. :param str host: A passed host can be a domain or IP address. If the host is a domain, try to resolve it :param str \*args: (optional) Positional arguments that :...
[ "async", "def", "create", "(", "cls", ",", "host", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# noqa: W605", "loop", "=", "kwargs", ".", "pop", "(", "'loop'", ",", "None", ")", "resolver", "=", "kwargs", ".", "pop", "(", "'resolver'", ",...
39.8
0.001963
def createSegment(self, cell): """ Create a :class:`~nupic.algorithms.connections.Segment` on the specified cell. This method calls :meth:`~nupic.algorithms.connections.Connections.createSegment` on the underlying :class:`~nupic.algorithms.connections.Connections`, and it does some extra boo...
[ "def", "createSegment", "(", "self", ",", "cell", ")", ":", "return", "self", ".", "_createSegment", "(", "self", ".", "connections", ",", "self", ".", "lastUsedIterationForSegment", ",", "cell", ",", "self", ".", "iteration", ",", "self", ".", "maxSegmentsP...
43.529412
0.009259
def compile_low_chunks(self): ''' Compile the highstate but don't run it, return the low chunks to see exactly what the highstate will execute ''' top = self.get_top() matches = self.top_matches(top) high, errors = self.render_highstate(matches) # If ther...
[ "def", "compile_low_chunks", "(", "self", ")", ":", "top", "=", "self", ".", "get_top", "(", ")", "matches", "=", "self", ".", "top_matches", "(", "top", ")", "high", ",", "errors", "=", "self", ".", "render_highstate", "(", "matches", ")", "# If there i...
31.807692
0.002347
def update(self, i): """D.update(E) -> None. Update D from iterable E with pre-existing items being overwritten. Elements in E are assumed to be dicts containing the primary key to allow the equivelent of: for k in E: D[k.primary_key] = k """ key_list = ...
[ "def", "update", "(", "self", ",", "i", ")", ":", "key_list", "=", "self", ".", "key_list", "keynone", "=", "{", "key", ":", "None", "for", "key", "in", "key_list", "}", "# Generator which fills in missing data from the original iterator", "def", "datagen", "(",...
38.875
0.008368
def on_deleted(self, event): """ on_deleted handler """ logger.debug("File deleted: %s", event.src_path) if not event.is_directory: self.update_file(event.src_path)
[ "def", "on_deleted", "(", "self", ",", "event", ")", ":", "logger", ".", "debug", "(", "\"File deleted: %s\"", ",", "event", ".", "src_path", ")", "if", "not", "event", ".", "is_directory", ":", "self", ".", "update_file", "(", "event", ".", "src_path", ...
39.2
0.01
def inside(points, polygons, short_circuit='any', precision=0.001): """ Test whether each of the points is within the given set of polygons. Parameters ---------- points : array-like[N][2] or list of array-like[N][2] Coordinates of the points to be tested or groups of points to be t...
[ "def", "inside", "(", "points", ",", "polygons", ",", "short_circuit", "=", "'any'", ",", "precision", "=", "0.001", ")", ":", "poly", "=", "[", "]", "if", "isinstance", "(", "polygons", ",", "PolygonSet", ")", ":", "poly", ".", "extend", "(", "polygon...
38.204082
0.000521
def create(self, instance, parameters, existing): """ Create the instance Args: instance (AtlasServiceInstance.Instance): Existing or New instance parameters (dict): Parameters for the instance existing (bool): Create an instance on an existing Atlas cluster ...
[ "def", "create", "(", "self", ",", "instance", ",", "parameters", ",", "existing", ")", ":", "if", "not", "instance", ".", "isProvisioned", "(", ")", ":", "# Set parameters", "instance", ".", "parameters", "=", "parameters", "# Existing cluster", "if", "existi...
42.369565
0.01003
def __add_dependency(self, word_instance, sent_id): """ adds an ingoing dependency relation from the projected head of a token to the token itself. """ # 'head_attr': (projected) head head = word_instance.__getattribute__(self.head_attr) deprel = word_instance.__g...
[ "def", "__add_dependency", "(", "self", ",", "word_instance", ",", "sent_id", ")", ":", "# 'head_attr': (projected) head", "head", "=", "word_instance", ".", "__getattribute__", "(", "self", ".", "head_attr", ")", "deprel", "=", "word_instance", ".", "__getattribute...
43.962963
0.001649
def add(self, name, productcat_id, standard_price, retail_price_low, retail_price_high, category_id, quantity, alarm_number, desc, prov, city, postage_type, have_invoice, have_guarantee, session, **kwargs): '''taobao.fenxiao.product.add 添加产品 添加分销平台产品数据。业务逻辑与分销系统前台页面一致 - 产品图片默认为...
[ "def", "add", "(", "self", ",", "name", ",", "productcat_id", ",", "standard_price", ",", "retail_price_low", ",", "retail_price_high", ",", "category_id", ",", "quantity", ",", "alarm_number", ",", "desc", ",", "prov", ",", "city", ",", "postage_type", ",", ...
58
0.016332
async def read( cls, reader: Callable[[int], Awaitable[bytes]], *, mask: bool, max_size: Optional[int] = None, extensions: Optional[Sequence["websockets.extensions.base.Extension"]] = None, ) -> "Frame": """ Read a WebSocket frame and return a :class:`...
[ "async", "def", "read", "(", "cls", ",", "reader", ":", "Callable", "[", "[", "int", "]", ",", "Awaitable", "[", "bytes", "]", "]", ",", "*", ",", "mask", ":", "bool", ",", "max_size", ":", "Optional", "[", "int", "]", "=", "None", ",", "extensio...
35.013889
0.001929
def _point_in_tectonic_region(self, polygon): ''' Returns the region type and area according to the tectonic region :param polygon: Dictionary containing the following attributes - 'long_lims' - Longitude limits (West, East) 'lat_lims' - Latitude limits (South, No...
[ "def", "_point_in_tectonic_region", "(", "self", ",", "polygon", ")", ":", "marker", "=", "np", ".", "zeros", "(", "self", ".", "strain", ".", "get_number_observations", "(", ")", ",", "dtype", "=", "bool", ")", "idlong", "=", "np", ".", "logical_and", "...
44.961538
0.001675
def init_params(net): '''Init layer parameters.''' for m in net.modules(): if isinstance(m, nn.Conv2d): init.kaiming_normal(m.weight, mode='fan_out') if m.bias: init.constant(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): init.constant(m.weight...
[ "def", "init_params", "(", "net", ")", ":", "for", "m", "in", "net", ".", "modules", "(", ")", ":", "if", "isinstance", "(", "m", ",", "nn", ".", "Conv2d", ")", ":", "init", ".", "kaiming_normal", "(", "m", ".", "weight", ",", "mode", "=", "'fan_...
35.357143
0.001969
def script(self, sql_script, split_algo='sql_split', prep_statements=True, dump_fails=True): """Wrapper method providing access to the SQLScript class's methods and properties.""" return Execute(sql_script, split_algo, prep_statements, dump_fails, self)
[ "def", "script", "(", "self", ",", "sql_script", ",", "split_algo", "=", "'sql_split'", ",", "prep_statements", "=", "True", ",", "dump_fails", "=", "True", ")", ":", "return", "Execute", "(", "sql_script", ",", "split_algo", ",", "prep_statements", ",", "du...
89
0.018587
def copy(self): """Returns a deep copy of itself.""" net = QueueNetwork(None) net.g = self.g.copy() net.max_agents = copy.deepcopy(self.max_agents) net.nV = copy.deepcopy(self.nV) net.nE = copy.deepcopy(self.nE) net.num_agents = copy.deepcopy(self.num_agents) ...
[ "def", "copy", "(", "self", ")", ":", "net", "=", "QueueNetwork", "(", "None", ")", "net", ".", "g", "=", "self", ".", "g", ".", "copy", "(", ")", "net", ".", "max_agents", "=", "copy", ".", "deepcopy", "(", "self", ".", "max_agents", ")", "net",...
42.166667
0.001932
def _str(self, i, x): """Handles string formatting of cell data i - index of the cell datatype in self._dtype x - cell data to format """ FMT = { 'a':self._fmt_auto, 'i':self._fmt_int, 'f':self._fmt_float, 'e':self._fmt_exp...
[ "def", "_str", "(", "self", ",", "i", ",", "x", ")", ":", "FMT", "=", "{", "'a'", ":", "self", ".", "_fmt_auto", ",", "'i'", ":", "self", ".", "_fmt_int", ",", "'f'", ":", "self", ".", "_fmt_float", ",", "'e'", ":", "self", ".", "_fmt_exp", ","...
26.521739
0.011076
def post(self, tag_suffix=None): # pylint: disable=W0221 ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **E...
[ "def", "post", "(", "self", ",", "tag_suffix", "=", "None", ")", ":", "# pylint: disable=W0221", "disable_auth", "=", "self", ".", "application", ".", "mod_opts", ".", "get", "(", "'webhook_disable_auth'", ")", "if", "not", "disable_auth", "and", "not", "self"...
31.708333
0.000765
def generate_filename(self, directory=os.getcwd(), prefix='tile', format='png', path=True): """Construct and return a filename for this tile.""" filename = prefix + '_{col:02d}_{row:02d}.{ext}'.format( col=self.column, row=self.row, ext=format.lower().repl...
[ "def", "generate_filename", "(", "self", ",", "directory", "=", "os", ".", "getcwd", "(", ")", ",", "prefix", "=", "'tile'", ",", "format", "=", "'png'", ",", "path", "=", "True", ")", ":", "filename", "=", "prefix", "+", "'_{col:02d}_{row:02d}.{ext}'", ...
53.75
0.009153
def add_services(self, info): """Add auth service descriptions to an IIIFInfo object. Login service description is the wrapper for all other auth service descriptions so we have nothing unless self.login_uri is specified. If we do then add any other auth services at children. ...
[ "def", "add_services", "(", "self", ",", "info", ")", ":", "if", "(", "self", ".", "login_uri", ")", ":", "svc", "=", "self", ".", "login_service_description", "(", ")", "svcs", "=", "[", "]", "if", "(", "self", ".", "logout_uri", ")", ":", "svcs", ...
41.296296
0.001753
def _verify_support(identity, ecdh): """Make sure the device supports given configuration.""" protocol = identity.identity_dict['proto'] if protocol not in {'ssh'}: raise NotImplementedError( 'Unsupported protocol: {}'.format(protocol)) if ecdh: raise NotImplementedError('No ...
[ "def", "_verify_support", "(", "identity", ",", "ecdh", ")", ":", "protocol", "=", "identity", ".", "identity_dict", "[", "'proto'", "]", "if", "protocol", "not", "in", "{", "'ssh'", "}", ":", "raise", "NotImplementedError", "(", "'Unsupported protocol: {}'", ...
45.090909
0.001976
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" n=pa...
[ "def", "as_xml", "(", "self", ",", "parent", ")", ":", "n", "=", "parent", ".", "newChild", "(", "None", ",", "\"ORG\"", ",", "None", ")", "n", ".", "newTextChild", "(", "None", ",", "\"ORGNAME\"", ",", "to_utf8", "(", "self", ".", "name", ")", ")"...
33.571429
0.020704
def main(argv): """Main""" global options opts = None try: opts, args = getopt.getopt(argv, options['short'], options['long']) except getopt.GetoptError: usage() exit(2) for opt, arg in opts: if opt in ("-h", "--help"): usage() exit() ...
[ "def", "main", "(", "argv", ")", ":", "global", "options", "opts", "=", "None", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "argv", ",", "options", "[", "'short'", "]", ",", "options", "[", "'long'", "]", ")", "except", "get...
30.544118
0.000933
def regular(u): ''' Equation matrix generation for the regular (cubic) lattice. The order of constants is as follows: .. math:: C_{11}, C_{12}, C_{44} :param u: vector of deformations: [ :math:`u_{xx}, u_{yy}, u_{zz}, u_{yz}, u_{xz}, u_{xy}` ] :returns: Symmetry defined stress-...
[ "def", "regular", "(", "u", ")", ":", "uxx", ",", "uyy", ",", "uzz", ",", "uyz", ",", "uxz", ",", "uxy", "=", "u", "[", "0", "]", ",", "u", "[", "1", "]", ",", "u", "[", "2", "]", ",", "u", "[", "3", "]", ",", "u", "[", "4", "]", ",...
33.095238
0.001399
def add_member(self,grange): """Add a genomic range to the locus :param grange: :type grange: GenomicRange """ if self.use_direction and not grange.direction: sys.stderr.write("ERROR if using direction then direction of input members must be set\n") sys.exit() # Get range set proper...
[ "def", "add_member", "(", "self", ",", "grange", ")", ":", "if", "self", ".", "use_direction", "and", "not", "grange", ".", "direction", ":", "sys", ".", "stderr", ".", "write", "(", "\"ERROR if using direction then direction of input members must be set\\n\"", ")",...
40.625
0.018036
def WriteGoogleTransitFeed(self, file): """Output this schedule as a Google Transit Feed in file_name. Args: file: path of new feed file (a string) or a file-like object Returns: None """ # Compression type given when adding each file archive = zipfile.ZipFile(file, 'w') if 'a...
[ "def", "WriteGoogleTransitFeed", "(", "self", ",", "file", ")", ":", "# Compression type given when adding each file", "archive", "=", "zipfile", ".", "ZipFile", "(", "file", ",", "'w'", ")", "if", "'agency'", "in", "self", ".", "_table_columns", ":", "agency_stri...
39.10274
0.011787
def sortino_ratio(self, threshold=0.0, ddof=0, freq=None): """Return over a threshold per unit of downside deviation. A performance appraisal ratio that replaces standard deviation in the Sharpe ratio with downside deviation. [Source: CFA Institute] Parameters ---------...
[ "def", "sortino_ratio", "(", "self", ",", "threshold", "=", "0.0", ",", "ddof", "=", "0", ",", "freq", "=", "None", ")", ":", "stdev", "=", "self", ".", "semi_stdev", "(", "threshold", "=", "threshold", ",", "ddof", "=", "ddof", ",", "freq", "=", "...
39.818182
0.001486
def community_user_posts(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/posts#list-posts" api_path = "/api/v2/community/users/{id}/posts.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
[ "def", "community_user_posts", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/community/users/{id}/posts.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "(...
54.4
0.01087
def _get_task_statuses(task_ids, cluster): """ Retrieve task statuses from ECS API Returns list of {RUNNING|PENDING|STOPPED} for each id in task_ids """ response = client.describe_tasks(tasks=task_ids, cluster=cluster) # Error checking if response['failures'] != []: raise Exception...
[ "def", "_get_task_statuses", "(", "task_ids", ",", "cluster", ")", ":", "response", "=", "client", ".", "describe_tasks", "(", "tasks", "=", "task_ids", ",", "cluster", "=", "cluster", ")", "# Error checking", "if", "response", "[", "'failures'", "]", "!=", ...
36.333333
0.00149
def _process_omim2disease(self, limit=None): """ This method maps the KEGG disease IDs to the corresponding OMIM disease IDs. Currently this only maps KEGG diseases and OMIM diseases that are 1:1. Triples created: <kegg_disease_id> is a class <omim_disease_id> is...
[ "def", "_process_omim2disease", "(", "self", ",", "limit", "=", "None", ")", ":", "LOG", ".", "info", "(", "\"Processing 1:1 KEGG disease to OMIM disease mappings\"", ")", "if", "self", ".", "test_mode", ":", "graph", "=", "self", ".", "testgraph", "else", ":", ...
41.898551
0.002366
def walk(self, cli): """ Walk through children. """ yield self for i in self.content.walk(cli): yield i for f in self.floats: for i in f.content.walk(cli): yield i
[ "def", "walk", "(", "self", ",", "cli", ")", ":", "yield", "self", "for", "i", "in", "self", ".", "content", ".", "walk", "(", "cli", ")", ":", "yield", "i", "for", "f", "in", "self", ".", "floats", ":", "for", "i", "in", "f", ".", "content", ...
22.8
0.008439
def _eq(self, other): """Compare two nodes for equality.""" return (self.type, self.children) == (other.type, other.children)
[ "def", "_eq", "(", "self", ",", "other", ")", ":", "return", "(", "self", ".", "type", ",", "self", ".", "children", ")", "==", "(", "other", ".", "type", ",", "other", ".", "children", ")" ]
46.333333
0.014184
def assemble( cls, args, input_tube, output_tubes, size, disable_result, do_stop_task, ): """Create, assemble and start workers. Workers are created of class *cls*, initialized with *args*, and given task/result communication c...
[ "def", "assemble", "(", "cls", ",", "args", ",", "input_tube", ",", "output_tubes", ",", "size", ",", "disable_result", ",", "do_stop_task", ",", ")", ":", "# Create the workers.", "workers", "=", "[", "]", "for", "ii", "in", "range", "(", "size", ")", "...
28.84375
0.008386
def getPlayer(name): """obtain a specific PlayerRecord settings file""" if isinstance(name, PlayerRecord): return name try: return getKnownPlayers()[name.lower()] except KeyError: raise ValueError("given player name '%s' is not a known player definition"%(name))
[ "def", "getPlayer", "(", "name", ")", ":", "if", "isinstance", "(", "name", ",", "PlayerRecord", ")", ":", "return", "name", "try", ":", "return", "getKnownPlayers", "(", ")", "[", "name", ".", "lower", "(", ")", "]", "except", "KeyError", ":", "raise"...
47.333333
0.020761
def geocode_location(location, sensor=False, api_key=None): """Converts a human-readable location to lat-lng. Returns a dict with lat and lng keys. keyword arguments: location -- A human-readable location, e.g 'London, England' sensor -- Boolean flag denoting if the location came from a device u...
[ "def", "geocode_location", "(", "location", ",", "sensor", "=", "False", ",", "api_key", "=", "None", ")", ":", "params", "=", "{", "'address'", ":", "location", ",", "'sensor'", ":", "str", "(", "sensor", ")", ".", "lower", "(", ")", "}", "if", "api...
41.88
0.001867