Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
354,400
def firmware_download_output_cluster_output_rbridge_id(self, **kwargs): config = ET.Element("config") firmware_download = ET.Element("firmware_download") config = firmware_download output = ET.SubElement(firmware_download, "output") cluster_output = ET.SubElement(output,...
Auto Generated Code
354,401
def engine(func): func = _make_coroutine_wrapper(func, replace_callback=False) @functools.wraps(func) def wrapper(*args, **kwargs): future = func(*args, **kwargs) def final_callback(future): if future.result() is not None: raise ReturnValueIgnoredError( ...
Callback-oriented decorator for asynchronous generators. This is an older interface; for new code that does not need to be compatible with versions of Tornado older than 3.0 the `coroutine` decorator is recommended instead. This decorator is similar to `coroutine`, except it does not return a `.Fu...
354,402
def to_polar(x, y, theta_units="radians"): assert theta_units in [ "radians", "degrees", ], "kwarg theta_units must specified in radians or degrees" theta = atan2(y, x) r = sqrt(x ** 2 + y ** 2) if theta_units == "degrees": theta = to_degrees(theta) return r, thet...
Converts cartesian x, y to polar r, theta.
354,403
def parse_extras(self): extras = None if "@" in self.line or self.is_vcs or self.is_url: line = "{0}".format(self.line) uri = URI.parse(line) name = uri.name if name: self._name = name if uri.host and uri.path...
Parse extras from *self.line* and set them on the current object :returns: Nothing :rtype: None
354,404
def registerUpgrader(upgrader, typeName, oldVersion, newVersion): assert isinstance(typeName, str), "read the doc string" _upgradeRegistry[typeName, oldVersion] = upgrader
Register a callable which can perform a schema upgrade between two particular versions. @param upgrader: A one-argument callable which will upgrade an object. It is invoked with an instance of the old version of the object. @param typeName: The database typename for which this is an upgrader. @par...
354,405
def save_sampler(sampler): db = sampler.db fnode = tables.filenode.newnode(db._h5file, where=, name=) import pickle pickle.dump(sampler, fnode)
Dumps a sampler into its hdf5 database.
354,406
def virtualenv(self, virtualenv): if isinstance(virtualenv, bool): self._skip_virtualenv = virtualenv else: self._virtualenv = virtualenv if not os.path.isdir(self._virtualenv): raise Exception("virtualenv %s not found" % self._virtua...
Sets the virtual environment for the lambda package If this is not set then package_dependencies will create a new one. Takes a path to a virtualenv or a boolean if the virtualenv creation should be skipped.
354,407
def initialize(logger_name=LOGGER_NAME, log_filename=LOG_FILENAME, app_logging_level=APP_LOGGING_LEVEL, dep_logging_level=DEP_LOGGING_LEVEL, format=None, logger_class=None, handlers=[], global_logger=True): ...
Constructs and initializes a `logging.Logger` object. Returns :class:`logging.Logger` object. :param logger_name: name of the new logger. :param log_filename: The log file location :class:`str` or None. :param app_logging_level: The logging level to use for the application. :param dep_logging_leve...
354,408
def get_pmap_from_csv(oqparam, fnames): if not oqparam.imtls: oqparam.set_risk_imtls(get_risk_models(oqparam)) if not oqparam.imtls: raise ValueError( % oqparam.inputs[]) dic = {wrapper.imt: wrapper.array for wrapper in map(writers.read_composite_arr...
:param oqparam: an :class:`openquake.commonlib.oqvalidation.OqParam` instance :param fnames: a space-separated list of .csv relative filenames :returns: the site mesh and the hazard curves read by the .csv files
354,409
def _format_exception(err, is_failure, stdout=None, stderr=None): exctype, value, tb = err while tb and _is_relevant_tb_level(tb): tb = tb.tb_next if is_failure: length = _count_relevant_tb_levels(tb) msgLines = traceback.format_exception(exctype, value, tb, lengt...
Converts a sys.exc_info()-style tuple of values into a string.
354,410
def validate_anneal_schedule(self, anneal_schedule): if not in self.parameters: raise RuntimeError("anneal_schedule is not an accepted parameter for this sampler") properties = self.properties try: min_anneal_time, max_anneal_time = properties[] ma...
Raise an exception if the specified schedule is invalid for the sampler. Args: anneal_schedule (list): An anneal schedule variation is defined by a series of pairs of floating-point numbers identifying points in the schedule at which to change slope. The first ...
354,411
def pack_turret(turret, temp_files, base_config_path, path=None): file_name = turret[] files = temp_files[:] for fname in turret.get(, []): if os.path.isabs(fname) or path is None: files.append(fname) else: files.append(os.path.join(path, fname)) if path is n...
pack a turret into a tar file based on the turret configuration :param dict turret_config: the turret configuration to pack :param str tmp_config_file: the path of the temp config file :param str base_config_path: the base directory of the main configuration file
354,412
def barplot(bars, title=, upColor=, downColor=): import pandas as pd import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.patches import Rectangle if isinstance(bars, pd.DataFrame): ohlcTups = [ tuple(v) for v in bars[[, , , ]].values] eli...
Create candlestick plot for the given bars. The bars can be given as a DataFrame or as a list of bar objects.
354,413
def _pyside2(): import PySide2 as module _setup(module, ["QtUiTools"]) Qt.__binding_version__ = module.__version__ try: try: import shiboken2 except ImportError: from PySide2 import shiboken2 Qt.QtCompat.wrapInstance = ( ...
Initialise PySide2 These functions serve to test the existence of a binding along with set it up in such a way that it aligns with the final step; adding members from the original binding to Qt.py
354,414
def get_number_unit(number): n = str(float(number)) mult, submult = n.split() if float(submult) != 0: unit = + (len(submult)-1)* + return float(unit) else: return float(1)
get the unit of number
354,415
def get_dynamodb_type(self, val): dynamodb_type = None if is_num(val): dynamodb_type = elif is_str(val): dynamodb_type = elif isinstance(val, (set, frozenset)): if False not in map(is_num, val): dynamodb_type = e...
Take a scalar Python value and return a string representing the corresponding Amazon DynamoDB type. If the value passed in is not a supported type, raise a TypeError.
354,416
def get_arguments(self): ApiCli.get_arguments(self) if self.args.metric_name is not None: self._metric_name = self.args.metric_name if self.args.sample is not None: self.sample = self.args.sample if self.args.source is not None: self.source ...
Extracts the specific arguments of this CLI
354,417
def parallel_cp( pfpicklelist, outdir, lcbasedir, fast_mode=False, lcfnamelist=None, cprenorm=False, lclistpkl=None, gaia_max_timeout=60.0, gaia_mirror=None, nbrradiusarcsec=60.0, maxnumneighbors=5, makeneighborlcs=True, ...
This drives the parallel execution of `runcp` for a list of periodfinding result pickles. Parameters ---------- pfpicklelist : list of str or list of Nones This is the list of the filenames of the period-finding result pickles to process. To make checkplots using the light curves direc...
354,418
def phreg(self, data: [, str] = None, assess: str = None, bayes: str = None, by: str = None, cls: [str, list] = None, contrast: str = None, effect: str = None, estimate: str = None, freq: str = None, ...
Python method to call the PHREG procedure Documentation link: https://go.documentation.sas.com/?cdcId=pgmsascdc&cdcVersion=9.4_3.4&docsetId=statug&docsetTarget=statug_phreg_syntax.htm&locale=en :param data: SASdata object or string. This parameter is required. :parm assess: The assess ...
354,419
def __validate(self, value, validate_element): if not self.repeated: return validate_element(value) else: if isinstance(value, (list, tuple)): result = [] for element in value: if element is None: ...
Internal validation function. Validate an internal value using a function to validate individual elements. Args: value: Value to validate. validate_element: Function to use to validate individual elements. Raises: ValidationError if value is not expected ...
354,420
def subdivide(self): left_nodes, right_nodes = _curve_helpers.subdivide_nodes(self.nodes) midpoint = 0.5 * (self.start + self.end) left = SubdividedCurve( left_nodes, self.original_nodes, start=self.start, end=midpoint ) right = SubdividedCurve( r...
Split the curve into a left and right half. See :meth:`.Curve.subdivide` for more information. Returns: Tuple[SubdividedCurve, SubdividedCurve]: The left and right sub-curves.
354,421
def setup_parser(sub_parsers): parser = sub_parsers.add_parser("software", prog="law software", description="Create or update" " the law software cache ({}). This is only required for some sandboxes that need to" " forward software into containers.".format(get_sw_dir())) parser.add_argumen...
Sets up the command line parser for the *software* subprogram and adds it to *sub_parsers*.
354,422
def config_loader(app, **kwargs): app.config.from_object(Config) app.config.update(**kwargs)
Custom config loader.
354,423
def get_simplex_solution_graph(self): flows of arcs. Returns the graph with arcs that have flow between 0 and capacity. Pre: (1) attribute represents a feasible flow solution. See Pre section of min_cost_flow() for details. Return: Gra...
API: get_simplex_solution_graph(self): Description: Assumes a feasible flow solution stored in 'flow' attribute's of arcs. Returns the graph with arcs that have flow between 0 and capacity. Pre: (1) 'flow' attribute represents a feasible flow s...
354,424
def _build_url(self, host, sport, method, id, format, parameters): path = "/".join(filter(None, (sport, method, id))) url = "https://" + host + "/" + path + "." + format if parameters: paramstring = urllib.parse.urlencode(parameters) url = url + "?" + paramstring...
build url from args
354,425
def umi_below_threshold(umi_quals, quality_encoding, quality_filter_threshold): below_threshold = get_below_threshold( umi_quals, quality_encoding, quality_filter_threshold) return any(below_threshold)
return true if any of the umi quals is below the threshold
354,426
def _load(self, value: Any): if value in self.empty_values: if self.default is not None: default = self.default value = default() if callable(default) else default return value elif self.required: ...
Load the value for the field, run validators and return the value. Subclasses can override this to provide custom load logic. :param value: value of the field
354,427
def j0_4(f=1, rho=0.3, z=50): r gam = np.sqrt(2j*np.pi*mu_0*f/rho) def lhs(x): beta = np.sqrt(x**2 + gam**2) return x*np.exp(-beta*np.abs(z))/beta def rhs(b): R = np.sqrt(b**2 + z**2) return np.exp(-gam*R)/R return Ghosh(, lhs, rhs)
r"""Hankel transform pair J0_4 ([ChCo82]_). Parameters ---------- f : float Frequency (Hz) rho : float Resistivity (Ohm.m) z : float Vertical distance between source and receiver (m)
354,428
def addStep(self, callback, *args, **kwargs): self.steps.append((callback, args, kwargs))
Add rollback step with optional arguments. If a rollback is triggered, each step is called in LIFO order.
354,429
def update_from_json(self, data): self.subscription = data.get("subscription", "none") self.approved = bool(data.get("approved", False)) self.ask = data.get("ask", None) self.name = data.get("name", None) self.groups = set(data.get("groups", []))
Update the attributes of this :class:`Item` using the values obtained from the dictionary `data`. The format of `data` should be the same as the format returned by :meth:`export_as_json`.
354,430
def get_record_set_md5(rs_name, rs_type): rs_name = rs_name.lower() rs_type = rs_type.upper() rs_type = "ACNAME" if rs_type in ["A", "CNAME"] else rs_type return md5(rs_name + rs_type).hexdigest()
Accept record_set Name and Type. Return MD5 sum of these values.
354,431
def guess(self, *args): logging.debug("guess called.") logging.debug("Validating game object") self._validate_game_object(op="guess") logging.debug("Building return object") _return_results = { "cows": None, "bulls": None, "analysis":...
guess() allows a guess to be made. Before the guess is made, the method checks to see if the game has been won, lost, or there are no tries remaining. It then creates a return object stating the number of bulls (direct matches), cows (indirect matches), an analysis of the guess (a list o...
354,432
def perform_work( self): self.debug_log(( )) self.tid = threading.current_thread().ident if self.sleep_interval > 0: if self.timer: self.timer.cancel() else: self.debug_log(( ...
perform_work Process handler function for processing messages found in the ``multiprocessing.Manager.queue`` Build the ``self.log_payload`` from the queued log messages and POST it to the Splunk endpoint
354,433
def check_angle_solution(ang,n_vec,toy_aa,timeseries): f,a=plt.subplots(3,1) for i in range(3): a[i].plot(toy_aa.T[i+3],) size = len(ang[6:])/3 AA = np.array([np.sum(ang[6+i*size:6+(i+1)*size]*np.sin(np.sum(n_vec*K,axis=1))) for K in toy_aa.T[3:].T]) a[i].plot((ang[i]+ang[i+...
Plots the toy angle solution against the toy angles --- Takes true angles and frequencies ang, the Fourier vectors n_vec, the toy action-angles toy_aa and the timeseries
354,434
def load_trajectory(name=None, index=None, as_new=False, load_parameters=pypetconstants.LOAD_DATA, load_derived_parameters=pypetconstants.LOAD_SKELETON, load_results=pypetconstants.LOAD_SKELETON, load...
Helper function that creates a novel trajectory and loads it from disk. For the parameters see :func:`~pypet.trajectory.Trajectory.f_load`. ``new_name`` and ``add_time`` are only used in case ``as_new`` is ``True``. Accordingly, they determine the new name of trajectory.
354,435
def b58decode(v): if not isinstance(v, str): v = v.decode() origlen = len(v) v = v.lstrip(alphabet[0]) newlen = len(v) acc = b58decode_int(v) result = [] while acc > 0: acc, mod = divmod(acc, 256) result.append(mod) return (b * (origlen - newlen) + bseq(...
Decode a Base58 encoded string
354,436
def is_sharable(self): return self.sharable and all(x.is_sharable() for x in self.buttons)
Is sharable if marked as and if buttons are sharable (they might hold sensitive data).
354,437
def psf_general(vx_size=(1,1,1), fwhm=(5, 5, 6), hradius=8, scale=2): xSig = (scale*fwhm[0]/vx_size[0]) / (2*(2*np.log(2))**.5) ySig = (scale*fwhm[1]/vx_size[1]) / (2*(2*np.log(2))**.5) zSig = (scale*fwhm[2]/vx_size[2]) / (2*(2*np.log(2))**.5) x = np.arange(-hradius,hradius+1) xKrnl = np....
Separable kernels for convolution executed on the GPU device The outputted kernels are in this order: z, y, x
354,438
def get_info(self): plugin_infos = {} for pc in self.plugins: plugin_infos.update(pc.get_info()) return { self.get_plugin_name() : { "version" : self.get_version(), "sub-plugins" : plugin_infos, "params" : { ...
Return plugin information.
354,439
def resize(self, capacity): count = max(int(capacity), 0) - len(self) if count == 0: pass elif -count == len(self): self.clear() elif count > 0: for i in range(count): self.append() else: for i in range(abs...
Re-sizes the `Array` by appending new *array elements* or removing *array elements* from the end. :param int capacity: new capacity of the `Array` in number of *array elements*.
354,440
def InitKeypair(aws_id, aws_secret, ec2, s3, keypair_name, src_region, dst_regions): metadata = CirrusAccessIdMetadata(s3, aws_id) keypair = ec2.get_key_pair(keypair_name) ssh_key = None if keypair: ssh_key = metadata.GetSshKey(keypair_name) if not ssh_key: if keypair...
Returns the ssh private key for the given keypair name Cirrus created bucket. Creates the keypair if it doesn't yet exist and stores private key in S3.
354,441
def NextToken(self): if not self.buffer: return current_state = self.state for token in self._tokens: if token.state_regex and not token.state_regex.match(current_state): continue if self.verbose: logging.debug("%s: Trying to match %r with %r", self.state...
Fetch the next token by trying to match any of the regexes in order.
354,442
def getAllCols(self, sddsfile=None): if SDDS_: if sddsfile is not None: sddsobj = sdds.SDDS(2) sddsobj.load(sddsfile) else: sddsobj = self.sddsobj return sddsobj.columnName else: if sddsfile is None:...
get all available column names from sddsfile :param sddsfile: sdds file name, if not given, rollback to the one that from ``__init__()`` :return: all sdds data column names :rtype: list :Example: >>> dh = DataExtracter('test.out') >>> print(dh.getAllCols()) ['x...
354,443
def scroll(self, x, y): assert isinstance(x, _INTTYPES), "x must be an integer, got %s" % repr(x) assert isinstance(y, _INTTYPES), "y must be an integer, got %s" % repr(x) def getSlide(x, length): if x > 0: srcx = 0 length -= x ...
Scroll the contents of the console in the direction of x,y. Uncovered areas will be cleared to the default background color. Does not move the virutal cursor. Args: x (int): Distance to scroll along the x-axis. y (int): Distance to scroll along the y-axis. Retu...
354,444
def get_full_url(self, url): request = Request(, url) preparedrequest = self.session.prepare_request(request) return preparedrequest.url
Get full url including any additional parameters Args: url (str): URL for which to get full url Returns: str: Full url including any additional parameters
354,445
def reverse_guard(lst): rev = {: , : , : , : } return [rev[l] if l in rev else l for l in lst]
Reverse guard expression. not (@a > 5) -> (@a =< 5) Args: lst (list): Expression returns: list
354,446
def get_repos(self): return github.PaginatedList.PaginatedList( github.Repository.Repository, self._requester, self.url + "/repos", None )
:calls: `GET /teams/:id/repos <http://developer.github.com/v3/orgs/teams>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository`
354,447
def _atexit_callback(cls): updated_scripts = {} for baseline in cls._baselines_to_update: if baseline.z__path.endswith(): continue try: script = updated_scripts[baseline.z__path] except KeyError: script = Scr...
Create Python script copies with updated baselines. For any baseline that had a miscompare, make a copy of the source file which contained the baseline and update the baseline with the new string value. :returns: record of every Python file update (key=path, val...
354,448
def addDocs(self, docs): lst = [] for fields in docs: self.__add(lst, fields) lst.append() xstr = .join(lst) return self.doUpdateXML(xstr)
docs is a list of fields that are a dictionary of name:value for a record.
354,449
def as_artist(self, origin=(0, 0), **kwargs): from matplotlib.patches import Circle xy = self.center.x - origin[0], self.center.y - origin[1] radius = self.radius mpl_params = self.mpl_properties_default() mpl_params.update(kwargs) return Circle(xy=xy, radius=r...
Matplotlib patch object for this region (`matplotlib.patches.Circle`) Parameters ---------- origin : array_like, optional The ``(x, y)`` pixel position of the origin of the displayed image. Default is (0, 0). kwargs : `dict` All keywords that a `~matp...
354,450
def plot_txn_time_hist(transactions, bin_minutes=5, tz=, ax=None, **kwargs): if ax is None: ax = plt.gca() txn_time = transactions.copy() txn_time.index = txn_time.index.tz_convert(pytz.timezone(tz)) txn_time.index = txn_time.index.map(lambda x: x.hour * 60 + x.min...
Plots a histogram of transaction times, binning the times into buckets of a given duration. Parameters ---------- transactions : pd.DataFrame Prices and amounts of executed trades. One row per trade. - See full explanation in tears.create_full_tear_sheet. bin_minutes : float, optio...
354,451
def getPosArgs(self): if len(self._posArgs) < 1: return [] self._posArgs.sort() retval = [] for idx, scope, name in self._posArgs: theDict, val = findScopedPar(self, scope, name) retval.append(val) return retval
Return a list, in order, of any parameters marked with "pos=N" in the .cfgspc file.
354,452
def iter_leaves(self, is_leaf_fn=None): for n in self.traverse(strategy="preorder", is_leaf_fn=is_leaf_fn): if not is_leaf_fn: if n.is_leaf(): yield n else: if is_leaf_fn(n): yield n
Returns an iterator over the leaves under this node.
354,453
def _segment_lengths(self, relative=False, n=20): lengths = [] first = True for el in self._get_elements(): if first is True: close_x, close_y = el.x, el.y first = False elif el.cmd == MOVETO: close_x, clos...
Returns a list with the lengths of each segment in the path.
354,454
def exe_to_egg(self, dist_filename, egg_tmp): prefixes = get_exe_prefixes(dist_filename) to_compile = [] native_libs = [] top_level = {} def process(src, dst): s = src.lower() for old, new in prefixes: if s.startswith(old...
Extract a bdist_wininst to the directories an egg would use
354,455
def _context_menu_make(self, pos): menu = super(FrontendWidget, self)._context_menu_make(pos) for before_action in menu.actions(): if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \ QtGui.QKeySequence.ExactMatch: menu.insertAction(...
Reimplemented to add an action for raw copy.
354,456
def do_unmute(self, sender, body, args): if sender.get(): sender[] = False self.broadcast( % (sender[],)) for msg in sender.get(, []): self.send_message(msg, sender) sender[] = [] else: self.send_message(, sender)
Unmutes the chatroom for a user
354,457
def handle_publish(self, package, _): try: self.publisher.publish(package) return package except Exception: log.critical(, exc_info=True) return None
Get something from epull, publish it out epub, and return the package (or None)
354,458
def sequence(self, struct, size=1000, tree_depth=1, append_callable=None): if not tree_depth: return self._map_type() _struct = struct() add_struct = _struct.append if not append_callable \ else getattr(_struct, append_callable) for x in range(size): ...
Generates random values for sequence-like objects @struct: the sequence-like structure you want to fill with random data @size: #int number of random values to include in each @tree_depth @tree_depth: #int dict tree dimensions size, i.e. 1=|(value1, v...
354,459
def pwm_array2pssm_array(arr, background_probs=DEFAULT_BASE_BACKGROUND): b = background_probs2array(background_probs) b = b.reshape([1, 4, 1]) return np.log(arr / b).astype(arr.dtype)
Convert pwm array to pssm array
354,460
def material_roughness(ID, D=None, optimism=None): rs difflib or with the fuzzywuzzy module if available. Parameters ---------- ID : str Search terms for matching pipe materials, [-] D : float, optional Diameter of desired pipe; used only if ID is in [2]_, [m] optimism : boo...
r'''Searches through either a dict of clean pipe materials or used pipe materials and conditions and returns the ID of the nearest material. Search is performed with either the standard library's difflib or with the fuzzywuzzy module if available. Parameters ---------- ID : str Search t...
354,461
def get_object(self, name, *argv, **kwargs): regexp = name options = self.opts(regexp) options.update(kwargs) args = options.pop(, argv) csrf_enable = self.get_backend_data(regexp).get(, True) if regexp in self.settings_urls: regexp = r.format(self.ge...
Get url object tuple for url :param name: url regexp from :type name: str :param argv: overrided args :param kwargs: overrided kwargs :return: url object :rtype: django.conf.urls.url
354,462
def cancel(self, event): topic = event.data.get(, None) if topic is None: self.log(, lvl=warn) return self._cancel(topic)
AlertManager event handler for incoming events :param event with incoming AlertManager message
354,463
def watch(self, flag): lib.EnvSetDefmessageHandlerWatch( self._env, int(flag), self._cls, self._idx)
True if the MessageHandler is being watched.
354,464
def serialize(message): fmt = "!BBH" if message.token is None or message.token == "": tkl = 0 else: tkl = len(message.token) tmp = (defines.VERSION << 2) tmp |= message.type tmp <<= 4 tmp |= tkl values = [tmp, message.cod...
Serialize a message to a udp packet :type message: Message :param message: the message to be serialized :rtype: stream of byte :return: the message serialized
354,465
def parse_arguments(): base_dn = os.environ[] if in os.environ \ else domain = os.environ[].upper() if in os.environ else page_size = os.environ[].upper() if in os.environ else 300 tls_no_verify = bool(os.environ[].lower().capitalize()) \ if in os.enviro...
Collect command-line arguments. Let the caller run parse_args(), as sphinx-argparse requires a function that returns an instance of argparse.ArgumentParser
354,466
def all(cls, otp=False, ccid=False, u2f=False): modes = set([ cls.OTP, cls.CCID, cls.OTP_CCID, cls.U2F, cls.OTP_U2F, cls.U2F_CCID, cls.OTP_U2F_CCID ]) if otp: modes.difference_update(set([ ...
Returns a set of all USB modes, with optional filtering
354,467
def log_iter(self, maxentries=None, template=None, **kwargs): template = str(template or self.template) op = self.log(n=maxentries, template=template, **kwargs) if not op: return print(op) for l in itersplit(op, se...
Run the repository log command, parse, and yield log tuples Yields: tuple: self._tuple
354,468
def set(self, request_url, response_json): if self.size() == self._max_size: popped = self._usage_recency.pop() del self._table[popped] current_time = timeutils.now() if request_url not in self._table: self._table[request_url] = {: response_json, ...
Checks if the maximum size of the cache has been reached and in case discards the least recently used item from 'usage_recency' and 'table'; then adds the response_json to be cached to the 'table' dict using as a lookup key the request_url of the request that generated the value; finally...
354,469
def copy(self): rv = self.__class__(self.capacity) rv._mapping.update(self._mapping) rv._queue = deque(self._queue) return rv
Return a shallow copy of the instance.
354,470
def list_tables(self, dataset): request = self.client.tables().list(projectId=dataset.project_id, datasetId=dataset.dataset_id, maxResults=1000) response = request.execute() while response is not N...
Returns the list of tables in a given dataset. :param dataset: :type dataset: BQDataset
354,471
def hash_coloured_escapes(text): ansi_code = int(sha256(text.encode()).hexdigest(), 16) % 230 prefix, suffix = colored(, ansi_code=ansi_code).split() return prefix, suffix
Return the ANSI hash colour prefix and suffix for a given text
354,472
def remove_star(self, component=None, **kwargs): kwargs.setdefault(, ) return self.remove_component(component, **kwargs)
[NOT IMPLEMENTED] Shortcut to :meth:`remove_component` but with kind='star'
354,473
def set_fan(self, fan): if type(fan) != int and fan not in range(0, 11): raise InvalidInput("Fan value must be int between 0-10") self._config[] = fan self._q.put(self._config)
Set the fan config. :param fan: Value to set the fan :type fan: int [0-10] :returns: None :raises: InvalidInput
354,474
def to_feather(df, path): path = _stringify_path(path) if not isinstance(df, DataFrame): raise ValueError("feather only support IO with DataFrames") feather = _try_import()[0] valid_types = {, } if not isinstance(df.index, Int64Index): raise ValueError("f...
Write a DataFrame to the feather-format Parameters ---------- df : DataFrame path : string file path, or file-like object
354,475
def plot_total(self, colorbar=True, cb_orientation=, cb_label=, ax=None, show=True, fname=None, **kwargs): if ax is None: fig, axes = self.total.plot( colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, s...
Plot the total magnetic intensity. Usage ----- x.plot_total([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname, **kwargs]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] ...
354,476
def _bucket_events(self, event_iterable): current_bucket_time = None current_bucket_events = None for event in event_iterable: event_bucket_time = self._bucket_time(event[TIMESTAMP_FIELD]) if current_bucket_time is None or current_bucket_time < event_bucket_time: if current_bucket_...
Convert an iterable of events into an iterable of lists of events per bucket.
354,477
def _hack_namedtuple(cls): name = cls.__name__ fields = cls._fields def __reduce__(self): return (_restore, (name, fields, tuple(self))) cls.__reduce__ = __reduce__ cls._is_namedtuple_ = True return cls
Make class generated by namedtuple picklable
354,478
def boot(app_name) -> Rinzler: app = Rinzler(app_name) app.log.info("App booted =)") return app
Start Rinzler App :param app_name: str Application's identifier :return: dict
354,479
def _parse_executable_spec(src_dir, json_file_name, parser): if not os.path.isdir(src_dir): parser.error("{} is not a directory".format(src_dir)) if not os.path.exists(os.path.join(src_dir, json_file_name)): raise WorkflowBuilderException( "Directory {} does not contain dxworkf...
Returns the parsed contents of a json specification. Raises WorkflowBuilderException (exit code 3) if this cannot be done.
354,480
def setInputs(self, inputs): if not self.verifyArguments(inputs) and not self.patterned: raise NetworkError(, inputs) self.inputs = inputs self.loadOrder = [0] * len(self.inputs) for i in range(len(self.inputs)): self.loadOrder[i] = i
Sets self.input to inputs. Load order is by default random. Use setOrderedInputs() to order inputs.
354,481
def update_dict(d, u): for key, val in u.items(): if isinstance(val, collections.Mapping): d[key] = update_dict(d.get(key, {}), val) else: d[key] = u[key] return d
Recursively updates nested dict d from nested dict u
354,482
async def listen(self): while not self._shutdown: try: data = json.loads(await self._ws.recv()) except websockets.ConnectionClosed as error: log.warning(.format(str(error))) for g in self._lavalink.players._players.copy().ke...
Waits to receive a payload from the Lavalink server and processes it.
354,483
def ParseFileObject(self, parser_mediator, file_object): filename = parser_mediator.GetFilename() file_size = file_object.get_size() if file_size <= 0: raise errors.UnableToParseFile( .format(file_size)) if file_size > 50000000: raise errors.UnableToParseFile( ...
Parses a plist file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): a file-like object. Raises: UnableToParseFile: when the file cannot be parsed.
354,484
def setup_alignak_logger(self): try: self.check_dir(self.logdir) setup_logger(logger_configuration_file=self.logger_configuration, log_dir=self.logdir, process_name=self.name, log_file=self.log_filename) ...
Setup alignak logger: - with the daemon log configuration properties - configure the global daemon handler (root logger) - log the daemon Alignak header - configure the global Alignak monitoring log This function is called very early on daemon start. The daemon is not yet forke...
354,485
def role_add(user, role): ** ret = {} roles = role.split() known_roles = role_list().keys() valid_roles = [r for r in roles if r in known_roles] log.debug( , roles, known_roles, valid_roles, ) if valid_roles: res = __salt__[](.format( ...
Add role to user user : string username role : string role name CLI Example: .. code-block:: bash salt '*' rbac.role_add martine netcfg salt '*' rbac.role_add martine netcfg,zfssnap
354,486
def fillna( self, value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs ): if isinstance(value, BasePandasDataset): new_query_compiler = self._default_to_pandas( ...
Fill NA/NaN values using the specified method. Args: value: Value to use to fill holes. This value cannot be a list. method: Method to use for filling holes in reindexed Series pad. ffill: propagate last valid observation forward to next valid bac...
354,487
def rndmask(shp, frc, dtype=None): r msk = np.asarray(np.random.uniform(-1.0, 1.0, shp), dtype=dtype) msk[np.abs(msk) > frc] = 1.0 msk[np.abs(msk) < frc] = 0.0 return msk
r"""Return random mask image with values in :math:`\{0,1\}`. Parameters ---------- s : tuple Mask array shape frc : float Desired fraction of zero pixels dtype : data-type or None, optional (default None) Data type of mask array Returns ------- msk : ndarray Mas...
354,488
def cluster(args): from jcvi.utils.grouper import Grouper from itertools import combinations p = OptionParser(cluster.__doc__) p.add_option("--slop", default=False, action="store_true", help="allow minor variation in terminal 5 UTR" + \ " start/stop position [default: ...
%prog cluster gffile Given a gff file of gene structures (multiple transcripts per gene locus), cluster/consolidate all transcripts based on shared splicing structure. If `slop` is enabled, clustering/consolidation will collapse any variation in terminal UTR lengths, keeping only the longest as repres...
354,489
def _add_crc(self, frame): crc = struct.pack(, crc16(frame)) return frame + crc
Add CRC to modbus frame (for RTU mode) :param frame: modbus RTU frame :type frame: str (Python2) or class bytes (Python3) :returns: modbus RTU frame with CRC :rtype: str (Python2) or class bytes (Python3)
354,490
def parse() -> dict: parser = ArgumentParser() parser.add_argument(, , action=, default=False) return vars(parser.parse_args())
Parse command line arguments
354,491
async def fetchrow(self, *args, timeout=None): data = await self.__bind_execute(args, 1, timeout) if not data: return None return data[0]
Execute the statement and return the first row. :param str query: Query text :param args: Query arguments :param float timeout: Optional timeout value in seconds. :return: The first row as a :class:`Record` instance.
354,492
def plot_emg_graphical_statistical(time, signal, max_sample_value, min_sample_value, avg_sample_value, std_sample_value): list_figures = [] list_figures.append(figure(x_axis_label=, y_axis_label=, x_range=(0, time[-1] + 0.50 * time[-1]), y_range=[-1.10, 1], **...
----- Brief ----- This plotting function ensures a graphical representation of maximum, minimum and average sample values registered on the entire EMG acquisition. ----------- Description ----------- Function intended to generate a single Bokeh figure with graphically describing and ide...
354,493
def create_database(self, name, character_set=None, collate=None): if character_set is None: character_set = "utf8" if collate is None: collate = "utf8_general_ci" self._database_manager.create(name=name, character_set=character_set, collate=colla...
Creates a database with the specified name. If a database with that name already exists, a BadRequest (400) exception will be raised.
354,494
def _read(self): while self._rxactive: try: rv = self._ep_in.read(self._ep_in.wMaxPacketSize) if self._isFTDI: status = rv[:2] if status[0] != 1 or status[1] != 0x60: log.in...
check ep for data, add it to queue and sleep for interval
354,495
def version(**kwargs): retry = kwargs.get("retry") if retry: click.echo() else: click.echo() try: current_version = get_current_version() except GitError as e: click.echo(click.style(str(e), ), err=True) return False click.echo(.format(current_versi...
Detects the new version according to git log and semver. Writes the new version number and commits it, unless the noop-option is True.
354,496
def action_findip(reader, *args): target_ips = set(args) for record in reader: if (record.srcaddr in target_ips) or (record.dstaddr in target_ips): print(record.to_message())
Find Flow Log records involving a specific IP or IPs.
354,497
def predict(self, eval_data, num_batch=None, merge_batches=True, reset=True, always_output_list=False, sparse_row_id_fn=None): assert self.binded and self.params_initialized if isinstance(eval_data, (ndarray.NDArray, np.ndarray)): if isinstance(eval_data, np.ndarray...
Runs prediction and collects the outputs. When `merge_batches` is ``True`` (by default), the return value will be a list ``[out1, out2, out3]``, where each element is formed by concatenating the outputs for all the mini-batches. When `always_output_list` is ``False`` (as by default), th...
354,498
def _destructively_move(self, dest_doc): if dest_doc is self: raise RuntimeError("Attempted to overwrite a document with itself") dest_doc.clear() if len(self._all_models) != 0: raise RuntimeError("_all_models still had stuff in it: %...
Move all data in this doc to the dest_doc, leaving this doc empty. Args: dest_doc (Document) : The Bokeh document to populate with data from this one Returns: None
354,499
def segment_lengths(neurites, neurite_type=NeuriteType.all): def _seg_len(sec): return np.linalg.norm(np.diff(sec.points[:, COLS.XYZ], axis=0), axis=1) return map_segments(_seg_len, neurites, neurite_type)
Lengths of the segments in a collection of neurites