Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
350,400
def queue_status(self, client_id, msg): content = msg[] targets = content[] try: targets = self._validate_targets(targets) except: content = error.wrap_exception() self.session.send(self.query, "hub_error", content=content,...
Return the Queue status of one or more targets. if verbose: return the msg_ids else: return len of each type. keys: queue (pending MUX jobs) tasks (pending Task jobs) completed (finished jobs from both queues)
350,401
def intent(self, intent_name): def decorator(f): self._intent_view_funcs[intent_name] = f @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f return decorator
Decorator routes an Rogo IntentRequest. Functions decorated as an intent are registered as the view function for the Intent's URL, and provide the backend responses to give your Skill its functionality. @ask.intent('WeatherIntent') def weather(city): return statement('I predi...
350,402
def __get_hooks_for_dll(self, event): result = [] if self.__apiHooks: path = event.get_module().get_filename() if path: lib_name = PathOperations.pathname_to_filename(path).lower() for hook_lib, hook_api_list in compat.iteritems(self.__api...
Get the requested API hooks for the current DLL. Used by L{__hook_dll} and L{__unhook_dll}.
350,403
def add_text(self, text): t = self._r.add_t(text) return _Text(t)
Returns a newly appended |_Text| object (corresponding to a new ``<w:t>`` child element) to the run, containing *text*. Compare with the possibly more friendly approach of assigning text to the :attr:`Run.text` property.
350,404
def search(self, buffer, freshlen, searchwindowsize=None): absurd_match = len(buffer) first_match = absurd_match for index, s in self._strings: if searchwindowsize is None: ...
This searches 'buffer' for the first occurence of one of the search strings. 'freshlen' must indicate the number of bytes at the end of 'buffer' which have not been searched before. It helps to avoid searching the same, possibly big, buffer over and over again. See class spawn for the ...
350,405
def run(self): if self.on_start: self.on_start(self) try: result = self.func(*self.func_args, **self.func_kwargs) except Exception as err: self.to_failed() if self.on_error: self.on_error(self, err) raise ...
Runs the task. This fires the ``on_start`` hook function first (if present), passing the task itself. Then it runs the target function supplied via ``Task.to_call`` with its arguments & stores the result. If the target function succeeded, the ``on_success`` hook function is ...
350,406
def payload(self, value): if not isinstance(value, rdfvalue.RDFValue): raise RuntimeError("Payload must be an RDFValue.") self.Set("args", value.SerializeToString()) if value._age is not None: self.args_age = value._age self.args_rdf_name = value.__class__.__name__
Automatically encode RDFValues into the message.
350,407
async def list_with_limit(cls, limit, offset, status: str = , fields: Iterable[str] = None) -> Sequence[dict]: ALIVETERMINATEDLOST if fields is None: fields = ( ...
Fetches the list of agents with the given status with limit and offset for pagination. :param limit: number of agents to get :param offset: offset index of agents to get :param status: An upper-cased string constant representing agent status (one of ``'ALIVE'``, ``'TERMINATE...
350,408
def v2_extension_encode(self, target_network, target_system, target_component, message_type, payload): registered return MAVLink_v2_extension_message(target_network, target_system, target_component, message_type, payload)
Message implementing parts of the V2 payload specs in V1 frames for transitional support. target_network : Network ID (0 for broadcast) (uint8_t) target_system : System ID (0 for broadcast) (uint8_t) target_component : Comp...
350,409
def parse_log(self, bowtie_log): print("is here!") regexes = { : { : r"(\\d+) \\([\\d\\.]+%\\) aligned 0 times", : r"(\\d+) \\([\\d\\.]+%\\) aligned exactly 1 time", : r"(\\d+) \\([\\d\\.]+%\\) aligned >1 times" ...
Parse a bowtie log file. This is a bowtie log parsing method that populates the :py:attr:`self.n_reads, self.align_0x, self.align_1x, self.align_mt1x and self.overall_rate` attributes with data from the log file. Disclamer: THIS METHOD IS HORRIBLE BECAUSE THE BOWTIE LOG IS HORRIBLE. ...
350,410
def _count_devices(self): number_of_devices = ctypes.c_uint() if ctypes.windll.user32.GetRawInputDeviceList( ctypes.POINTER(ctypes.c_int)(), ctypes.byref(number_of_devices), ctypes.sizeof(RawInputDeviceList)) == -1: warn("Call to GetR...
See what Windows' GetRawInputDeviceList wants to tell us. For now, we are just seeing if there is at least one keyboard and/or mouse attached. GetRawInputDeviceList could be used to help distinguish between different keyboards and mice on the system in the way Linux can. Howeve...
350,411
def smsc(self): if self._smscNumber == None: try: readSmsc = self.write() except SmscNumberUnknownError: pass if cscaMatch: self._smscNumber = cscaMatch.group(1) return self._smscNumber
:return: The default SMSC number stored on the SIM card
350,412
def _convert_name(filenames, shuffle=False): if not isinstance(filenames, (list, tuple)): filenames = [filenames] base = filenames[0] if shuffle: base += if len(filenames) > 1: return base + "_and_{}_more.hdf5".format(len(filenames)-1) else: return base + ".hdf5...
Convert a filename (or list of) to a filename with .hdf5 and optionally a -shuffle suffix
350,413
def getall(self, key, type=None): values = [] for k, v in self._items: if k == key: if type is not None: try: values.append(type(v)) except ValueError: pass else: ...
Return a list of values for the given key. If `type` is not None, all values will be converted by calling `type` with the value as argument. if type() raises `ValueError`, the value will not appear in the result list.
350,414
def list_files(self, prefix="", flat=False): for f in self._interface.list_files(prefix, flat): yield f
List the files in the layer with the given prefix. flat means only generate one level of a directory, while non-flat means generate all file paths with that prefix. Here's how flat=True handles different senarios: 1. partial directory name prefix = 'bigarr' - lists the '' directory and...
350,415
def _get_timeframe_bounds(self, timeframe, bucket_width): if bucket_width: bucket_width_seconds = bucket_width bucket_width = epoch_time_to_kronos_time(bucket_width) if timeframe[][] == : end_time = kronos_time_now() original_end_time = end_time duration...
Get a `bucket_width` aligned `start_time` and `end_time` from a `timeframe` dict
350,416
def _generate_union_class_variant_creators(self, ns, data_type): for field in data_type.fields: if not is_void_type(field.data_type): field_name = fmt_func(field.name) field_name_reserved_check = fmt_func(field.name, check_reserved=True) if is...
Each non-symbol, non-any variant has a corresponding class method that can be used to construct a union with that variant selected.
350,417
def movingAverage(requestContext, seriesList, windowSize): if not seriesList: return [] windowInterval = None if isinstance(windowSize, six.string_types): delta = parseTimeOffset(windowSize) windowInterval = to_seconds(delta) if windowInterval: previewSeconds = wind...
Graphs the moving average of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour' or '5min' (See ``from / until`` in the render\_api_ for example...
350,418
def main(): ep = requests.get(TRELLO_API_DOC).content root = html.fromstring(ep) links = root.xpath() pages = [requests.get(TRELLO_API_DOC + u) for u in links if u.endswith()] endpoints = [] for page in pages: root = html.fromstring(page.content) sections = ro...
Prints the complete YAML.
350,419
def nearest_neighbors(self, word, top_k=10): point = self[word] diff = self.vectors - point distances = np.linalg.norm(diff, axis=1) top_ids = distances.argsort()[1:top_k+1] return [self.vocabulary.id_word[i] for i in top_ids]
Return the nearest k words to the given `word`. Args: word (string): single word. top_k (integer): decides how many neighbors to report. Returns: A list of words sorted by the distances. The closest is the first. Note: L2 metric is used to calculate distances.
350,420
def get_item(self, path_, default): section, path_ = self._get_section(path_) key = path_[-1] if key not in section: self.set_item(path_, default) return default xvalue = section[key] type_ = type(default) if type_ in (str...
Return item or default. In the latter, change file to have default. Arguments: path_ -- path to item in section/subsection structure. May be either: ["section", "subsection", ...] or "[/]section/subsection/..." (leading slash is tolerated) ...
350,421
def search_worker(self, regex, directory_path, names, binary=False, callback=None): try: result = DirectoryResult(directory_path) def find_matches(name): full_path = path.join(directory_path, name) file_contents = get_file_co...
build a DirectoryResult for the given regex, directory path, and file names
350,422
def set_lr_mult(self, args_lr_mult): self.lr_mult = {} if self.sym_info: attr, arg_names = self.sym_info for name in arg_names: if name in attr and in attr[name]: self.lr_mult[name] = float(attr[name][]) self.lr_mult.update(ar...
Sets an individual learning rate multiplier for each parameter. If you specify a learning rate multiplier for a parameter, then the learning rate for the parameter will be set as the product of the global learning rate `self.lr` and its multiplier. .. note:: The default learning rate m...
350,423
def right_to_left(self): self._entry_mode &= ~Command.MODE_INCREMENT self.command(self._entry_mode)
This is for text that flows Right to Left
350,424
def write(text, filename, encoding=, mode=): text, encoding = encode(text, encoding) with open(filename, mode) as textfile: textfile.write(text) return encoding
Write 'text' to file ('filename') assuming 'encoding' Return (eventually new) encoding
350,425
async def message_handler(self, event): chat = await event.get_chat() if event.is_group: if event.out: sprint(.format( event.text, get_display_name(chat) )) else: ...
Callback method for received events.NewMessage
350,426
def _validate(self, writing=True): if any([box.box_id != for box in self.box]): msg = ("Colour group boxes can only contain colour specification " "boxes.") self._dispatch_validation_error(msg, writing=writing)
Verify that the box obeys the specifications.
350,427
def cleanup(self): plots = self.traverse(lambda x: x, [Plot]) for plot in plots: if not isinstance(plot, (GenericCompositePlot, GenericElementPlot, GenericOverlayPlot)): continue for stream in set(plot.streams): stream._subscribers = [ ...
Cleans up references to the plot on the attached Stream subscribers.
350,428
def _new_master_key(self, key_id): _key_id = to_str(key_id) return KMSMasterKey(config=KMSMasterKeyConfig(key_id=key_id, client=self._client(_key_id)))
Returns a KMSMasterKey for the specified key_id. :param bytes key_id: KMS CMK ID :returns: KMS Master Key based on key_id :rtype: aws_encryption_sdk.key_providers.kms.KMSMasterKey :raises InvalidKeyIdError: if key_id is not a valid KMS CMK ID to which this key provider has access
350,429
def authenticate(self, token): if self.verify_token_callback: return self.verify_token_callback(token) if not token: return False name = self.token_manager.verify(token) if not name: return False return True
Authenticate a token :param token:
350,430
def _rgb2ycbcr(self, mode): self._check_modes(("RGB", "RGBA")) (self.channels[0], self.channels[1], self.channels[2]) = \ rgb2ycbcr(self.channels[0], self.channels[1], self.channels[2]) if self.fill_value is not None: ...
Convert the image from RGB mode to YCbCr.
350,431
def sample_stats_to_xarray(self): if self.model_fn is None or self.observed is None: return None log_likelihood = [] sample_size = self.posterior[0].shape[0] for i in range(sample_size): variables = {} for var_i, var_name in enumer...
Extract sample_stats from tfp trace.
350,432
def enter_unlinking_mode(self, group): msg = StandardSend(self._address, COMMAND_ENTER_UNLINKING_MODE_0X0A_NONE, cmd2=group) self._send_msg(msg)
Unlink a device from an All-Link group. Not supported by i1 devices.
350,433
def handleLocalJob(self, jobNode): if (not self.config.runCwlInternalJobsOnWorkers and jobNode.jobName.startswith(CWL_INTERNAL_JOBS)): return self.localBatch.issueBatchJob(jobNode) else: return None
To be called by issueBatchJobs. Returns the jobID if the jobNode has been submitted to the local queue, otherwise returns None
350,434
def pop(self): if self._count == 0: raise StreamEmptyError("Pop called on virtual stream walker without any data", selector=self.selector) self._count = self._count - 1 return self.reading
Pop a reading off of this virtual stream and return it.
350,435
def custodian_archive(packages=None): modules = {, } if packages: modules = filter(None, modules.union(packages)) return PythonPackageArchive(*sorted(modules))
Create a lambda code archive for running custodian. Lambda archive currently always includes `c7n` and `pkg_resources`. Add additional packages in the mode block. Example policy that includes additional packages .. code-block:: yaml policy: name: lambda-archive-example re...
350,436
def get_cached_response(self, key): cached_value = self.data.get(key, _CACHE_MISS) is_found = cached_value is not _CACHE_MISS return CachedResponse(is_found, key, cached_value)
Retrieves a CachedResponse for the provided key. Args: key (string) Returns: A CachedResponse with is_found status and value.
350,437
def checkplot_png(lspinfo, times, mags, errs, varepoch=, magsarefluxes=False, objectinfo=None, findercmap=, finderconvolve=None, findercachedir=, ...
This makes a checkplot PNG using the output from a period-finder routine. A checkplot is a 3 x 3 grid of plots like so:: [periodogram + objectinfo] [ unphased LC ] [period 1 phased LC] [ period 1 phased LC /2 ] [period 1 phased LC x2] [period 2 phased LC] [ period 3 phased LC ...
350,438
def plot_network(symbol, title="plot", save_format=, shape=None, dtype=None, node_attrs={}, hide_weights=True): try: from graphviz import Digraph except: raise ImportError("Draw network requires graphviz library") if not isinstance(symbol, Symbol): raise Ty...
Creates a visualization (Graphviz digraph object) of the given computation graph. Graphviz must be installed for this function to work. Parameters ---------- title: str, optional Title of the generated visualization. symbol: Symbol A symbol from the computation graph. The generated ...
350,439
def file_list(self): blacklist = [, ] working_tree = self.git.work_tree def recursive(path=): if os.path.basename(path) in blacklist: return 0, 0 if os.path.isdir(path): files = [] for file in os.listdir(path): ...
Lists all files in the working directory.
350,440
def _clear_ignore(endpoint_props): return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS and prop_val is not None )
Both _clear_dict and _ignore_keys in a single iteration.
350,441
def build(self, pre=None, shortest=False): if pre is None: pre = [] if shortest or rand.maybe(self.prob): raise errors.OptGram return super(Opt, self).build(pre, shortest=shortest)
Build the current ``Opt`` instance :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
350,442
def _queue_job(redis, queue_name, delegate, *args): log.info() with Connection(redis): q = Queue(queue_name) job = q.enqueue(delegate, *args) return job.id
creates a new job on the queue :param redis: redis :param delegate: method to be executed by the queue. Use fully qualified method name as String. :param args: arguments of the method :return: job_id
350,443
def read_infile(infile: Union[Path, str], from_words=False, word_column: int = WORD_COLUMN, pos_column: int = POS_COLUMN, tag_column: int = TAG_COLUMN, max_sents: int = -1, read_only_words: bool = False) -> List[Tuple[List, Union[List, None]]]: answer, curr_word_...
Reads input file in CONLL-U format Args: infile: a path to a file word_column: column containing words (default=1) pos_column: column containing part-of-speech labels (default=3) tag_column: column containing fine-grained tags (default=5) max_sents: maximal number of sents t...
350,444
def parse_fileshare_or_file_snapshot_parameter(url): if is_not_empty(url): if in url: try: tmp = url.split() if len(tmp) == 2: dateutil.parser.parse(tmp[1]) return tmp[0], tmp[1] except (ValueError, Ov...
Checks if the fileshare or file is a snapshot :param url str: file url :rtype: tuple :return: (url, snapshot)
350,445
def listFileChildren(self, logical_file_name=, block_name=, block_id=0): conn = self.dbi.connection() try: if not logical_file_name and not block_name and not block_id: dbsExceptionHandler(,\ "Logical_file_name, block_id or block_name is requi...
required parameter: logical_file_name or block_name or block_id returns: logical_file_name, child_logical_file_name, parent_file_id
350,446
def create_board(self, board_json): return trolly.board.Board( trello_client=self, board_id=board_json[], name=board_json[], data=board_json, )
Create Board object from a JSON object Returns: Board: The board from the given `board_json`.
350,447
def threatlist(self, ip: str): url_path = "/api/threatlist/{ip}".format(ip=ip) return self._request(path=url_path)
Return threatlist information we have for the given IPv{4,6} address with history of changes
350,448
def set_multi(self, mappings, time=100, compress_level=-1): mappings = mappings.items() msg = [] for key, value in mappings: if isinstance(key, tuple): key, cas = key else: cas = None if cas == 0: ...
Set multiple keys with its values on server. If a key is a (key, cas) tuple, insert as if cas(key, value, cas) had been called. :param mappings: A dict with keys/values :type mappings: dict :param time: Time in seconds that your key will expire. :type time: int ...
350,449
def url_to_query(url): q = {} (ignore, ignore, path, ignore, query, ignore) = urlparse(url) base = os.path.basename(path) if base not in (, ): return {} for (k, v) in parse_qsl(query): if k not in q: q[k] = v ...
Given a big huge bugzilla query URL, returns a query dict that can be passed along to the Bugzilla.query() method.
350,450
def to_df(self, method: str = , **kwargs) -> : ll = self._is_valid() if ll: print(ll[]) return None else: return self.sas.sasdata2dataframe(self.table, self.libref, self.dsopts, method, **kwargs)
Export this SAS Data Set to a Pandas Data Frame :param method: defaults to MEMORY; the original method. CSV is the other choice which uses an intermediary csv file; faster for large data :param kwargs: :return: Pandas data frame
350,451
def _do_mutate_retryable_rows(self): retryable_rows = [] index_into_all_rows = [] for index, status in enumerate(self.responses_statuses): if self._is_retryable(status): retryable_rows.append(self.rows[index]) index_into_all_rows.append(index)...
Mutate all the rows that are eligible for retry. A row is eligible for retry if it has not been tried or if it resulted in a transient error in a previous call. :rtype: list :return: The responses statuses, which is a list of :class:`~google.rpc.status_pb2.Status`. ...
350,452
def patch_django_for_autodoc(): ManagerDescriptor.__get__ = lambda self, *args, **kwargs: self.manager models.QuerySet.__repr__ = lambda self: self.__class__.__name__
Fix the appearance of some classes in autodoc. This avoids query evaluation.
350,453
def web_error_and_result(f): @wraps(f) def web_error_and_result_decorator(*args, **kwargs): return error_and_result_decorator_inner_fn(f, True, *args, **kwargs) return web_error_and_result_decorator
Same as error_and_result decorator, except: If no exception was raised during task execution, ONLY IN CASE OF WEB REQUEST formats task result into json dictionary {'data': task return value}
350,454
def _unescape(s, uri=False): out = while len(s) > 0: c = s[0] if c == : esc_c = s[1] if esc_c in (, ): out += six.unichr(int(s[2:6], base=16)) s = s[6:] continue else: ...
Iterative parser for string escapes.
350,455
def _load_dict_hierarchical(self, db_key: str) -> dict: db_keys = self._db.keys(pattern=db_key + ) my_dict = {} for _db_key in db_keys: if self._db.type(_db_key) == : db_values = self._db.lrange(_db_key, 0, -1) for i, value in enumerate(db_val...
Load a dictionary stored hierarchically at db_key.
350,456
def checkAuthentication(): if app.oidcClient is None: return if flask.request.endpoint == : return key = flask.session.get() or flask.request.args.get() if key is None or not app.cache.get(key): if in flask.request.args: raise exceptions.NotAuthenticatedExceptio...
The request will have a parameter 'key' if it came from the command line client, or have a session key of 'key' if it's the browser. If the token is not found, start the login process. If there is no oidcClient, we are running naked and we don't check. If we're being redirected to the oidcCallback we d...
350,457
def make_requests_session(): session = requests.Session() version = __import__().__version__ ua = "python-steam/{0} {1}".format(version, session.headers[]) session.headers[] = ua return session
:returns: requests session :rtype: :class:`requests.Session`
350,458
def _extractEgaNegFromSent( sentTokens, clausesDict, foundChains ): egaegaegaegaeinudegaegaegaegaega sonaEga = WordTemplate({ROOT:,POSTAG:}) verbEiJarel = WordTemplate({POSTAG:,FORM:}) verbEiJarel2 = WordTemplate({ROOT:, POSTAG:,FORM:}) verbTud = WordTemplate({POSTAG:,FORM:}) verb...
Meetod, mis tuvastab antud lausest 'ega'-predikaadiga seotud eituse(d): ega + sobiv verb. *) Juhtudel kui 'ega'-le j2rgneb juba tuvastatud, positiivse polaarsusega verbiahel (nt ahel mille alguses on käskivas kõneviisis verb), liidetakse 'ega' olemasoleva ahela ette ning muudetakse ahe...
350,459
def update(self): pids = fileops.readlines(self.paths[]) self.pids = [int(pid) for pid in pids if pid != ] self.n_procs = len(pids)
It updates process information of the cgroup.
350,460
def _escape(s): e = s e = e.replace(, ) e = e.replace(, ) e = e.replace(, ) e = e.replace("") e = e.replace(, ) return e
Helper method that escapes parameters to a SQL query.
350,461
def image_groups_create(self, filename, api_url=None, options=None, properties=None): return self.image_groups_get( ImageGroupHandle.create( self.get_api_references(api_url)[sco.REF_IMAGE_GROUPS_CREATE], filename, options, ...
Create new image group at given SCO-API by uploading local file. Expects an tar-archive containing images in the image group. Allows to update properties of created resource. Parameters ---------- filename : string Path to tar-archive on local disk api_url : ...
350,462
def get_flags(): flags = unitdata.kv().getrange(, strip=True) or {} return sorted(flags.keys())
Return a list of all flags which are set.
350,463
def white(cls, string, auto=False): return cls.colorize(, string, auto=auto)
Color-code entire string. :param str string: String to colorize. :param bool auto: Enable auto-color (dark/light terminal). :return: Class instance for colorized string. :rtype: Color
350,464
def update_email(strategy, details, user=None, *args, **kwargs): if user: email = details.get() if email and user.email != email: user.email = email strategy.storage.user.changed(user)
Update the user's email address using data from provider.
350,465
def removeAction(self, action): action = action.split() del self.ACTIONS[int(action[1])] return True
Remove Registered Action
350,466
def _create_mapping(grammar): termmap = dict() rulemap = dict() for r in grammar.rules: if len(r.right) == 1: h = hash(r.toSymbol) if h not in termmap: termmap[h] = set() termmap[h].add(r) else: ...
Create mapping between symbols and rules rewritable to these symbols. :param grammar: Grammar to use. :return: Tuple of two dictionaries. First dictionary maps rule to terminal hash. Second dictionary maps rule to nonterminals hash.
350,467
def _unsubscribe_myself(self): url = UNSUBSCRIBE_ENDPOINT return self._session.query(url, method=, raw=True, stream=False)
Unsubscribe this base station for all events.
350,468
def plot_registration(anat_nii, div_id, plot_params=None, order=(, , ), cuts=None, estimate_brightness=False, label=None, contour=None, compress=): plot_params = {} if plot_params is None else plot_params if cuts is None: raise...
Plots the foreground and background views Default order is: axial, coronal, sagittal
350,469
def clean_up(self): self.submenu.join() self.menu.clear_screen() self.menu.resume()
This class overrides this method
350,470
def doExperiment(cellDimensions, cellCoordinateOffsets, numObjects, featuresPerObject, objectWidth, numFeatures, useTrace, noiseFactor, moduleNoiseFactor, anchoringMet...
Learn a set of objects. Then try to recognize each object. Output an interactive visualization. @param cellDimensions (pair) The cell dimensions of each module @param cellCoordinateOffsets (sequence) The "cellCoordinateOffsets" parameter for each module
350,471
def get_sub_menu_template_names(self): site = self._contextual_vals.current_site level = self._contextual_vals.current_level handle = self.handle template_names = [] if settings.SITE_SPECIFIC_TEMPLATE_DIRS and site: hostname = site.hostname templa...
Returns a list of template names to search for when rendering a a sub menu for a specific flat menu object (making use of self.handle)
350,472
def split_segments(text, closing_paren=False): buf = StringIO() last_group = True continue elif character == constants.GROUP_END: val = buf.getvalue() if not buf.tell() or not closing_paren: ...
Return objects representing segments.
350,473
def main(**kwargs): if kwargs[] is None: kwargs[] = \ DEFAULT_TIME_FORMAT[:-3] if kwargs[] else DEFAULT_TIME_FORMAT if kwargs[]: curses.wrapper(countdown, **kwargs) else: seconds_elapsed, laps = curses.wrapper(stopwatch, **kwargs) for lap_index, lap_tim...
\b Starts a countdown to or from TIME. Example values for TIME: 10, '1h 5m 30s', '12:00', '2020-01-01', '2020-01-01 14:00 UTC'. \b If TIME is not given, termdown will operate in stopwatch mode and count forward. \b Hotkeys: \tL\tLap (stopwatch mode only) \tR\tReset \tSPACE\tPause...
350,474
def hardware_port_group_mode_support_performance(self, **kwargs): config = ET.Element("config") hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware") port_group = ET.SubElement(hardware, "port-group") name_key = ET.SubElement(port_group, "na...
Auto Generated Code
350,475
def update(self, data: TransDict, flags: Flags): for lang, lang_data in data.items(): self.update_lang(lang, lang_data, flags)
Update all langs at once
350,476
def make_query(search_term, querytype=): HoldingsQueryExpTypeQueryX-RAYSOLID-STATE NMRAdvancedKeywordQueryStructureIdQueryModifiedStructuresQueryAdvancedAuthorQueryMotifQueryNoLigandQueryactin networkorgPdbQuerydescriptionText Search for: actinkeywordsactinqueryTypeAdvancedKeywordQueryactin network1D7M3W3D4A7H4A7L4...
Repackage strings into a search dictionary This function takes a list of search terms and specifications and repackages it as a dictionary object that can be used to conduct a search Parameters ---------- search_term : str The specific term to search in the database. For specific query ty...
350,477
def create_x10(plm, housecode, unitcode, feature): from insteonplm.devices.ipdb import IPDB ipdb = IPDB() product = ipdb.x10(feature) deviceclass = product.deviceclass device = None if deviceclass: device = deviceclass(plm, housecode, unitcode) return device
Create an X10 device from a feature definition.
350,478
def free_vpcid_for_switch(vpc_id, nexus_ip): LOG.debug("free_vpcid_for_switch() called") if vpc_id != 0: update_vpc_entry([nexus_ip], vpc_id, False, False)
Free a vpc id for the given switch_ip.
350,479
def run_analysis(self, argv): args = self._parser.parse_args(argv) name_keys = dict(target_type=args.ttype, target_name=args.target, sim_name=args.sim, fullpath=True) orig_dir = NAME_FACTORY.targetdir(**name_ke...
Run this analysis
350,480
def mousePressEvent(self, event): if sys.platform.startswith() and event.button() == Qt.MidButton: self.calltip_widget.hide() self.setFocus() event = QMouseEvent(QEvent.MouseButtonPress, event.pos(), Qt.LeftButton, Qt.LeftButton,...
Reimplement Qt method
350,481
def save_ical(self, ical_location): data = self.cal.to_ical() with open(ical_location, ) as ical_file: ical_file.write(data.decode())
Save the calendar instance to a file
350,482
def call(self, method, params, callback=None): cur_id = self._next_id() if callback: self._callbacks[cur_id] = callback self.send({: , : cur_id, : method, : params})
Call a method on the server Arguments: method - the remote server method params - an array of commands to send to the method Keyword Arguments: callback - a callback function containing the return data
350,483
def get_task_instance(dag_id, task_id, execution_date): dagbag = DagBag() if dag_id not in dagbag.dags: error_message = "Dag id {} not found".format(dag_id) raise DagNotFound(error_message) dag = dagbag.get_dag(dag_id) if not dag.has_task(task_id): error_message...
Return the task object identified by the given dag_id and task_id.
350,484
def stop(self): self.running = False try: self.commands_thread.kill() except: pass try: self.lock.set() if self.config["debug"]: self.log("lock set, exiting") for module in self....
Set the Event lock, this will break all threads' loops.
350,485
def copy(self, tagname, **kwargs): new_kwargs = { : self.replacement, : self.whitelist, : self.safe_mode, : self.log_rejects, : self.ending_slash } new_kwargs.update(**kwargs) return TagWrap(tagname, **new_kwargs)
Returns a new instance of `TagWrap` using the given *tagname* that has all the same attributes as this instance. If *kwargs* is given they will override the attributes of the created instance.
350,486
def main(argv=None): if len(argv): comPort, commands = commands.split(None, 1) sendCommands(comPort, commands) return 0
Send X10 commands when module is used from the command line. This uses syntax similar to sendCommands, for example: x10.py com2 A1 On, A2 Off, B All Off
350,487
def _create_ema_callback(self): with self.cached_name_scope(): size = tf.cast(self.queue.size(), tf.float32, name=) size_ema_op = add_moving_summary(size, collection=None, decay=0.5)[0].op ret = RunOp( lambda: size_ema_op, run_before=Fals...
Create a hook-only callback which maintain EMA of the queue size. Also tf.summary.scalar the EMA.
350,488
def zip_exposure(exposure_xml, archive_zip=, log=logging.info): archive_zip = archive_zip or exposure_xml[:-4] + if os.path.exists(archive_zip): sys.exit( % archive_zip) [exp] = Exposure.read_headers([exposure_xml]) files = [exposure_xml] + exp.datafiles general.zipfiles(files, archive...
Zip an exposure.xml file with all its .csv subfiles (if any)
350,489
def handle_data(self, ts, msg): try: chan_id, *data = msg except ValueError as e: raise FaultyPayloadError("handle_data(): %s - %s" % (msg, e)) self._heartbeats[chan_id] = ts if data[0] == : self._handle_hearbeat(ts, chan_id) ...
Passes msg to responding data handler, determined by its channel id, which is expected at index 0. :param ts: timestamp, declares when data was received by the client :param msg: list or dict of websocket data :return:
350,490
def set_pid_file(self, fpath, before_priv_drop=True, safe=False): command = if not before_priv_drop: command += if safe: command = + command self._set(command, fpath) return self._section
Creates pidfile before or after privileges drop. :param str|unicode fpath: File path. :param bool before_priv_drop: Whether to create pidfile before privileges are dropped. .. note:: Vacuum is made after privileges drop, so it may not be able to delete PID file if it was c...
350,491
def unknown_command(self, args): mode_mapping = self.master.mode_mapping() mode = args[0].upper() if mode in mode_mapping: self.master.set_mode(mode_mapping[mode]) return True return False
handle mode switch by mode name as command
350,492
def validate(schema_file, config_file, deprecation): result = validator_from_config_file(config_file, schema_file) result.validate(error_on_deprecated=deprecation) for error in result.errors(): click.secho( % error, err=True, fg=) for warning in result.warnings(): click.secho( % ...
Validate a configuration file against a confirm schema.
350,493
def _subtoken_ids_to_tokens(self, subtokens): escaped_tokens = "".join([ self.subtoken_list[s] for s in subtokens if s < len(self.subtoken_list)]) escaped_tokens = escaped_tokens.split("_") ret = [] for token in escaped_tokens: if token: ret.append(_unescape...
Convert list of int subtoken ids to a list of string tokens.
350,494
def grad_named(fun, argname): t work on *args or **kwargs.' arg_index = getargspec(fun).args.index(argname) return grad(fun, arg_index)
Takes gradients with respect to a named argument. Doesn't work on *args or **kwargs.
350,495
def _set_tag(self, tag=None, tags=None, value=True): existing_tags = self._requirements.get("tags") if tags and not tag: existing_tags = merge(existing_tags, tags) self._requirements["tags"] = existing_tags elif tag and not tags: existing_tags[tag] = ...
Sets the value of a specific tag or merges existing tags with a dict of new tags. Either tag or tags must be None. :param tag: Tag which needs to be set. :param tags: Set of tags which needs to be merged with existing tags. :param value: Value to set for net tag named by :param tag. ...
350,496
def download_slides(self): return self.presentation.client.download_all(self.presentation.metadata[], self.tmp_dir)
Download all SWF slides. The location of the slides files are returned. A DownloadError is raised if at least one of the slides cannot be download..
350,497
def _compute_non_linear_term(self, pga4nl, bnl): fnl = np.zeros(pga4nl.shape) a1 = 0.03 a2 = 0.09 pga_low = 0.06 idx = pga4nl <= a1 fnl[idx] = bnl[idx] * np.log(pga_low / 0.1) idx = np.where((pga4nl > a1) & (pga4nl <= a2)) del...
Compute non-linear term, equation (8a) to (8c), pag 108.
350,498
def getAttributeValueData(self, index): offset = self._get_attribute_offset(index) return self.m_attributes[offset + const.ATTRIBUTE_IX_VALUE_DATA]
Return the data of the attribute at the given index :param index: index of the attribute
350,499
def field_to_dict(self, field): value = getattr(self, field) if isinstance(value, (list, tuple)): return [self.value_to_dict(val) for val in value] return self.value_to_dict(value)
Read field value and converts to dict if possible