Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
350,100
def all_status(self): laundry_rooms = {} for room in self.hall_to_link: laundry_rooms[room] = self.parse_a_hall(room) return laundry_rooms
Return names, hall numbers, and the washers/dryers available for all rooms in the system >>> all_laundry = l.all_status()
350,101
def _do_bulk_write_command( namespace, operation, command, docs, check_keys, opts, ctx): if ctx.sock_info.max_wire_version > 5: return _do_batched_op_msg( namespace, operation, command, docs, check_keys, opts, ctx) return _do_batched_write_command( namespace, operation, ...
Bulk write commands entry point.
350,102
def read_line(self, fid): lin = while lin[0] == : lin = fid.readline().strip() if lin == : return lin return lin
Read a line from a file string and check it isn't either empty or commented before returning.
350,103
def set_alpha(self, alpha): self.transparency = alpha self.diffuse[3] = alpha self.ambient[3] = alpha self.specular[3] = alpha self.emissive[3] = alpha
Set alpha/last value on all four lighting attributes.
350,104
def U(data, bits=None, endian=None, target=None): return globals()[ % _get_bits(bits, target)](data, endian=endian, target=target)
Unpack an unsigned pointer for a given target. Args: data(bytes): The data to unpack. bits(:class:`pwnypack.target.Target.Bits`): Override the default word size. If ``None`` it will look at the word size of ``target``. endian(:class:`~pwnypack.target.Target.Endian`):...
350,105
def _update_texttuple(self, x, y, s, cs, d): pos = (x, y, cs) for i, (old_x, old_y, old_s, old_cs, old_d) in enumerate(self.value): if (old_x, old_y, old_cs) == pos: self.value[i] = (old_x, old_y, s, old_cs, d) return raise ValueError("No text...
Update the text tuple at `x` and `y` with the given `s` and `d`
350,106
def __change_inferencing_mode(self, inferencing_mode): self.__encoder_decoder_controller.decoder.opt_params.inferencing_mode = inferencing_mode self.__encoder_decoder_controller.encoder.opt_params.inferencing_mode = inferencing_mode self.__retrospective_encoder.opt_params.inferencin...
Change dropout rate in Encoder/Decoder. Args: dropout_rate: The probalibity of dropout.
350,107
def isContained(bbox1, bbox2, tol=TOLERANCE): if bbox1[0] > bbox2[0] - tol and bbox1[1] > bbox2[1] - tol: if bbox1[2] < bbox2[2] + tol and bbox1[3] < bbox2[3] + tol: return True return False
:param bbox1: bounding box of the first rectangle :param bbox2: bounding box of the second rectangle :return: True if bbox1 is contaned in bbox2
350,108
def read_file(filepath: str) -> str: filepath = os.path.expanduser(filepath) with open(filepath) as opened_file: file_read = opened_file.read() return file_read
Read a file and return it as a string
350,109
def _get_function_matches(attributes_a, attributes_b, filter_set_a=None, filter_set_b=None): if filter_set_a is None: filtered_attributes_a = {k: v for k, v in attributes_a.items()} else: filtered_attributes_a = {k: v for k, v in attributes_a.items() if k in fil...
:param attributes_a: A dict of functions to their attributes :param attributes_b: A dict of functions to their attributes The following parameters are optional. :param filter_set_a: A set to limit attributes_a to the functions in this set. :param filter_set_b: A set to limi...
350,110
def derivative(self, t, n=1): angle = radians(self.theta + t*self.delta) phi = radians(self.rotation) rx = self.radius.real ry = self.radius.imag k = (self.delta*2*pi/360)**n if n % 4 == 0 and n > 0: return rx*cos(phi)*cos(angle) - ry*sin(phi)*sin(...
returns the nth derivative of the segment at t.
350,111
def get_catalog_path(catalog_id, catalogs_dir=CATALOGS_DIR, fmt="json"): base_path = os.path.join(catalogs_dir, "catalog", catalog_id) if fmt == "json": return os.path.join(base_path, "data.json") elif fmt == "xlsx": return os.path.join(base_path, "catalog.xlsx") else: rais...
Genera el path estándar de un catálogo en un filesystem.
350,112
def _downgrade_v2(op): op.drop_index() op.drop_index() with op.batch_alter_table() as batch_op: batch_op.drop_column() op.create_index(, table_name=, columns=[]) op.create_index(, table_name=, ...
Downgrade assets db by removing the 'auto_close_date' column.
350,113
def as_string(self, name=None): sas = self._change_schema(streamsx.topology.schema.CommonSchema.String, , name)._layout() sas.oport.operator.sl = _SourceLocation(_source_info(), ) return sas
Declares a stream converting each tuple on this stream into a string using `str(tuple)`. The stream is typed as a :py:const:`string stream <streamsx.topology.schema.CommonSchema.String>`. If this stream is already typed as a string stream then it will be returned (with no additional pr...
350,114
def CallFlow(self, flow_name=None, next_state=None, request_data=None, client_id=None, base_session_id=None, **kwargs): client_id = client_id or self.runner_args.client_id state = rdf_flow_ru...
Creates a new flow and send its responses to a state. This creates a new flow. The flow may send back many responses which will be queued by the framework until the flow terminates. The final status message will cause the entire transaction to be committed to the specified state. Args: flow_nam...
350,115
def read_hopopt(self, length, extension): if length is None: length = len(self) _next = self._read_protos(1) _hlen = self._read_unpack(1) hopopt = dict( next=_next, length=(_hlen + 1) * 8, ) options = self._read_hop...
Read IPv6 Hop-by-Hop Options. Structure of HOPOPT header [RFC 8200]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + ...
350,116
def _get_val(other): assert isinstance(other, (numbers.Number, SymbolNUMBER, SymbolCONST)) if isinstance(other, SymbolNUMBER): return other.value if isinstance(other, SymbolCONST): return other.expr.value return other
Given a Number, a Numeric Constant or a python number return its value
350,117
def encode_offset_commit_request(cls, client_id, correlation_id, group, payloads): grouped_payloads = group_by_topic_and_partition(payloads) message = [] message.append(cls._encode_message_header(client_id, correlation_id, ...
Encode some OffsetCommitRequest structs Arguments: client_id: string correlation_id: int group: string, the consumer group you are committing offsets for payloads: list of OffsetCommitRequest
350,118
def _project_to_part_level(hist: Hist, outliers_removal_axis: OutliersRemovalAxis) -> Hist: import ROOT if isinstance(hist, (ROOT.TH2, ROOT.TH3)): projection_information: Dict[str, Any] = {} output_object = _OutputObject(None) projector = projectors.HistProjector( o...
Project the input histogram to the particle level axis. Args: hist: Histogram to check for outliers. outliers_removal_axis: Axis along which outliers removal will be performed. Usually the particle level aixs. Returns: The histogram to check for outliers.
350,119
def next_offsets(self): resume_bytes = self._resume() with self._meta_lock: if self._chunk_num >= self._total_chunks: return None, resume_bytes if self._chunk_size == -1 and self._src_block_list is not None: num_bytes = self._src_...
Retrieve the next offsets :param Descriptor self: this :rtype: Offsets :return: download offsets
350,120
def _generate_recommendation(self, query_analysis, db_name, collection_name): index_rec = for query_field in query_analysis[]: if query_field[] is EQUIV_TYPE: if len(i...
Generates an ideal query recommendation
350,121
def _cs_path_exists(fspath): if not os.path.exists(fspath): return False abspath = os.path.abspath(fspath) directory, filename = os.path.split(abspath) return filename in os.listdir(directory)
Case-sensitive path existence check >>> sdist_add_defaults._cs_path_exists(__file__) True >>> sdist_add_defaults._cs_path_exists(__file__.upper()) False
350,122
def from_json(cls, data): assert in data, keys = (, , , ) for key in keys: if key not in data: data[key] = None data_type = DataTypeBase.from_json(data[]) ap = AnalysisPeriod.from_json(data[]) return cls(data_type, data[], ...
Create a header from a dictionary. Args: data: { "data_type": {}, //Type of data (e.g. Temperature) "unit": string, "analysis_period": {} // A Ladybug AnalysisPeriod "metadata": {}, // A dictionary of metadata }
350,123
def order(self): d = {} for (i, x) in enumerate(self): if x.is_gap: continue xid = x.component_id d[xid] = (i, x) xid = xid.rsplit(".", 1)[0] if xid not in d: d[xid] = (i, x) return d
Returns a dict with component_id => (i, agpline)
350,124
def fix_builtins(override_debug=False): override_dict = {} orig_print = None used_print = None if(__builtins__.__class__ is dict): builtins_dict = __builtins__ else: try: import builtins except ImportError: import __builtin__ as builtins ...
Activate the builtins compatibility.
350,125
def pass_times(self, latitude, longitude, altitude=None, number=None): schema = Schema({ Required(): All(Any(int, float), Range(min=-80, max=80)), Required(): All(Any(int, float), Range(min=-180, max=180)), : Any(None, All(Any(int, float), Range(min=0, max=1...
The next pass times of the ISS. :param latitude: latitude in degrees of location you want iss pass above :type latitude: float :param longitude: longitude in degrees of location you want iss pass above :type longitude: float :param altitude: altitude in meters of...
350,126
def deleteRating(self): url = "%s/deleteRating" % self.root params = { "f": "json", } return self._post(url, params, securityHandler=self._securityHandler, proxy_port=self._proxy_p...
Removes the rating the calling user added for the specified item (POST only).
350,127
def save_state(self, state): request = HTTPRequest( method="PUT", resource="activities/state", content=state.content, ) if state.content_type is not None: request.headers["Content-Type"] = state.content_type else: reque...
Save a state doc to the LRS :param state: State document to be saved :type state: :class:`tincan.documents.state_document.StateDocument` :return: LRS Response object with saved state as content :rtype: :class:`tincan.lrs_response.LRSResponse`
350,128
def ColorWithSaturation(self, saturation): h, s, l = self.__hsl return Color((h, saturation, l), , self.__a, self.__wref)
Create a new instance based on this one with a new saturation value. .. note:: The saturation is defined for the HSL mode. Parameters: :saturation: The saturation of the new color [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithSat...
350,129
def setOffPixmap(self, pixmap): pmap = QtGui.QPixmap(pixmap) self._offPixmap = pmap.scaled(self.width(), self.height(), QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)
Sets the off pixmap that will be used for this button to the given pixmap. This can be a QPixmap instance, or a string for where to load the pixmap from. :param pixmap | <QtGui.QPixmap> || <str>
350,130
def crop(self, height, width, center_i=None, center_j=None): color_im_crop = self.color.crop(height, width, center_i, center_j) depth_im_crop = self.depth.crop(height, width, center_i, center_j) return RgbdImage.from_color_and_depth(color_im_crop, depth_im_crop)
Crop the image centered around center_i, center_j. Parameters ---------- height : int The height of the desired image. width : int The width of the desired image. center_i : int The center height point at which to crop. If not specified, the...
350,131
def read(self, size=1024): data = self.fileobj.recv(size) if not data: self.flag_eof = True raise EOFError() return self.decoder.decode(data, final=False)
Read and return at most ``size`` characters from the pty. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed.
350,132
def create_datastore_from_json_schema(self, json_path, delete_first=0, path=None): data = load_json(json_path) self.create_datastore_from_dict_schema(data, delete_first, path=path)
For tabular data, create a resource in the HDX datastore which enables data preview in HDX from a JSON file containing a list of fields and types of form {'id': 'FIELD', 'type': 'TYPE'} and optionally a primary key. If path is not supplied, the file is first downloaded from HDX. Args: ...
350,133
def to_csv(self, path, mode=WRITE_MODE, dialect=, compression=None, newline=, **fmtparams): if in mode: newline = None with universal_write_open(path, mode=mode, compression=compression, newline=newline) as output: csv_...
Saves the sequence to a csv file. Each element should be an iterable which will be expanded to the elements of each row. :param path: path to write file :param mode: file open mode :param dialect: passed to csv.writer :param fmtparams: passed to csv.writer
350,134
def parse_mime_version(value): mime_version = MIMEVersion() if not value: mime_version.defects.append(errors.HeaderMissingRequiredValue( "Missing MIME version number (eg: 1.0)")) return mime_version if value[0] in CFWS_LEADER: token, value = get_cfws(value)...
mime-version = [CFWS] 1*digit [CFWS] "." [CFWS] 1*digit [CFWS]
350,135
def serialize(self, cls, record): return json.dumps(record, cls=self.encoder)
Serialize the record to JSON. cls unused in this implementation. >>> s = teststore() >>> s.serialize('tstoretest', {'id': '1', 'name': 'Toto'}) '{"id": "1", "name": "Toto"}'
350,136
def delete_admin_by_sis_id(self, sis_account_id, user_id, role): return self.delete_admin(self._sis_id(sis_account_id), user_id, role)
Remove an account admin role from a user for the account sis id.
350,137
def element_from_dict(parent, data, element): el = ET.SubElement(parent, element) el.text = data.pop(element) return el
Create ``element`` to ``parent`` and sets its value to data[element], which will be removed from the ``data``. :param parent: parent element :type parent: Element :param data: dictionary where data[element] is desired value :type data: dict(str, str) :param element: name of the new element ...
350,138
def _cosine(a, b): return 1. * len(a & b) / (math.sqrt(len(a)) * math.sqrt(len(b)))
Return the len(a & b) / len(a)
350,139
def get_scaled_cutout_wdht(self, x1, y1, x2, y2, new_wd, new_ht, method=): if method in (, ): shp = self.shape (view, (scale_x, scale_y)) = \ trcalc.get_scaled_cutout_wdht_view(shp, x1, y1, x2, y2, ...
Extract a region of the image defined by corners (x1, y1) and (x2, y2) and resample it to fit dimensions (new_wd, new_ht). `method` describes the method of interpolation used, where the default "basic" is nearest neighbor.
350,140
def get_dimensionality(structure, max_hkl=2, el_radius_updates=None, min_slab_size=5, min_vacuum_size=5, standardize=True, bonds=None): if standardize: structure = SpacegroupAnalyzer(structure). \ get_conventional_standard_structure() if no...
This method returns whether a structure is 3D, 2D (layered), or 1D (linear chains or molecules) according to the algorithm published in Gorai, P., Toberer, E. & Stevanovic, V. Computational Identification of Promising Thermoelectric Materials Among Known Quasi-2D Binary Compounds. J. Mater. Chem. A 2, 4...
350,141
def down(tag, sql, revision): alembic_command.downgrade( config=get_config(), revision=revision, sql=sql, tag=tag )
Downgrade to revision
350,142
def _get_updated_rows(self, auth, function): qps = [] for row in self._curs_pg: qps.append( { : , : , : row[] } ) return up...
Get rows updated by last update query * `function` [function] Function to use for searching (one of the search_* functions). Helper function used to fetch all rows which was updated by the latest UPDATE ... RETURNING id query.
350,143
def read_index(fn): index = None with open(fn, "rb") as i_file: if i_file.read(len(_CHECK_STRING)) != _CHECK_STRING: raise ValueError("{}: not a valid index file".format(fn)) index = pd.read_csv(io.StringIO( zlib.decompress(i_file.read()).decode(encoding="utf-8"), ...
Reads index from file. Args: fn (str): the name of the file containing the index. Returns: pandas.DataFrame: the index of the file. Before reading the index, we check the first couple of bytes to see if it is a valid index file.
350,144
def remove(self, rev, permanent=False): if not isinstance(rev, Revision): raise TypeError() if rev not in self: raise ValueError(.format(rev)) self._files.remove(rev) if not permanent: rev.changelist = self._connection.default
Removes a revision from this changelist :param rev: Revision to remove :type rev: :class:`.Revision` :param permanent: Whether or not we need to set the changelist to default :type permanent: bool
350,145
def critical_point(self, cp_override: CriticalPoint = None) -> Point: if not self.has_tip or cp_override == CriticalPoint.NOZZLE: cp_type = CriticalPoint.NOZZLE tip_length = 0.0 else: cp_type = CriticalPoint.TIP tip_length = self.current_tip_lengt...
The vector from the pipette's origin to its critical point. The critical point for a pipette is the end of the nozzle if no tip is attached, or the end of the tip if a tip is attached. If `cp_override` is specified and valid - so is either :py:attr:`CriticalPoint.NOZZLE` or :py:attr:`Cr...
350,146
def DEFINE_multi_float( name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
Registers a flag whose value can be a list of arbitrary floats. Use the flag on the command line multiple times to place multiple float values into the list. The 'default' may be a single float (which will be converted into a single-element list) or a list of floats. Args: name: A string, the flag name...
350,147
def prob_t(self, seq_p, seq_ch, t, pattern_multiplicity = None, return_log=False, ignore_gaps=True): seq_pair, multiplicity = self.compress_sequence_pair(seq_p, seq_ch, pattern_multiplicity=pattern_multiplicity, ignore_gaps=ignore_gaps) ret...
Compute the probability to observe seq_ch (child sequence) after time t starting from seq_p (parent sequence). Parameters ---------- seq_p : character array Parent sequence seq_c : character array Child sequence t : double Time (...
350,148
async def process_activity(self, req, auth_header: str, logic: Callable): activity = await self.parse_request(req) auth_header = auth_header or await self.authenticate_request(activity, auth_header) context = self.create_context(activity) return await self.run_middlew...
Processes an activity received by the bots web server. This includes any messages sent from a user and is the method that drives what's often referred to as the bots "Reactive Messaging" flow. :param req: :param auth_header: :param logic: :return:
350,149
def _emulated(self, timeout=None): tried.add(queue.name) if tried == self.all: raise else: return item, queue.name
Get the next message avaiable in the queue. :returns: The message and the name of the queue it came from as a tuple. :raises Empty: If there are no more items in any of the queues.
350,150
def POST_AUTH(self): userdata = self.database.users.find_one({"email": self.user_manager.session_email()}) if not userdata: raise web.notfound() msg = "" error = False data = web.input() if "save" in data: userdata, msg, error = self.s...
POST request
350,151
def getCmdOpts(self, text): off = 0 _, off = s_syntax.nom(text, off, s_syntax.whites) name, off = s_syntax.meh(text, off, s_syntax.whites) _, off = s_syntax.nom(text, off, s_syntax.whites) opts = {} args = collections.deque([synt for synt in self._cmd_syntax...
Use the _cmd_syntax def to split/parse/normalize the cmd line. Args: text (str): Command to process. Notes: This is implemented independent of argparse (et al) due to the need for syntax aware argument splitting. Also, allows different split per command ...
350,152
def hash_name(name, script_pubkey, register_addr=None): bin_name = b40_to_bin(name) name_and_pubkey = bin_name + unhexlify(script_pubkey) if register_addr is not None: name_and_pubkey += str(register_addr) return hex_hash160(name_and_pubkey)
Generate the hash over a name and hex-string script pubkey
350,153
def _execute(self, sql, opt=None, callno = 0): self._logger.debug("SQL: " + sql + " params: " + unicode(opt)) try: self._curs_pg.execute(sql, opt) except psycopg2.InternalError as exc: self._con_pg.rollback() ...
Execute query, catch and log errors.
350,154
def dispatch(self, *args, **kwargs): return super(EntryTrackback, self).dispatch(*args, **kwargs)
Decorate the view dispatcher with csrf_exempt.
350,155
def supports_heading_type(self, heading_type=None): from .osid_errors import IllegalState, NullArgument if not heading_type: raise NullArgument() if self._kwargs[] not in []: raise IllegalState() return heading_type in self.get_heading_types
Tests if the given heading type is supported. arg: heading_type (osid.type.Type): a heading Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not a ``HEADING`` raise: NullArgument - ``heading_type`` is ``...
350,156
def property(self, key, default=None): if key == : return self.name() elif key == : return self.dateStart() elif key == : return self.dateEnd() elif key == : return self.duration() elif key == : retur...
Returns the custom data that is stored on this object. :param key | <str> default | <variant> :return <variant>
350,157
def file_or_resource(fname=None): if fname is not None: filename = os.path.expanduser(fname) resource_package = opentargets_validator.__name__ resource_path = os.path.sep.join((, filename)) abs_filename = os.path.join(os.path.abspath(os.getcwd()), filename) \ ...
get filename and check if in getcwd then get from the package resources folder
350,158
def _tp_cache(func): cached = functools.lru_cache()(func) _cleanups.append(cached.cache_clear) @functools.wraps(func) def inner(*args, **kwds): try: return cached(*args, **kwds) except TypeError: pass return func(*args, **kwds) return inner
Internal wrapper caching __getitem__ of generic types with a fallback to original function for non-hashable arguments.
350,159
def session_preparation(self): self._test_channel_read() self.set_base_prompt() if self.secret: self.enable() else: self.asa_login() self.disable_paging(command="terminal pager 0") if self.allow_auto_change: try: ...
Prepare the session after the connection has been established.
350,160
def restore(self): try: for modname, mod in self._saved.items(): if mod is not None: sys.modules[modname] = mod else: try: del sys.modules[modname] except KeyError: ...
Restores the modules that the saver knows about into sys.modules.
350,161
def interpret_pixel_data(data, dc, pixel_array, invert=True): index_value = np.where(is_address_record(data))[0] + 1 index_value = index_value[is_value_record(data[index_value])] index_address = index_value - 1 address = get_address_record_address(data[index_address]) val...
Takes the pixel raw data and interprets them. This includes consistency checks and pixel/data matching. The data has to come from one double column only but can have more than one pixel bit (e.g. TDAC = 5 bit). Parameters ---------- data : numpy.ndarray The raw data words. dc : int ...
350,162
def _find_rankings(self, year): if not year: year = utils._find_year_for_season() page = self._pull_rankings_page(year) if not page: output = ("Cantable } weekly_rankings.append(rank_details) self._rankings[int(we...
Retrieve the rankings for each week. Find and retrieve all AP rankings for the requested year and combine them on a per-week basis. Each week contains information about the name, abbreviation, rank, movement, and previous rank for each team as well as the date and week number the result...
350,163
def get_config(config_file): def load(fp): try: return yaml.safe_load(fp) except yaml.YAMLError as e: sys.stderr.write(text_type(e)) sys.exit(1) if config_file == : return load(sys.stdin) if not os.path.exists(config_file): sys.stde...
Get configuration from a file.
350,164
def by_issn(issn): old_url = aleph.ALEPH_URL aleph.ALEPH_URL = NTK_ALEPH_URL records = aleph.getISSNsXML(issn, base="STK02") aleph.ALEPH_URL = old_url for record in records: marc = MARCXMLRecord(record) additional_info = { "222": marc.ge...
Query aleph for records with given `issn`. The lookup is directed to the NTK's Aleph. Args: issn (str): ISSN of the periodical. Returns: obj: :class:`Model` instances for each record.
350,165
def properties(self): properties = {: self._id} if self._name is not None: properties[] = self._name return properties
All compartment properties as a dict.
350,166
def transmit(self, payload, **kwargs): items_to_create, items_to_update, items_to_delete, transmission_map = self._partition_items(payload) self._prepare_items_for_delete(items_to_delete) prepared_items = {} prepared_items.update(items_to_create) prepared_items.update(it...
Transmit content metadata items to the integrated channel.
350,167
def to_cryptography_key(self): backend = _get_backend() if self._only_public: return backend._evp_pkey_to_public_key(self._pkey) else: return backend._evp_pkey_to_private_key(self._pkey)
Export as a ``cryptography`` key. :rtype: One of ``cryptography``'s `key interfaces`_. .. _key interfaces: https://cryptography.io/en/latest/hazmat/\ primitives/asymmetric/rsa/#key-interfaces .. versionadded:: 16.1.0
350,168
def to_fs_from_unicode(unic): if is_unicode(unic): try: string = unic.encode(FS_ENCODING) except (UnicodeError, TypeError): pass else: return string return unic
Return a byte string version of unic encoded using the file system encoding.
350,169
def _build_inheritance_chain(cls, bases, *names, merge=False): result = [] for name in names: maps = [] for base in bases: bmap = getattr(base, name, None) if bmap is not None: assert isinstance(bmap, (dict, ChainMap)) ...
For all of the names build a ChainMap containing a map for every base class.
350,170
def callproc(self, procname, parameters=()): self._assert_open() return self._callproc(procname, parameters)
Call a stored procedure with the given name. :param procname: The name of the procedure to call :type procname: str :keyword parameters: The optional parameters for the procedure :type parameters: sequence
350,171
def unbind(self, binding): username = self.backend.config.generate_binding_username(binding) try: self.backend.atlas.DatabaseUsers.delete_a_database_user(username) except ErrAtlasNotFound: pass sel...
Unbind the instance Args: binding (AtlasServiceBinding.Binding): Existing or New binding
350,172
def remove_task(self, task_id): try: self._scheduler.cancel_task(task_id) except NotFoundError as e: logger.info("Cannot cancel %s task because it does not exist.", task_id) return False else: return True
Remove and cancel a task. :param task_id: id of the task to be removed
350,173
def by_URI(cls, URI, label=None, autoflush=True): s label (optional, default: None) :type label: string :returns: the semantic tag object with the given id or URI, or None if there is no tag with that id or name :rtype: ckan.model.semantictag.SemanticTag ' if label: query = meta.Session.query(Seman...
Return the semantic ag with the given URI, or None. :param URI: the URI of the semantic tag to return :type URI: string (URI format) :param label: URI's label (optional, default: None) :type label: string :returns: the semantic tag object with the given id or URI, or None if there is no tag with that id ...
350,174
def addPointScalars(self, scalars, name): poly = self.polydata(False) if len(scalars) != poly.GetNumberOfPoints(): colors.printc(, len(scalars), poly.GetNumberOfPoints(), c=1) exit() arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep...
Add point scalars to the actor's polydata assigning it a name. .. hint:: |mesh_coloring| |mesh_coloring.py|_
350,175
def make_patch_request(url, data, params, headers, connection): timeout = getattr(connection, ) response = connection.patch(url, data=data, params=params, headers=headers, timeout=timeout) if response.ok or response.status_code == 403: return response.json() if r...
Helper function that makes an HTTP PATCH request to the given firebase endpoint. Timeout is 60 seconds. `url`: The full URL of the firebase endpoint (DSN appended.) `data`: JSON serializable dict that will be stored in the remote storage. `params`: Python dict that is appended to the URL like a querystr...
350,176
def FindAttribute(self, textAttributeId: int, val, backward: bool) -> : textRange = self.textRange.FindAttribute(textAttributeId, val, int(backward)) if textRange: return TextRange(textRange=textRange)
Call IUIAutomationTextRange::FindAttribute. textAttributeID: int, a value in class `TextAttributeId`. val: COM VARIANT according to textAttributeId? todo. backward: bool, True if the last occurring text range should be returned instead of the first; otherwise False. return `TextRange` or...
350,177
def convert_tree(self, ptb_tree, representation=, include_punct=True, include_erased=False, add_lemmas=False, universal=True): self._raise_on_bad_input(ptb_tree) self._raise_on_bad_representation(representation) tree = self.treeReader(ptb_tree) ...
Arguments are as in StanfordDependencies.convert_trees but with the addition of add_lemmas. If add_lemmas=True, we will run the Stanford CoreNLP lemmatizer and fill in the lemma field.
350,178
def login(self, user, password, exe_path, comm_password=None, **kwargs): try: self._app = pywinauto.Application().connect( path=self._run_exe_path(exe_path), timeout=1 ) except Exception: self._app = pywinauto.Application().start(exe_...
登陆客户端 :param user: 账号 :param password: 明文密码 :param exe_path: 客户端路径类似 'C:\\中国银河证券双子星3.2\\Binarystar.exe', 默认 'C:\\中国银河证券双子星3.2\\Binarystar.exe' :param comm_password: 通讯密码, 华泰需要,可不设 :return:
350,179
def encrypt(self, plaintext): plainbytes = plaintext.encode() compressed = zlib.compress(plainbytes) cipher = AES.new(self.cipher_key, AES.MODE_GCM, nonce=random_bytes(12)) encrypted, tag = cipher.encrypt_and_digest(compressed) ...
Return ciphertext for given plaintext.
350,180
def enhance_json_encode(api_instance, extra_settings=None): api_instance.json_encoder = JSONEncodeManager() dumps_settings = {} if extra_settings is None else extra_settings dumps_settings[] = api_instance.json_encoder dumps_settings.setdefault(, False) @api_instance.representation() def ...
use `JSONEncodeManager` replace default `output_json` function of Flask-RESTful for the advantage of use `JSONEncodeManager`, please see https://github.com/anjianshi/json_encode_manager
350,181
def serial_starfeatures(lclist, outdir, lc_catalog_pickle, neighbor_radius_arcsec, maxobjects=None, deredden=True, custom_bandpasses=None, lcformat=, ...
This drives the `get_starfeatures` function for a collection of LCs. Parameters ---------- lclist : list of str The list of light curve file names to process. outdir : str The output directory where the results will be placed. lc_catalog_pickle : str The path to a catalog...
350,182
def split_join_classification(element, classification_labels, nodes_classification): classification_join = "Join" classification_split = "Split" if len(element[1][consts.Consts.incoming_flow]) >= 2: classification_labels.append(classification_join) if len(element[1][...
Add the "Split", "Join" classification, if the element qualifies for. :param element: an element from BPMN diagram, :param classification_labels: list of labels attached to the element, :param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels.
350,183
def replace_variables(self, tokens, scope): list = [] for t in tokens: if utility.is_variable(t): list.append(scope.swap(t)) elif str(type(t)) == "<class >": list.append(scope.swap(t.name)) else: list.append(t) ...
Replace variables in tokenlist args: tokens (list): tokenlist scope (Scope): Current scope returns: list
350,184
def p_non_empty_array_pair_list_pair(p): if len(p) == 7: p[0] = p[1] + [ast.ArrayElement(p[3], p[6], True, lineno=p.lineno(2))] elif len(p) == 6: p[0] = p[1] + [ast.ArrayElement(p[3], p[5], False, lineno=p.lineno(2))] elif len(p) == 5: p[0] = [ast.ArrayElement(p[1], p[4], True, ...
non_empty_array_pair_list : non_empty_array_pair_list COMMA expr DOUBLE_ARROW AND variable | non_empty_array_pair_list COMMA expr DOUBLE_ARROW expr | expr DOUBLE_ARROW AND variable | expr DOUBLE_ARROW expr
350,185
def check_install_build_global(options, check_options=None): if check_options is None: check_options = options def getname(n): return getattr(check_options, n, None) names = ["build_options", "global_options", "install_options"] if any(map(getname, names)): control = o...
Disable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options.
350,186
def check_surrounding_whitespaces(self, definition, docstring): if docstring: lines = ast.literal_eval(docstring).split() if lines[0].startswith() or \ len(lines) == 1 and lines[0].endswith(): return violations.D210()
D210: No whitespaces allowed surrounding docstring text.
350,187
def _normalize_cmd_args(cmd): if isinstance(cmd, six.string_types): if cmd.find(" | ") > 0 or cmd.find(">(") or cmd.find("<("): return "set -o pipefail; " + cmd, True, find_bash() else: return cmd, True, None else: return [str(x) for x in cmd], False...
Normalize subprocess arguments to handle list commands, string and pipes. Piped commands set pipefail and require use of bash to help with debugging intermediate errors.
350,188
def followers_qs(self, actor, flag=): check(actor) queryset = self.filter( content_type=ContentType.objects.get_for_model(actor), object_id=actor.pk ).select_related() if flag: queryset = queryset.filter(flag=flag) return queryset
Returns a queryset of User objects who are following the given actor (eg my followers).
350,189
def validate_payload_len(self, payload): if not hasattr(self, "PAYLOAD_LEN"): return if len(payload) != self.PAYLOAD_LEN: raise PyVLXException("Invalid payload len", expected_len=self.PAYLOAD_LEN, current_len=len(payload), frame_type=type(self).__na...
Validate payload len.
350,190
def system_monitor_SFM_threshold_down_threshold(self, **kwargs): config = ET.Element("config") system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor") SFM = ET.SubElement(system_monitor, "SFM") threshold = ET.SubElement(SFM, ...
Auto Generated Code
350,191
def _handle_result_by_index(self, idx): if idx < 0: return None opts = dict(self.options) skip = opts.pop(, 0) limit = opts.pop(, None) py_to_couch_validate(, skip) py_to_couch_validate(, limit) if limit is not None and idx >= limit: ...
Handle processing when the result argument provided is an integer.
350,192
def get_FEC(molecule_list, temperature, pressure, electronic_energy=): if not temperature or not pressure: return(0) else: molecule_list = [m for m in molecule_list if m != ] FEC_sum = [] for molecule in molecule_list: if in molecule: mo...
Returns the Gibbs free energy corrections to be added to raw reaction energies. Parameters ---------- molecule_list : list of strings temperature : numeric temperature in K pressure : numeric pressure in mbar Returns ------- G_H, G_OH : Gibbs free energy of proton and hy...
350,193
def plot_low_pass_filter_response(show_plot=False, file_name=None): freqs = numpy.linspace(1, 1200, 100000) cutoff_freq = 40 gain_functions = [] legend_strs = [] for order in range(1, 7): gain = 20*numpy.log10(1 / (numpy.sqrt(1 + (freqs / cutoff_freq)**(2*order)))...
----- Brief ----- Taking into consideration the generic transfer function that defines the frequency response of a low-pass filter (|H|=1/(sqrt(1+(f/fc)^2n), where fc is the corner frequency and n is the filter order), the current function will generate a figure for comparing the frequency response ...
350,194
def write(self, filename=None, ncol=ncol, format=format): with open(self.filename(filename, ext=), ) as ndx: for name in self: atomnumbers = self._getarray(name) ndx.write(.format(name)) for k in range(0, len(atomnumbers), ncol): ...
Write index file to *filename* (or overwrite the file that the index was read from)
350,195
def get_previous_price(self, currency, date_obj): start = date_obj.strftime() end = date_obj.strftime() url = ( .format( start, end, currency ) ) response = requests.get(url) if response.status_code == 20...
Get Price for one bit coin on given date
350,196
def _accumulate(sequence, func): iterator = iter(sequence) total = next(iterator) yield total for element in iterator: total = func(total, element) yield total
Python2 accumulate implementation taken from https://docs.python.org/3/library/itertools.html#itertools.accumulate
350,197
def detect_change_mode(text,change): "returns or . see comments to update_changes for more details." if len(change.deltas)>1: return
returns 'add' 'delete' or 'internal'. see comments to update_changes for more details.
350,198
def _validate_install(self): self.printer(, flush=True) from os import devnull from subprocess import call, check_output sys_command = try: call(sys_command, shell=True, stdout=open(devnull, )) except Exception a...
a method to validate heroku is installed
350,199
def _get_total_services_not_monitored(self): return sum(1 for s in self.services if not s.active_checks_enabled and not s.passive_checks_enabled)
Get the number of service not monitored (active and passive checks disabled) :return: Number of services which are not monitored :rtype: int