Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
354,200
def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): url =...
Issues a request to insert a query job. Args: sql: the SQL string representing the query to execute. code: code for Javascript UDFs, if any. imports: a list of GCS URLs containing additional Javascript UDF support code, if any. table_name: None for an anonymous table, or a name parts tuple ...
354,201
def visit_DictComp(self, node: ast.DictComp) -> None: if node in self._recomputed_values: value = self._recomputed_values[node] text = self._atok.get_text(node) self.reprs[text] = value self.generic_visit(node=node)
Represent the dictionary comprehension by dumping its source code.
354,202
def merge_multipartobject(upload_id, version_id=None): mp = MultipartObject.query.filter_by(upload_id=upload_id).one_or_none() if not mp: raise RuntimeError() if not mp.completed: raise RuntimeError() try: obj = mp.merge_parts( version_id=version_id, ...
Merge multipart object. :param upload_id: The :class:`invenio_files_rest.models.MultipartObject` upload ID. :param version_id: Optionally you can define which file version. (Default: ``None``) :returns: The :class:`invenio_files_rest.models.ObjectVersion` version ID.
354,203
def datetime(self): date_string = % (self._date, self._year) date_string = re.sub(r, , date_string) return datetime.strptime(date_string, )
Returns a datetime object of the month, day, year, and time the game was played.
354,204
def check_string(sql_string, add_semicolon=False): prepped_sql = sqlprep.prepare_sql(sql_string, add_semicolon=add_semicolon) success, msg = ecpg.check_syntax(prepped_sql) return success, msg
Check whether a string is valid PostgreSQL. Returns a boolean indicating validity and a message from ecpg, which will be an empty string if the input was valid, or a description of the problem otherwise.
354,205
def get_property_names(obj): property_names = [] if obj != None: cycle_detect = [] RecursiveObjectReader._perform_get_property_names(obj, None, property_names, cycle_detect) return property_names
Recursively gets names of all properties implemented in specified object and its subobjects. The object can be a user defined object, map or array. Returned property name correspondently are object properties, map keys or array indexes. :param obj: an object to introspect. :return: a ...
354,206
def run_autoapi(app): if not app.config.autoapi_dirs: raise ExtensionError("You must configure an autoapi_dirs setting") normalized_dirs = [] autoapi_dirs = app.config.autoapi_dirs if isinstance(autoapi_dirs, str): autoapi_dirs = [autoapi_dirs] for path in autoapi_dirs: ...
Load AutoAPI data from the filesystem.
354,207
def get_len(self, key): data = self.model.get_data() return len(data[key])
Return sequence length
354,208
def _GetDataTypeMap(self, name): data_type_map = self._data_type_maps.get(name, None) if not data_type_map: data_type_map = self._fabric.CreateDataTypeMap(name) self._data_type_maps[name] = data_type_map return data_type_map
Retrieves a data type map defined by the definition file. The data type maps are cached for reuse. Args: name (str): name of the data type as defined by the definition file. Returns: dtfabric.DataTypeMap: data type map which contains a data type definition, such as a structure, that...
354,209
def calc_significand(prefix, dpd_bits, num_bits): num_segments = num_bits // 10 segments = [] for i in range(num_segments): segments.append(dpd_bits & 0b1111111111) dpd_bits >>= 10 segments.reverse() v = prefix for dpd in segments: v = v * 1000 + dpd_to_int(dpd...
prefix: High bits integer value dpd_bits: dpd encoded bits num_bits: bit length of dpd_bits
354,210
def append(self, word, lemma=None, type=None, chunk=None, role=None, relation=None, pnp=None, anchor=None, iob=None, custom={}): self._do_word(word, lemma, type) self._do_chunk(chunk, role, relation, iob) self._do_conjunction() self._do_relation() self._do_...
Appends the next word to the sentence / chunk / preposition. For example: Sentence.append("clawed", "claw", "VB", "VP", role=None, relation=1) - word : the current word, - lemma : the canonical form of the word, - type : part-of-speech tag for the word (NN, JJ,...
354,211
def clone(url): backend = None backendmgr = None if url.startswith(): backendtype = elif url.startswith("http") or url.startswith("git"): backendtype = else: backendtype = None mgr = plugins_get_mgr() repomgr = mgr.get(what=, name=) backendmgr = mgr.get(wh...
Clone a URL. Examples include: - git@github.com:pingali/dgit.git - https://github.com:pingali/dgit.git - s3://mybucket/git/pingali/dgit.git Parameters ---------- url: URL of the repo
354,212
def make_roi(cls, sources=None): if sources is None: sources = {} src_fact = cls() src_fact.add_sources(sources) ret_model = roi_model.ROIModel( {}, skydir=SkyCoord(0.0, 0.0, unit=)) for source in src_fact.sources.values(): ret_model.l...
Build and return a `fermipy.roi_model.ROIModel` object from a dict with information about the sources
354,213
def parse_response(resp): if resp.status_code in [200, 201, 202]: return resp.json() elif resp.status_code == 204: return None elif resp.status_code == 400: raise error.BadRequestError(resp.text) elif resp.status_code == 401: raise...
Method to parse response from the Optimizely API and return results as JSON. Errors are thrown for various errors that the API can throw.
354,214
def parse_files(self, files=None, sections=None): files = _list(files, self.configfiles) sections = _list(sections, self.sections) for file in files: parser = StrictConfigParser() parser.read(file) for section in sections: if not parse...
Parse configfiles. files <list str>, <str> or None: What files to parse. None means use self.configfiles. New values override old ones. A string value will be interpreted as a list of one item. sections <list str>, <str> or None: Which sections to parse f...
354,215
def remove_args(parser): arguments = [] for action in list(parser._get_optional_actions()): if not in action.option_strings: arguments += action.option_strings for arg in arguments: if arg in sys.argv: sys.argv.remove(arg)
Remove custom arguments from the parser
354,216
def remove_all_gap_columns( self ): seqs = [] for c in self.components: try: seqs.append( list( c.text ) ) except TypeError: seqs.append( None ) i = 0 text_size = self.text_size while i < text_size: all_...
Remove any columns containing only gaps from alignment components, text of components is modified IN PLACE.
354,217
def bigram(self, items): def bigram_join(tok_list): text = nltk.bigrams(tok_list) return list(map(lambda x: x[0] + + x[1], text)) if items == "tokens": self.bigrams = list(map(bigram_join, self.tokens)) elif items == "stems": self.bigr...
generate bigrams of either items = "tokens" or "stems"
354,218
def postorder(self): nodes_random = self.nodes() nodes_by_branch = sorted(nodes_random, cmp=self.cmp_branch) nodes_topological = [] for node in nodes_by_branch: self.dfs(node, nodes_topological) self.clear_nodes() ...
Returns a valid postorder of the **node objects** of the ``DictGraph`` *if* the topology is a directed acyclic graph. This postorder is semi-random, because the order of elements in a dictionary is semi-random and so are the starting nodes of the depth-first search traversal, which d...
354,219
def destinations(self): session = meta.Session() sel = select([distinct(model.frames_table.c.destination)]) result = session.execute(sel) return set([r[0] for r in result.fetchall()])
Provides a list of destinations (queue "addresses") available. @return: A list of the detinations available. @rtype: C{set}
354,220
def has_changed(self): request = urllib_request.Request(self.url) request.get_method = lambda: response = urllib_request.urlopen(request) information = response.info() if in information: last_modified = information[] if last_modi...
Method to check if an image has changed since it was last downloaded. By making a head request, this check can be done quicker that downloading and processing the whole file.
354,221
def pause(self): if self.decoder.status == mediadecoder.PAUSED: self.decoder.pause() self.paused = False elif self.decoder.status == mediadecoder.PLAYING: self.decoder.pause() self.paused = True else: print("Player not in pausable state")
Pauses playback.
354,222
def _report_exc_info(exc_info, request, extra_data, payload_data, level=None): if not _check_config(): return filtered_level = _filtered_level(exc_info[1]) if level is None: level = filtered_level filtered_exc_info = events.on_exception_info(exc_info, ...
Called by report_exc_info() wrapper
354,223
def getATR(self): CardConnection.getATR(self) if None == self.hcard: raise CardConnectionException() hresult, reader, state, protocol, atr = SCardStatus(self.hcard) if hresult != 0: raise CardConnectionException( + \ SCard...
Return card ATR
354,224
def _setup_gc2_framework(self): edge_sets = self._get_cartesian_edge_set() self.gc2_config = {} endpoint_set = numpy.vstack([cep for cep in self.cartesian_endpoints]) dmat = squareform(pdist(endpoint_set)) irow, icol = numpy.unravel_index(numpy.argmax(d...
This method establishes the GC2 framework for a multi-segment (and indeed multi-typology) case based on the description in Spudich & Chiou (2015) - see section on Generalized Coordinate System for Multiple Rupture Traces
354,225
def _parse_figure(self, node, state): if node.tag not in ["img", "figure"]: return state stable_id = ( f"{state[].name}" f"::" f"{}" f":" f"{state[][]}" ) name = node.attrib["name"] if "n...
Parse the figure node. :param node: The lxml img node to parse :param state: The global state necessary to place the node in context of the document as a whole.
354,226
def _get_by_id(collection, id): matches = [item for item in collection if item.id == id] if not matches: raise ValueError() elif len(matches) > 1: raise ValueError(.format(len(matches))) return matches[0]
Get item from a list by the id field
354,227
def _ExtractOAuth2Client(product_yaml_key, product_data, proxy_config): oauth2_kwargs = { : proxy_config } if all(config in product_data for config in _OAUTH2_INSTALLED_APP_KEYS): oauth2_args = [ product_data[], product_data[], product_data[] ] oauth2_client = googleads.oauth...
Generates an GoogleOAuth2Client subclass using the given product_data. Args: product_yaml_key: a string key identifying the product being configured. product_data: a dict containing the configurations for a given product. proxy_config: a ProxyConfig instance. Returns: An instantiated GoogleOAuth2C...
354,228
def run(self, **kwargs): try: box = imaplib.IMAP4_SSL(settings.IMAP_SERVER) box.login(settings.IMAP_USERNAME, settings.IMAP_PASSWORD) box.select() result, mail_indices = box.search(None, ) if result == ...
Checks the IMAP mailbox for new mails and tries to handle them.
354,229
def warnings(self): response = self._get(url.status_warnings) self._check_response(response, 200) return self._create_response(response)
Get server system warnings. Uses GET to /status/warnings. :returns: (dict) Server messages and warnings as described `here <https://cloud.knuverse.com/docs/api/#api-General-Warnings>`_.
354,230
def get_all_triggers(bump, file_triggers): triggers = set() if file_triggers: triggers = triggers.union(detect_file_triggers(config.trigger_patterns)) if bump: _LOG.debug("trigger: %s bump requested", bump) triggers.add(bump) return triggers
Aggregated set of significant figures to bump
354,231
def from_lasio_curve(cls, curve, depth=None, basis=None, start=None, stop=None, step=0.1524, run=-1, null=-999.25, servi...
Makes a curve object from a lasio curve object and either a depth basis or start and step information. Args: curve (ndarray) depth (ndarray) basis (ndarray) start (float) stop (float) step (float): default: 0.1524 run (...
354,232
def on_recognizer_result( self, recognizer_result: RecognizerResult, turn_context: TurnContext, telemetry_properties: Dict[str, str] = None, telemetry_metrics: Dict[str, float] = None, ): properties = self.fill_luis_event_properties( recognizer_r...
Invoked prior to a LuisResult being logged. :param recognizer_result: The Luis Results for the call. :type recognizer_result: RecognizerResult :param turn_context: Context object containing information for a single turn of conversation with a user. :type turn_context: TurnContex...
354,233
def _extract_and_flatten_nested_structure(data, flattened=None): if flattened is None: flattened = [] structure = _extract_and_flatten_nested_structure(data, flattened) return structure, flattened if isinstance(data, list): return list(_extract_and_flatten_nested_structure(x...
Flatten the structure of a nested container to a list. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol. The nested container to be flattened. flattened : list or None The container thats holds flattened result. Returns ------- st...
354,234
def find_thermodynamic_reversibility_index(reactions): u incomplete_mapping = [] problematic_calculation = [] reversibility_indexes = [] unbalanced = [] metabolite_mapping = {} for rxn in reactions: stoich = translate_reaction(rxn, metabolite_mapping) if len(stoich) < len(rx...
u""" Return the reversibility index of the given reactions. To determine the reversibility index, we calculate the reversibility index ln_gamma (see [1]_ section 3.5) of each reaction using the eQuilibrator API [2]_. Parameters ---------- reactions: list of cobra.Reaction A...
354,235
def backward(self,pixx,pixy): skyx,skyy = self.output.wcs_pix2world(pixx,pixy,self.origin) result = self.input.all_world2pix(skyx,skyy,self.origin) return result
Transform pixx,pixy positions from the output frame back onto their original positions in the input frame.
354,236
def cleanup(self): if not len(self.water_ids) == 0: water_selection = [] for wid in self.water_ids: water_selection.append( % wid) self.rc("~display :HOH") self.rc("display :@/%s" % " or ".join(water_selection)) ...
Clean up the visualization.
354,237
def schemaNewValidCtxt(self): ret = libxml2mod.xmlSchemaNewValidCtxt(self._o) if ret is None:raise treeError() __tmp = SchemaValidCtxt(_obj=ret) __tmp.schema = self return __tmp
Create an XML Schemas validation context based on the given schema.
354,238
def get_last_modified_date( self, bucket: str, key: str, ) -> datetime.datetime: blob_obj = self._get_blob_obj(bucket, key) return blob_obj.updated
Retrieves last modified date for a given key in a given bucket. :param bucket: the bucket the object resides in. :param key: the key of the object for which the last modified date is being retrieved. :return: the last modified date
354,239
def get_stats(self): try: query = { for key, value in aggregations.items() } except NotFoundError: return {}
Get some stats on the packages in the registry
354,240
def load_image(self): try: image = initializers.load_tiff(self.filename) image = initializers.normalize( image, invert=self.invert, scale=self.exposure, dtype=self.float_precision ) except IOError as e: log.error("C...
Read the file and perform any transforms to get a loaded image
354,241
def init_hidden(self, hidden): if hidden is not None: hidden = hidden.chunk(self.num_layers) hidden = tuple(i.chunk(2) for i in hidden) else: hidden = [None] * self.num_layers self.next_hidden = [] return hidden
Converts flattened hidden state (from sequence generator) into a tuple of hidden states. :param hidden: None or flattened hidden state for decoder RNN layers
354,242
def get_models(self, columns=None): results = self._query.get(columns) connection = self._model.get_connection_name() return self._model.hydrate(results, connection).all()
Get the hydrated models without eager loading. :param columns: The columns to get :type columns: list :return: A list of models :rtype: list
354,243
def update_actions(self): self.clear() self.recent_files_actions[:] = [] for file in self.manager.get_recent_files(): action = QtWidgets.QAction(self) action.setText(os.path.split(file)[1]) action.setToolTip(file) action.setStatusTip(file)...
Updates the list of actions.
354,244
def registration_authority_entity_id(self): if ATTR_ENTITY_REGISTRATION_AUTHORITY in self.raw: try: return self.raw[ ATTR_ENTITY_REGISTRATION_AUTHORITY][ ATTR_ENTITY_REGISTRATION_AUTHORITY_ENTITY_ID][ ATTR_DOLLAR_S...
Some entities return the register entity id, but other do not. Unsure if this is a bug or inconsistently registered data.
354,245
def release(self): base64_key = _encode(self.key) base64_value = _encode(self._uuid) txn = { : [{ : base64_key, : , : , : base64_value }], : [{ : { : ...
Release the lock
354,246
def taxon_table(self): if self.tests: keys = sorted(self.tests[0].keys()) if isinstance(self.tests, list): ld = [[(key, i[key]) for key in keys] for i in self.tests] dd = [dict(i) for i in ld] df = pd.DataFrame(dd) ...
Returns the .tests list of taxa as a pandas dataframe. By auto-generating this table from tests it means that the table itself cannot be modified unless it is returned and saved.
354,247
def run(self): queue = Queue() process = UploadProcess(self._connection_settings, self._room, queue, self._files) if self._data: process.add_data(self._data) process.start() if not process.is_alive(): return self._uploading = True ...
Called by the thread, it runs the process. NEVER call this method directly. Instead call start() to start the thread. Before finishing the thread using this thread, call join()
354,248
def _createFromLocal(self, data, schema): if not isinstance(data, list): data = list(data) if schema is None or isinstance(schema, (list, tuple)): struct = self._inferSchemaFromList(data, names=schema) converter = _create_converter(struct) ...
Create an RDD for DataFrame from a list or pandas.DataFrame, returns the RDD and schema.
354,249
def reset_password(app, appbuilder, username, password): _appbuilder = import_application(app, appbuilder) user = _appbuilder.sm.find_user(username=username) if not user: click.echo("User {0} not found.".format(username)) else: _appbuilder.sm.reset_password(user.id, password) ...
Resets a user's password
354,250
def get(self): data = dict() for label, entry in zip(self.keys, self.values): data[label.cget()] = entry.get() return data
Retrieve the GUI elements for program use. :return: a dictionary containing all \ of the data from the key/value entries
354,251
def update(self): stats = self.get_init_value() if import_error_tag: return self.stats if self.input_method == : stats = get_smart_data() elif self.input_method == : pass self.stats = stats return self.sta...
Update SMART stats using the input method.
354,252
def log_normalize(data): if sp.issparse(data): data = data.copy() data.data = np.log2(data.data + 1) return data return np.log2(data.astype(np.float64) + 1)
Perform log transform log(x + 1). Parameters ---------- data : array_like
354,253
def get_assignments(self, course_id): url = ASSIGNMENTS_API.format(course_id) data = self._get_resource(url) assignments = [] for datum in data: assignments.append(Assignment(data=datum)) return assignments
List assignments for a given course https://canvas.instructure.com/doc/api/assignments.html#method.assignments_api.index
354,254
def calculate_exposure(self, duration): exposure = duration - self.frequency_accuracy * duration / 1000000.0 - \ self.readout_time assert exposure > 0.0, \ "Exposure time %s too small when deadtime taken into account" % ( exposure,) ...
Calculate the exposure to set the detector to given the duration of the frame and the readout_time and frequency_accuracy
354,255
def DEFINE_multi_enum( name, default, enum_values, help, flag_values=_flagvalues.FLAGS, case_sensitive=True, **args): parser = _argument_parser.EnumParser(enum_values, case_sensitive) serializer = _argument_parser.ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values,...
Registers a flag whose value can be a list strings from enum_values. Use the flag on the command line multiple times to place multiple enum values into the list. The 'default' may be a single string (which will be converted into a single-element list) or a list of strings. Args: name: str, the flag nam...
354,256
def retrieve_profile_extension_records(self, profile_extension, field_list, ids_to_retrieve, query_column=): profile_extension = profile_extension.get_soap_object(self.client) return RecordData.from_soap_type( self.call(, ...
Responsys.retrieveProfileExtensionRecords call Accepts: InteractObject profile_extension list field_list list ids_to_retrieve string query_column default: 'RIID' Returns RecordData
354,257
def ks_pvalue(fg_pos, bg_pos=None): if len(fg_pos) == 0: return 1.0 a = np.array(fg_pos, dtype="float") / max(fg_pos) p = kstest(a, "uniform")[1] return p
Computes the Kolmogorov-Smirnov p-value of position distribution. Parameters ---------- fg_pos : array_like The list of values for the positive set. bg_pos : array_like, optional The list of values for the negative set. Returns ------- p : float KS p-value.
354,258
def setAutoRangeOn(self): if self.getRefreshBlocked(): logger.debug("Set autorange on blocked for {}".format(self.nodeName)) return if self.autoRangeCti: self.autoRangeCti.data = True self.model.sigItemChanged.emit(self)
Turns on the auto range checkbox for the equivalent axes Emits the sigItemChanged signal so that the inspector may be updated. Use the setXYAxesAutoRangeOn stand-alone function if you want to set the autorange on for both axes of a viewport.
354,259
def extract_name(self): name = None name_schemas = self._DCM["InfoObjectNaming"].objects.filter(iobject_type=self.iobject_type).order_by( ).values_list(, flat=True) name_components = [] fact_list = self._DCM[].objects.filter(iobject_thru__iobject=self).o...
We want to dynamically name the iobject based on its type and selected facts. This is, what this function does: it collects all facts that have "naming" set and concatenates them in the order given by the "naming" argument. If no fact has such a flag, the type is used
354,260
def extract_words(lines): for line in lines: for word in re.findall(r"\w+", line): yield word
Extract from the given iterable of lines the list of words. :param lines: an iterable of lines; :return: a generator of words of lines.
354,261
def _load_plugins(self): plugins = self.settings[] self.plugins_dict = {} for key in plugins: if plugins[key] is None: continue self.logger.debug("Trying to load plugin {cls}".format(cls=key)) the_class = sel...
Sets up all plugins, defaults and settings.py
354,262
def set_snmp(community, host=None, admin_username=None, admin_password=None): return __execute_cmd( .format(community), host=host, admin_username=admin_username, admin_password=admin_password)
Configure CMC or individual iDRAC SNMP community string. Use ``deploy_snmp`` for configuring chassis switch SNMP. CLI Example: .. code-block:: bash salt dell dracr.set_snmp [COMMUNITY] salt dell dracr.set_snmp public
354,263
def reply(self,message,message_type): if message_type == MULTIPART: raise Exception("Unsupported reply type") super(Replier,self).send(message,message_type)
Send a reply message of the given type Args: - message: the message to publish - message_type: the type of message being sent
354,264
def _from_exception(cls, pe): return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)
internal factory method to simplify creating one type of ParseException from another - avoids having __init__ signature conflicts among subclasses
354,265
def addFASTAFilteringCommandLineOptions(parser): parser.add_argument( , type=int, help=) parser.add_argument( , type=int, help=) parser.add_argument( , action=, help=) parser.add_argument( , action=, help=) parser.add_argument(...
Add standard FASTA filtering command-line options to an argparse parser. These are options that can be used to select or omit entire FASTA records, NOT options that change them (for that see addFASTAEditingCommandLineOptions). @param parser: An C{argparse.ArgumentParser} instance.
354,266
def get_many(self, ids): return [self.instance(id, **fields) for id, fields in zip(ids, self.api.mget(ids))]
Get several entries at once.
354,267
def file_or_folder(path): target = unicode(path) return Folder(target) if os.path.isdir(target) else File(target)
Returns a File or Folder object that would represent the given path.
354,268
def logs(sess_id_or_alias): with Session() as session: try: print_wait() kernel = session.Kernel(sess_id_or_alias) result = kernel.get_logs().get() logs = result.get() if in result else print(logs) print_done() except Exc...
Shows the output logs of a running container. \b SESSID: Session ID or its alias given when creating the session.
354,269
def highlight_canvas(self, highlight): colorname = self.canvas.palette().highlight().color().name() if highlight: self.canvas.setStyleSheet( "FigureCanvas{border: 1px solid %s;}" % colorname) else: self.canvas.setStyleSheet("FigureCanvas{}")
Set a colored frame around the FigureCanvas if highlight is True.
354,270
def rm_filesystems(name, device, config=): * modified = False view_lines = [] if not in __grains__[]: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): ...
.. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg
354,271
def labels(self): return [self._labels.get(value) or text.pretty(key) for key, value in sorted(self.items(), key=lambda x: x[1])]
Return a list of "user friendly" labels. :return <list> [ <str>, .. ]
354,272
def _make_summary_statistic(attr): def _fn(self, **kwargs): x = getattr(self.distribution, attr)(**kwargs) shape = prefer_static.concat([ self.distribution.batch_shape_tensor(), prefer_static.ones(prefer_static.rank_from_shape(self.sample_shape), dtype=self.s...
Factory for implementing summary statistics, eg, mean, stddev, mode.
354,273
def notify_launch(self, log_level=): if not self.debug: self.logger.log( logging.getLevelName(log_level), , self.PROGNAME, platform.node() ) flask_options = { key: getattr(self, key) for key in OPTION_ARGS } fla...
logs launcher message before startup Args: log_level (str): level to notify at
354,274
def solvemdbi_rsm(ah, rho, b, axisK, dimN=2): r axisM = dimN + 2 slcnc = (slice(None),) * axisK M = ah.shape[axisM] K = ah.shape[axisK] a = np.conj(ah) Ainv = np.ones(ah.shape[0:dimN] + (1,)*4) * \ np.reshape(np.eye(M, M) / rho, (1,)*(dimN + 2) + (M, M)) for k in range(0, K): ...
r""" Solve a multiple diagonal block linear system with a scaled identity term by repeated application of the Sherman-Morrison equation. The computation is performed by explictly constructing the inverse operator, leading to an :math:`O(K)` time cost and :math:`O(M^2)` memory cost, where :math:`M` i...
354,275
def get_absolute_url(self): try: node = Node.objects.select_related().filter(page=self)[0] return node.get_absolute_url() except Exception, e: raise ValueError(u"Error in {0}.{1}: {2}".format(self.__module__, self.__class__.__name__, e)) return u"...
It returns absolute url defined by node related to this page
354,276
def from_location(cls, location, north_angle=0, daylight_saving_period=None): location = Location.from_location(location) return cls(location.latitude, location.longitude, location.time_zone, north_angle, daylight_saving_period)
Create a sun path from a LBlocation.
354,277
def get_google_songs(self, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): logger.info("Loading Google Music songs...") google_songs = self.api.get_all_songs() matched_songs, filtered_songs = filter_google_songs( google_songs, include_filters=include_filters, exclude_...
Create song list from user's Google Music library. Parameters: include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Mobileclient client. Patterns are Python regex patterns. Google Music songs are filtered out if the given meta...
354,278
def inline(self) -> str: return "{0}:{1}:{2}".format(self.amount, self.base, pypeg2.compose(self.condition, output.Condition))
Return an inline string format of the document :return:
354,279
def serve_bower_components(path): res = pkg_resources.resource_filename( , os.path.join(, )) return send_from_directory(res, path)
Serve bower components. This is meant to be used ONLY by the internal dev server. Please configure your web server to handle requests to this URL:: /bower_components/ => coil/data/bower_components
354,280
def andexp_action(self, text, loc, arg): exshared.setpos(loc, text) if DEBUG > 0: print("AND+EXP:",arg) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return label = self.codegen.label("false{0}".format(self.false_label_number), True, False...
Code executed after recognising a andexp expression (something and something)
354,281
def questions(self, type=None): if type is None: type = Question if not issubclass(type, Question): raise TypeError("{} is not a valid question type.".format(type)) return type.query.filter_by(participant_id=self.id).all()
Get questions associated with this participant. Return a list of questions associated with the participant. If specified, ``type`` filters by class.
354,282
def qualifiers(self, qualifiers): self._qualifiers = NocaseDict() if qualifiers: try: iterator = qualifiers.items() except AttributeError: iterator = qualifiers for i...
Setter method; for a description see the getter method.
354,283
def _get_ind_from_H(H): r if H <= 0: return 0 for ind, Hi in enumerate(H_std): if Hi >= H : return ind-1 return 7
r'''Method defined in the US Standard Atmosphere 1976 for determining the index of the layer a specified elevation is above. Levels are 0, 11E3, 20E3, 32E3, 47E3, 51E3, 71E3, 84852 meters respectively.
354,284
def closest_hendecasyllable_patterns(self, scansion: str) -> List[str]: return self._closest_patterns(self.VALID_HENDECASYLLABLES, scansion)
Find the closest group of matching valid hendecasyllable patterns. :return: list of the closest valid hendecasyllable patterns; only candidates with a matching length/number of syllables are considered. >>> print(MetricalValidator().closest_hendecasyllable_patterns('UU-UU-U-U-X')) ['-U...
354,285
def get_minmax(self, stmt, refine_dict): minel = refine_dict["min-elements"] maxel = refine_dict["max-elements"] if minel is None: minst = stmt.search_one("min-elements") if minst: minel = minst.arg else: minel = "0" ...
Return pair of (min,max)-elements values for `stmt`. `stmt` must be a 'list' or 'leaf-list'. Applicable refinements from `refine_dict` are also taken into account.
354,286
def connect_socket(host, port, blocking=True): addr = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM) if not addr: raise Exception("Could not translate address " % (host, str(port))) my_socket = socket.socket(addr[0][0], addr[0][1], addr[0][2]) if ...
Create a TCP connection to the server.
354,287
def create_resource(self, uri): if isinstance(uri, str): uri = URI(uri) try: resource = self.resource_factory[uri.extension](uri) except KeyError: resource = self.resource_factory[](uri) self.resources[uri.normalize()] = resource resou...
Creates a new Resource. The created ressource type depends on the used URI. :param uri: the resource URI :type uri: URI :return: a new Resource :rtype: Resource .. seealso:: URI, Resource, XMIResource
354,288
def inner(self, x1, x2): if self.exponent != 2.0: raise NotImplementedError( .format(self.exponent)) else: inner = _inner_default(x1 * self.array, x2) if is_real_dtype(x1.dtype): ...
Return the weighted inner product of ``x1`` and ``x2``. Parameters ---------- x1, x2 : `NumpyTensor` Tensors whose inner product is calculated. Returns ------- inner : float or complex The inner product of the two provided vectors.
354,289
def rr_absent(name, HostedZoneId=None, DomainName=None, PrivateZone=False, Name=None, Type=None, SetIdentifier=None, region=None, key=None, keyid=None, profile=None): Name = Name if Name else name if Type is None: raise SaltInvocationError(" is a required parameter when...
Ensure the Route53 record is deleted. name The name of the state definition. This will be used for Name if the latter is not provided. HostedZoneId The ID of the zone to delete the record from. Exclusive with DomainName. DomainName The domain name of the zone to delete t...
354,290
def guest_create(self, userid, vcpus, memory, disk_list=None, user_profile=CONF.zvm.user_profile, max_cpu=CONF.zvm.user_default_max_cpu, max_mem=CONF.zvm.user_default_max_memory, ipl_from=, ipl_param=, ipl_loadparam=): ...
create a vm in z/VM :param userid: (str) the userid of the vm to be created :param vcpus: (int) amount of vcpus :param memory: (int) size of memory in MB :param disk_list: (dict) a list of disks info for the guest. It has one dictionary that contain some of the below keys...
354,291
def generate_parameters(self, parameter_id): if not self.history: self.init_search() new_father_id = None generated_graph = None if not self.training_queue: new_father_id, generated_graph = self.generate() new_model_id = self.model_count ...
Returns a set of trial neural architecture, as a serializable object. Parameters ---------- parameter_id : int
354,292
def get_enabled_modules(): enabled = [] directory_contents = os.listdir(MODULES_FOLDER_PATH) for fname in get_installed_modules(): if not fname+ in directory_contents: enabled.append(fname) return enabled
<Purpose> Returns all enabled modules. <Arguments> None <Side Effects> None <Exceptions> None <Return> The list of all enabled modules.
354,293
def wordrelationships(relationshiplist): relationships = etree.fromstring( ) count = 0 for relationship in relationshiplist: rel_elm = makeelement(, nsprefix=None, attributes={: +str(count+1), ...
Generate a Word relationships file
354,294
def barracks_correct_placement(self) -> Point2: if len(self.upper2_for_ramp_wall) == 2: if self.barracks_can_fit_addon: return self.barracks_in_middle else: return self.barracks_in_middle.offset((-2, 0)) raise Exception("Not implemented. T...
Corrected placement so that an addon can fit
354,295
def _evaluate_f(self, n, xdata, p=None): if p is None and self.results is not None: p = self.results[0] elif p is None and self.results is None: p = self._pguess args = (xdata,) + tuple(p) return self.f[n](*args)
Evaluates a single function n for arbitrary xdata and p tuple. p=None means use the fit results
354,296
def get_items_by_search(self, item_query, item_search): if not self._can(): raise PermissionDenied() return self._provider_session.get_items_by_search(item_query, item_search)
Pass through to provider ItemSearchSession.get_items_by_search
354,297
def create_token( self, registry_address, initial_alloc=10 ** 6, name=, symbol=, decimals=2, timeout=60, auto_register=True, ): with gevent.Timeout(timeout): token_address = deploy_contract_w...
Create a proxy for a new HumanStandardToken (ERC20), that is initialized with Args(below). Per default it will be registered with 'raiden'. Args: initial_alloc (int): amount of initial tokens. name (str): human readable token name. symbol (str): token shortha...
354,298
def emit_rmic_classes(target, source, env): class_suffix = env.get(, ) classdir = env.get() if not classdir: try: s = source[0] except IndexError: classdir = else: try: classdir = s.attributes.java_classdir except...
Create and return lists of Java RMI stub and skeleton class files to be created from a set of class files.
354,299
def search_images(q, start=1, count=10, wait=10, asynchronous=False, cached=False): service = YAHOO_IMAGES return YahooSearch(q, start, count, service, None, wait, asynchronous, cached)
Returns a Yahoo images query formatted as a YahooSearch list object.