Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
361,100
def transmit(self, payload, **kwargs): kwargs[] = kwargs[] = kwargs[] = super(SapSuccessFactorsLearnerTransmitter, self).transmit(payload, **kwargs)
Send a completion status call to SAP SuccessFactors using the client. Args: payload: The learner completion data payload to send to SAP SuccessFactors
361,101
def _actor_from_game_image(self, name, game_image): HEALTH_MAX = 100 MANA_MAX = 40 tools = {: self._player_tools, : self._oppnt_tools}[name] args = [name] t, l, b, r = tools[].region_in(game_image) health_image = game...
Return an actor object matching the one in the game image. Note: Health and mana are based on measured percentage of a fixed maximum rather than the actual maximum in the game. Arguments: name: must be 'player' or 'opponent' game_image: opencv image of the main game are...
361,102
def get_iterator(self, query, **options): return EventsPageIterator(self.client, , query, options).items()
Returns an event iterator for the given query (and optional 'sync' token)
361,103
def fetch(self): params = values.of({}) payload = self._version.fetch( , self._uri, params=params, ) return ExecutionContextInstance( self._version, payload, flow_sid=self._solution[], executio...
Fetch a ExecutionContextInstance :returns: Fetched ExecutionContextInstance :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextInstance
361,104
def close_cursor(self, cursor_id, address=None): warnings.warn( "close_cursor is deprecated.", DeprecationWarning, stacklevel=2) if not isinstance(cursor_id, integer_types): raise TypeError("cursor_id must be an instance of (int, long)") ...
DEPRECATED - Send a kill cursors message soon with the given id. Raises :class:`TypeError` if `cursor_id` is not an instance of ``(int, long)``. What closing the cursor actually means depends on this client's cursor manager. This method may be called from a :class:`~pymongo.cursor.Curs...
361,105
def output(self): return ElasticsearchTarget( host=self.host, port=self.port, http_auth=self.http_auth, index=self.index, doc_type=self.doc_type, update_id=self.update_id(), marker_index_hist_size=self.marker_index_hist...
Returns a ElasticsearchTarget representing the inserted dataset. Normally you don't override this.
361,106
def save(self, filename): f = open(filename, ) for e in self._entries: line = e.to_line() if line: f.write(line) f.close()
Save host keys into a file, in the format used by openssh. The order of keys in the file will be preserved when possible (if these keys were loaded from a file originally). The single exception is that combined lines will be split into individual key lines, which is arguably a bug. @p...
361,107
def build_response(description, resource=None): response = swagger.Response( description=description, ) if resource is not None: response.schema = swagger.JsonReference({ "$ref": " }) return response
Build a response definition.
361,108
def get_pid_from_file(self): pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u) if os.path.isfile(pid_file): with open(pid_file, ) as f: s = f.read().strip() try: pid = int(s) except: ...
Get the pid from the pid file. If the pid file doesn't exist a :exc:`PIDFileError` is raised.
361,109
def add_signal_receiver(self, callback_fn, signal, user_arg): if (signal in self._signal_names): s = Signal(signal, callback_fn, user_arg) self._signals[signal] = s self._bus.add_signal_receiver(s.signal_handler, signal, ...
Add a signal receiver callback with user argument See also :py:meth:`remove_signal_receiver`, :py:exc:`.ConnSignalNameNotRecognisedException` :param func callback_fn: User-defined callback function to call when signal triggers :param str signal: Signal name e.g....
361,110
def cleanupmem(initial_memory): i = 0 while i < len(initial_memory): tmp = initial_memory[i] match = RE_LABEL.match(tmp) if not match: i += 1 continue if tmp.rstrip() == match.group(): i += 1 continue initial_memory[i...
Cleans up initial memory. Each label must be ALONE. Each instruction must have an space, etc...
361,111
def cleanup_files(self): logger.debug() with indent_log(): for req in self.reqs_to_cleanup: req.remove_temporary_source() if self._pip_has_created_build_dir(): logger.debug(, self.build_dir) rmtree(self.build_dir)
Clean up files, remove builds.
361,112
def List(self): print() for key in list(self.keys()): print(key,,self[key]) print()
Lists the keys and values.
361,113
def decimate(self, method, a, maxpoints=10000, **kwargs): methods = {: self.decimate_mean, : self.decimate_min, : self.decimate_max, : self.decimate_smooth, : self.decimate_rms, : self.decimate_percentile, ...
Decimate data *a* to *maxpoints* using *method*. If *a* is a 1D array then it is promoted to a (2, N) array where the first column simply contains the index. If the array contains fewer than *maxpoints* points or if *maxpoints* is ``None`` then it is returned as it is. The defa...
361,114
def attribute(self): paint = { "bold": self.ESC + "1" + self.END, 1: self.ESC + "1" + self.END, "dim": self.ESC + "2" + self.END, 2: self.ESC + "2" + self.END, "underlined": self.ESC + "4" + self.END, 4: self.ESC + "4" + self.END,...
Set or reset attributes
361,115
def pos_tag( words: List[str], engine: str = "perceptron", corpus: str = "orchid" ) -> List[Tuple[str, str]]: _corpus = corpus _tag = [] if corpus == "orchid_ud": corpus = "orchid" if not words: return [] if engine == "perceptron": from .perceptron import tag as tag...
Part of Speech tagging function. :param list words: a list of tokenized words :param str engine: * unigram - unigram tagger * perceptron - perceptron tagger (default) * artagger - RDR POS tagger :param str corpus: * orchid - annotated Thai academic articles (default) ...
361,116
def fastaReadHeaders(fasta): headers = [] fileHandle = open(fasta, ) line = fileHandle.readline() while line != : assert line[-1] == if line[0] == : headers.append(line[1:-1]) line = fileHandle.readline() fileHandle.close() return headers
Returns a list of fasta header lines, excluding
361,117
def do_dock6_flexible(self, ligand_path, force_rerun=False): log.debug(.format(self.id)) ligand_name = os.path.basename(ligand_path).split()[0] in_name = op.join(self.dock_dir, "{}_{}_flexdock.in".format(self.id, ligand_name)) out_name = op.join(self.dock_dir, "{}_{}_flexdock.o...
Dock a ligand to the protein. Args: ligand_path (str): Path to ligand (mol2 format) to dock to protein force_rerun (bool): If method should be rerun even if output file exists
361,118
def get_tile_geometry(path, origin_espg, tolerance=500): with rasterio.open(path) as src: b = src.bounds tile_shape = Polygon([(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3]), (b[0], b[1])]) tile_geojson = mapping(tile_shape) image = src.read(1) ...
Calculate the data and tile geometry for sentinel-2 tiles
361,119
def png_data_uri(self, **kw): return writers.as_png_data_uri(self.matrix, self._version, **kw)
\ Converts the QR Code into a PNG data URI. Uses the same keyword parameters as the usual PNG serializer. :rtype: str
361,120
def srbt(bt_address, pkts, inter=0.1, *args, **kargs): if "port" in kargs: s = conf.BTsocket(bt_address=bt_address, port=kargs.pop("port")) else: s = conf.BTsocket(bt_address=bt_address) a, b = sndrcv(s, pkts, inter=inter, *args, **kargs) s.close() return a, b
send and receive using a bluetooth socket
361,121
def paste(self, key, data): data_gen = self._get_paste_data_gen(key, data) self.grid.actions.paste(key[:2], data_gen, freq=1000) self.main_window.grid.ForceRefresh()
Pastes data into grid Parameters ---------- key: 2-Tuple of Integer \tTop left cell data: String or wx.Bitmap \tTab separated string of paste data \tor paste data image
361,122
def send_audio(self, url, name, **audioinfo): return self.client.api.send_content(self.room_id, url, name, "m.audio", extra_information=audioinfo)
Send a pre-uploaded audio to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-audio for audioinfo Args: url (str): The mxc url of the audio. name (str): The filename of the audio. audioinfo (): Extra information about the audio.
361,123
def country_bank_code(self): entry = registry.get().get(self.compact) if entry: return entry.get()
str or None: The country specific bank-code associated with the BIC.
361,124
def fromcols(selection, n_sessions, eqdata, **kwargs): _constfeat = kwargs.get(, True) _outcols = [] if _constfeat else [] _n_rows = len(eqdata.index) for _col in selection: _outcols += map(partial(_concat, strval= + _col), range(-n_sessions + 1, 1)) _features = pd.DataFrame(index=eqdat...
Generate features from selected columns of a dataframe. Parameters ---------- selection : list or tuple of str Columns to be used as features. n_sessions : int Number of sessions over which to create features. eqdata : DataFrame Data from which to generate feature set. Mus...
361,125
def intern(self, sym: sym.Symbol, var: Var, force: bool = False) -> Var: m: lmap.Map = self._interns.swap(Namespace._intern, sym, var, force=force) return m.entry(sym)
Intern the Var given in this namespace mapped by the given Symbol. If the Symbol already maps to a Var, this method _will not overwrite_ the existing Var mapping unless the force keyword argument is given and is True.
361,126
def _reflect_table(self): with self.db.lock: try: self._table = SQLATable(self.name, self.db.metadata, schema=self.db.schema, autoload=True) ex...
Load the tables definition from the database.
361,127
def get_fit_auto(self, CentralFreq, MaxWidth=15000, MinWidth=500, WidthIntervals=500, MakeFig=True, show_fig=True, silent=False): MinTotalSumSquaredError = _np.infty for Width in _np.arange(MaxWidth, MinWidth - WidthIntervals, -WidthIntervals): try: OmegaTrap, A, Gam...
Tries a range of regions to search for peaks and runs the one with the least error and returns the parameters with the least errors. Parameters ---------- CentralFreq : float The central frequency to use for the fittings. MaxWidth : float, optional The ma...
361,128
def Serialize(self, writer): writer.WriteUInt32(self.Version) writer.WriteUInt64(self.Services) writer.WriteUInt32(self.Timestamp) writer.WriteUInt16(self.Port) writer.WriteUInt32(self.Nonce) writer.WriteVarString(self.UserAgent) writer.WriteUInt32(self.S...
Serialize object. Args: writer (neo.IO.BinaryWriter):
361,129
def set_ext_param(self, ext_key, param_key, val): if not self.extensions[ext_key]: self.extensions[ext_key] = defaultdict(lambda: None) self.extensions[ext_key][param_key] = val
Set the provided parameter in a set of extension parameters.
361,130
def post_message(name, channel, from_name, message, api_key=None, icon=None): ret = {: name, : {}, : False, : } if __opts__[]: ret[] = .format(message) ret[] = None ...
Send a message to a Slack channel. .. code-block:: yaml slack-message: slack.post_message: - channel: '#general' - from_name: SuperAdmin - message: 'This state was executed successfully.' - api_key: peWcBiMOS9HrZG15peWcBiMOS9HrZG15 The followi...
361,131
def managed(name, peers=None, servers=None): edge01.nrt04netntp_|-netntp_example_|-netntp_example_|-managedcommentNTP servers already configured as needed.namenetntp_examplestart_time12:45:24.056659durationchangespeersremoved192.168.0.2192.168.0.3added192.168.0.1172.17.17.1result ret = _default_ret(name) ...
Manages the configuration of NTP peers and servers on the device, as specified in the state SLS file. NTP entities not specified in these lists will be removed whilst entities not configured on the device will be set. SLS Example: .. code-block:: yaml netntp_example: netntp.managed: ...
361,132
def gauge(name, value, rate=1, tags=None): client().gauge(name, value, rate, tags)
Set the value for a gauge. >>> import statsdecor >>> statsdecor.gauge('my.metric', 10)
361,133
def get_file(self, filename): log.debug(, self.name, self.name, filename) try: blob = self.repo.head.commit.tree/filename return blob.data_stream except KeyError as err: raise GitError(err)
Get a file from the repo. Returns a file-like stream with the data.
361,134
def process_reply(self, reply, status=None, description=None): return self.__process_reply(reply, status, description)
Re-entry for processing a successful reply. Depending on how the ``retxml`` option is set, may return the SOAP reply XML or process it and return the Python object representing the returned value. @param reply: The SOAP reply envelope. @type reply: I{bytes} @param statu...
361,135
def _folder_get_content_iter(self, folder_key=None): lookup_params = [ {: , : }, {: , : } ] for param in lookup_params: more_chunks = True chunk = 0 while more_chunks: chunk += 1 content = self...
Iterator for api.folder_get_content
361,136
def notify_dispatch_request(self, request): if isinstance(request, Put) and request.path[0] == self.mri: self, attribute_name)
Will be called when a context passed to a hooked function is about to dispatch a request
361,137
def can_view(self, user=None, access_code=None): s user if user == self.invoice.user: return True if user.is_staff: return True if self.invoice.user.attendee.access_code == access_code: return True return False
Returns true if the accessing user is allowed to view this invoice, or if the given access code matches this invoice's user's access code.
361,138
def transfer(self, rights_assignment_data=None, *, from_user, to_user, rights_assignment_format=): rights_assignment = RightsAssignment.from_data( rights_assignment_data or {}, plugin=self.plugin) transfer_payload = rights_assignment._to_format( ...
Transfer this Right to another owner on the backing persistence layer. Args: rights_assignment_data (dict): Model data for the resulting :class:`~.RightsAssignment` from_user (any, keyword): A user based on the model specified by the persistence l...
361,139
def _run_suite(self, test_suite): tests_results = [] for testcase in test_suite: testcase_name = testcase.config.get("name") logger.log_info("Start to run testcase: {}".format(testcase_name)) result = self.unittest_runner.run(testcase) tests_res...
run tests in test_suite Args: test_suite: unittest.TestSuite() Returns: list: tests_results
361,140
def _open(self, filename): if filename.endswith(): if six.PY3: self._fp = bz2.open(filename, mode=, encoding=) else: self._fp = bz2.BZ2File(filename) else: self._fp = open(filename) line = self._fp.readline() i...
Open the input file. Set self._fp to point to it. Read the first line of parameters. @param filename: A C{str} filename containing JSON BLAST records. @raise ValueError: if the first line of the file isn't valid JSON, if the input file is empty, or if the JSON does not contain an ...
361,141
def from_pint(cls, arr, unit_registry=None): p_units = [] for base, exponent in arr._units.items(): bs = convert_pint_units(base) p_units.append("%s**(%s)" % (bs, Rational(exponent))) p_units = "*".join(p_units) if isinstance(arr.magnitude, np.ndarray): ...
Convert a Pint "Quantity" to a unyt_array or unyt_quantity. Parameters ---------- arr : Pint Quantity The Quantity to convert from. unit_registry : yt UnitRegistry, optional A yt unit registry to use in the conversion. If one is not supplied, the defa...
361,142
def iterable_validator(iterable_type, member_type): def _validate_tuple(instance, attribute, value): if not isinstance(value, iterable_type): raise TypeError(.format(name=attribute.name, type=iterable_type)) for member in value: if not isinstance(memb...
Validator for ``attrs`` that performs deep type checking of iterables.
361,143
def make_twitter_request(url, user_id, params={}, request_type=): if request_type == "GET": return requests.get(url, auth=get_twitter_auth(user_id), params=params) elif request_type == "POST": return requests.post(url, auth=get_twitter_auth(user_id), params=params)
Generically make a request to twitter API using a particular user's authorization
361,144
def append_child(self, name, child): temp = ArTree(name, child) self._array.append(temp) return temp
Append new child and return it.
361,145
def clean_streak(image, stat="pmode1", maxiter=15, sigrej=2.0, lower=None, upper=None, binwidth=0.3, mask=None, rpt_clean=0, atol=0.01, verbose=True): try: from stsci.imagestats import ImageStats except ImportError: ImageStats = None if mask is no...
Apply destriping algorithm to input array. Parameters ---------- image : `StripeArray` object Arrays are modifed in-place. stat : str Statistics for background computations (see :py:func:`clean` for more details) mask : `numpy.ndarray` Mask array. Pixels with zero ...
361,146
def on_message(self, msg=None): if msg is None: try: msg = self.ws.recv() except Exception as e: self.subscriber.on_message_error( % str(e)) self.disconnect() return False if not msg: ...
Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket.
361,147
def count(self): request_params = dict(self.request_params) request_url = str(self.request_url) request_params[] = 0 result = self.do_http_request( , request_url, data=request_params, custom_header=str(self.etiquette) ).js...
This method retrieve the total of records resulting from a given query. This attribute can be used compounded with query, filter, sort, order and facet methods. Examples: >>> from crossref.restful import Works >>> Works().query('zika').count() 3597 ...
361,148
def font(self): defRPr = self._element.defRPr font = Font(defRPr) return font
The |Font| object that provides access to the text properties for these data labels, such as bold, italic, etc.
361,149
def convert_from_file(file): if isinstance(file, six_string_types): with open(file, ) as f: return _internal_convert(f) else: return _internal_convert(file)
Reads the content of file in IDX format, converts it into numpy.ndarray and returns it. file is a file-like object (with read() method) or a file name.
361,150
def _flatten_beam_dim(tensor): shape = _shape_list(tensor) shape[0] *= shape[1] shape.pop(1) return tf.reshape(tensor, shape)
Reshapes first two dimensions in to single dimension. Args: tensor: Tensor to reshape of shape [A, B, ...] Returns: Reshaped tensor of shape [A*B, ...]
361,151
def _get_fault_type_dummy_variables(self, rup): Fn, Fr = 0, 0 if rup.rake >= -112.5 and rup.rake <= -67.5: Fn = 1 elif rup.rake >= 22.5 and rup.rake <= 157.5: Fr = 1 return Fn, Fr
The original classification considers four style of faulting categories (normal, strike-slip, reverse-oblique and reverse).
361,152
def _generate_ccitt_header(self, data): if not self.decode_parms: raise ValueError("/CCITTFaxDecode without /DecodeParms") if self.decode_parms[0].get("/K", 1) < 0: ccitt_group = 4 else: ccitt_group = 3 black_is_one = sel...
Construct a CCITT G3 or G4 header from the PDF metadata
361,153
def _ast_op_concat_to_code(self, opr, *, ignore_whitespace, **kwargs): hoist_target = OP_CONCAT if ignore_whitespace else OP_WS_CONCAT operands = self._hoist_operands(opr.operands, lambda t: isinstance(t, OptreeNode) and t.opnode.operator is hoist_target) lines = ["concatenation(["] for op in oper...
Convert an AST concatenate op to python source code.
361,154
def copy_graph(subject, existing_graph): new_graph = rdflib.Graph() for predicate, object_ in existing_graph.predicate_objects(): new_graph.add((subject, predicate, object_)) return new_graph
Function takes a subject and an existing graph, returns a new graph with all predicate and objects of the existing graph copied to the new_graph with subject as the new subject Args: subject(rdflib.URIRef): A URIRef subject existing_graph(rdflib.Graph): A rdflib.Graph Returns: ...
361,155
def check_visitors(cls): for name in dir(cls): if name.startswith("visit_"): if name[6:] not in CLASS_NAMES: raise Exception(u"Method {} doesn't correspond to a node class".format(name)) return cls
Check that a checker's visitors are correctly named. A checker has methods named visit_NODETYPE, but it's easy to mis-name a visit method, and it will never be called. This decorator checks the class to see that all of its visitors are named after an existing node class.
361,156
def metricCompute(self, sensorToBody, bodyToSpecificObject): overlaps = self.metricConnections.computeActivity({ "bodyToSpecificObject": bodyToSpecificObject, "sensorToBody": sensorToBody, }) self.activeMetricSegments = np.where(overlaps >= 2)[0] self.activeCells = np.unique( sel...
Compute the "sensor's location relative to a specific object" from the "body's location relative to a specific object" and the "sensor's location relative to body" @param sensorToBody (numpy array) Active cells of a single module that represents the sensor's location relative to t...
361,157
def drop_debug_privileges(cls, bIgnoreExceptions = False): try: cls.drop_privileges(win32.SE_DEBUG_NAME) return True except Exception: if not bIgnoreExceptions: raise return False
Drops debug privileges. This may be needed to avoid being detected by certain anti-debug tricks. @type bIgnoreExceptions: bool @param bIgnoreExceptions: C{True} to ignore any exceptions that may be raised when dropping debug privileges. @rtype: bool @retu...
361,158
def _handle_magic_exception(self, mod, exc): klass = getattr(mod, , None) if klass and isinstance(exc, klass): mod.module.fail_json(**exc.results)
Beginning with Ansible >2.6, some modules (file.py) install a sys.excepthook which is a closure over AnsibleModule, redirecting the magical exception to AnsibleModule.fail_json(). For extra special needs bonus points, the class is not defined in module_utils, but is defined in the modul...
361,159
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_tx_ls_rjt(self, **kwargs): config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_interface") config = fcoe_get_interface output = ET.SubElement(fcoe_get_interface, "output") fcoe_intf_list = ET.SubE...
Auto Generated Code
361,160
def _process_data_var(string): key, var = string.split("<-") if "structure" in var: var, dim = var.replace("structure(", "").replace(",", "").split(".Dim") dtype = float var = var.replace("c(", "").replace(")", "").strip().split() dim = dim.replace("=", "").replace(...
Transform datastring to key, values pair. All values are transformed to floating point values. Parameters ---------- string : str Returns ------- Tuple[Str, Str] key, values pair
361,161
def configure(self, options, config): log.debug("Configuring plugins") self.config = config cfg = PluginProxy(, self._plugins) cfg(options, config) enabled = [plug for plug in self._plugins if plug.enabled] self.plugins = enabled self.sort() log.d...
Configure the set of plugins with the given options and config instance. After configuration, disabled plugins are removed from the plugins list.
361,162
def total_reads_from_grabix(in_file): gbi_file = _get_grabix_index(in_file) if gbi_file: with open(gbi_file) as in_handle: next(in_handle) num_lines = int(next(in_handle).strip()) assert num_lines % 4 == 0, "Expected lines to be multiple of 4" return num_li...
Retrieve total reads in a fastq file from grabix index.
361,163
def determine_min_cell(disordered_structure): def lcm(n1, n2): return n1 * n2 / gcd(n1, n2) mag_species_order_parameter = {} mag_species_occurrences = {} for idx, site in enumerate(disordered_structure): if not site.is_ordered: ...
Determine the smallest supercell that is able to enumerate the provided structure with the given order parameter
361,164
def defaultStorable(self, python_type=None, storable_type=None, version=None, **kwargs): if python_type is None: python_type = lookup_type(storable_type) if self.verbose: print(.format(python_type)) self.storables.registerStorable(default_storable(python_type, \ ...
Generate a default storable instance. Arguments: python_type (type): Python type of the object. storable_type (str): storable type name. version (tuple): version number of the storable handler. Returns: StorableHandler: storable instance. Ex...
361,165
def oauth_register(form): if form.validate(): data = form.to_dict() if not data.get(): data[] = user = register_user(**data) if not data[]: user.password = None _datastore.commit() return user
Register user if possible. :param form: A form instance. :returns: A :class:`invenio_accounts.models.User` instance.
361,166
def concat_ws(sep, *cols): sc = SparkContext._active_spark_context return Column(sc._jvm.functions.concat_ws(sep, _to_seq(sc, cols, _to_java_column)))
Concatenates multiple input string columns together into a single string column, using the given separator. >>> df = spark.createDataFrame([('abcd','123')], ['s', 'd']) >>> df.select(concat_ws('-', df.s, df.d).alias('s')).collect() [Row(s=u'abcd-123')]
361,167
def sget_timestamp(self, cycle, step, dataset_number=None): dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return cycle_index_header = self.headers_normal.cycle_index_txt timestamp_h...
Returns timestamp for cycle, step. Convinience function; same as issuing dfdata[(dfdata[cycle_index_header] == cycle) & (dfdata[step_index_header] == step)][timestamp_header] Args: cycle: cycle number step: step number dataset_number: the...
361,168
def update(self, *data, **kwargs) -> : logger.debug(f) model_cls = repo_factory.get_model(self.__class__) repository = repo_factory.get_repository(self.__class__) try: self._update_data(*data, **kwargs) self._validate...
Update a Record in the repository. Also performs unique validations before creating the entity. Supports both dictionary and keyword argument updates to the entity:: dog.update({'age': 10}) dog.update(age=10) :param data: Dictionary of values to be updated for the en...
361,169
def _parse_json(self, doc, exactly_one): places = doc.get(, []) self._raise_for_error(doc) if not len(places): return None def parse_code(place): latitude = place.get(, None) longitude = place.get(, None) if latitude ...
Parse JSON response body.
361,170
def is_integer(value, coerce_value = False, minimum = None, maximum = None, base = 10, **kwargs): try: value = validators.integer(value, coerce_value = coerce_value, ...
Indicate whether ``value`` contains a whole number. :param value: The value to evaluate. :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to whole number. If ``False``, will only return ``True`` if ``value`` is already a whole number (regardless of type). Defaults...
361,171
def add_incomplete_penetrance(genes, alias_genes, hpo_lines): LOG.info("Add incomplete penetrance info") for hgnc_symbol in get_incomplete_penetrance_genes(hpo_lines): for hgnc_id in get_correct_ids(hgnc_symbol, alias_genes): genes[hgnc_id][] = True
Add information of incomplete penetrance
361,172
def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception() ret = [] for ri in r: ret.append(delete_object(ri[], **api_opts)) ...
Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call inf...
361,173
def subdivide_with(self, branches, join_function, name=): return _subdivide_context(self, branches, join_function, name)
Branches this pretty tensor and uses an explicit join function. This should be used in a with statement, for example to fork and join with a sum: with pt.subdivide_with(2, tf.add_n) as [a, b]: a... b... Args: branches: The number of branches. join_function: A funct...
361,174
def initialize(): try: import multiprocessing ncpus = .format(multiprocessing.cpu_count()) except (ImportError, NotImplementedError): ncpus = parser = argparse.ArgumentParser(description="Document a program or library written in modern Fortran. Any command-line options ov...
Method to parse and check configurations of FORD, get the project's global documentation, and create the Markdown reader.
361,175
def sort(polylines): for n, c in enumerate(polylines): l = len(c) if l > 2: mid = c.mean(axis=0) distV = (c - mid) dists = norm(distV, axis=-1) firstI = np.argmax(dists) sign = np.sign(distV[firstI]) ...
sort points within polyline p0-p1-p2...
361,176
def show(what=, calc_id=-1, extra=()): datadir = datastore.get_datadir() if what == : if not os.path.exists(datadir): return rows = [] for calc_id in datastore.get_calc_ids(datadir): try: ds = util.read(calc_id) oq = ds[] ...
Show the content of a datastore (by default the last one).
361,177
def is_module_has_decorated(path,decorator_module,decorator_name): expression = .format(decorator_module,decorator_name) with open(path) as f: module_source = f.read() regex_result = re.compile(expression).findall(module_source) return len(regex_result) > 0
Finds out if a python module uses a given decorator. Args : loaded_module : The loaded module to be scanned. decorator_module : Then name of the module defining the decorator. decorator_name : The name of the decorator.
361,178
def val_to_bin(edges, x): ibin = np.digitize(np.array(x, ndmin=1), edges) - 1 return ibin
Convert axis coordinate to bin index.
361,179
def _gen_packet_setcolor(self, sequence, hue, sat, bri, kel, fade): hue = min(max(hue, HUE_MIN), HUE_MAX) sat = min(max(sat, SATURATION_MIN), SATURATION_MAX) bri = min(max(bri, BRIGHTNESS_MIN), BRIGHTNESS_MAX) kel = min(max(kel, TEMP_MIN), TEMP_MAX) reserved1 = pack("<B...
Generate "setcolor" packet payload.
361,180
def rename(self, old_key, new_key): assert new_key not in self assert old_key != new_key file_ = self[old_key] old_data = self.filesmap[old_key] obj = ObjectVersion.create( bucket=self.bucket, key=new_key, _file_id=file_.obj.file_id ...
Rename a file. :param old_key: Old key that holds the object. :param new_key: New key that will hold the object. :returns: The object that has been renamed.
361,181
def push(self): if self.comm is None: raise Exception() diff = self.renderer.diff(self) self.comm.send(diff)
Pushes updated plot data via the Comm.
361,182
def generate_jobs_pending_widget(): pbar = widgets.IntProgress( value=0, min=0, max=50, description=, orientation=, layout=widgets.Layout(max_width=)) pbar.style.bar_color = pbar_current = widgets.Label( value=str(pbar.value), layout=widgets.Layout(min_...
Generates a jobs_pending progress bar widget.
361,183
def ngram_count(text,N=1,keep_punct=False): if not keep_punct: text = re.sub(,,text.upper()) count = {} for i in range(len(text)-N+1): c = text[i:i+N] if c in count: count[c] += 1 else: count[c] = 1.0 return count
if N=1, return a dict containing each letter along with how many times the letter occurred. if N=2, returns a dict containing counts of each bigram (pair of letters) etc. There is an option to remove all spaces and punctuation prior to processing
361,184
def add_files(self, files): if isinstance(files, basestring): files = [files] zip_file = None if self.zip_: zip_filename = self._get_zip_filename() zip_file = ZipFile(zip_filename, ) for filename in files: if os.path.isdir(filen...
Add files and/or folders to transfer. If :class:`Transfer.compress` attribute is set to ``True``, files will get packed into a zip file before sending. :param files: Files or folders to send :type files: str, list
361,185
def multi_evaluate(self, x, out=None): if out is None: out = _np.empty(len(x)) else: assert len(out) == len(x) for i, point in enumerate(x): out[i] = self.evaluate(point) return out
Evaluate log of the density to propose ``x``, namely log(q(x)) for each row in x. :param x: Matrix-like array; the proposed points. Expect i-th accessible as ``x[i]``. :param out: Vector-like array, length==``len(x)``, optional; If provided, th...
361,186
def _get_netengine_backend(self): backend_class_name = self.backend.split()[-1] backend_path = self.backend.lower() module = import_module(backend_path) BackendClass = getattr(module, backend_class_name) return BackendClass
returns the netengine backend specified in self.backend for internal use only
361,187
def visit_yieldfrom(self, node): yi_val = (" " + node.value.accept(self)) if node.value else "" expr = "yield from" + yi_val if node.parent.is_statement: return expr return "(%s)" % (expr,)
Return an astroid.YieldFrom node as string.
361,188
def _reset_timeout(self): if self._timeout: self._timeout.cancel() self._timeout = self.loop.call_later(self.client.timeout, self.transport.close)
Reset timeout for date keep alive.
361,189
def _request(self, method, path, server=None, **kwargs): while True: next_server = server or self._get_server() try: response = self.server_pool[next_server].request( method, path, username=self.username, password=self.password, schema=self.sc...
Execute a request to the cluster A server is selected from the server pool.
361,190
def stop(self): if self.is_running(): log.info("Stopping Dynamips process PID={}".format(self._process.pid)) yield from DynamipsHypervisor.stop(self) yield from asyncio.sleep(0.01) try: yield from wait_for_proces...
Stops the Dynamips hypervisor process.
361,191
def discover(self, start, top_level_directory=None, pattern=): logger.debug() if os.path.isdir(start): start_directory = start return self.discover_by_directory( start_directory, top_level_directory=top_level_directory, pattern=pattern) ...
Do test case discovery. This is the top-level entry-point for test discovery. If the ``start`` argument is a drectory, then ``haas`` will discover all tests in the package contained in that directory. If the ``start`` argument is not a directory, it is assumed to be a package ...
361,192
def plot_bargraph (self, data, cats=None, pconfig=None): from multiqc.plots import bargraph if pconfig is None: pconfig = {} return bargraph.plot(data, cats, pconfig)
Depreciated function. Forwards to new location.
361,193
def _ssl_PRF(secret, seed, req_len): if req_len > 416: warning("_ssl_PRF() is not expected to provide more than 416 bytes") return "" d = [b"A", b"B", b"C", b"D", b"E", b"F", b"G", b"H", b"I", b"J", b"K", b"L", b"M", b"N", b"O", b"P", b"Q", b"R", b"S", b"T", b"U", b"V", b"W", b"...
Provides the implementation of SSLv3 PRF function: SSLv3-PRF(secret, seed) = MD5(secret || SHA-1("A" || secret || seed)) || MD5(secret || SHA-1("BB" || secret || seed)) || MD5(secret || SHA-1("CCC" || secret || seed)) || ... req_len should not be more than 26 x 16 = 416.
361,194
def feature_scaling(x, xmin, xmax, a=0, b=1): return a + float(x - xmin) * (b - a) / (xmax - xmin)
Generalized feature scaling (useful for variable error correction rate calculation)
361,195
def get_authenticated_subjects(cert_pem): if isinstance(cert_pem, str): cert_pem = cert_pem.encode() return d1_common.cert.subjects.extract_subjects(cert_pem)
Return primary subject and set of equivalents authenticated by certificate. - ``cert_pem`` can be str or bytes
361,196
def run(self): while True: try: self._poll_for_update() except RuntimeError as error: if error.message == : _LOG.debug( ) time.sleep(0.1) else: _LOG.exception(, err...
Call self._poll_for_update() in a loop and handle errors.
361,197
def atlasdb_get_zonefiles_by_name(name, max_index=None, con=None, path=None): ret = [] with AtlasDBOpen(con=con, path=path) as dbcon: sql = args = (name,) if max_index: sql += args += (max_index,) sql += cur = dbcon.cursor() res...
Look up the sequence of zone file records by name, optionally up to a specific zonefile index Returns [{'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present': ..., 'tried_storage': ...}], in blockchain order
361,198
def _loadFromRow(self, result, fields, cursor): position = 0 for elem in fields: value = result[position] valueType = cursor.description[position][1] if hasattr(self._dbModule, ) and \ valueType == self._dbModule.BOOLEAN and \ ...
Load from a database row, described by fields. ``fields`` should be the attribute names that will be set. Note that userclasses will be created (but not loaded).
361,199
def save(self): super(Samples, self).save() if self.metadata is not None: self.metadata.save()
Persist changes on this Samples object back to the One Codex server along with any changes on its metadata (if it has any).