code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
def _print_foreign_playlist_copy_error(self): self.operation_mode = self.window_mode = NORMAL_MODE self.refreshBody() txt = self._show_help(txt, FOREIGN_PLAYLIST_COPY_ERROR_MODE, caption = , prompt = , is_message=True)
reset previous message
def extract_from_urllib3(): util.ssl_.SSLContext = orig_util_SSLContext util.HAS_SNI = orig_util_HAS_SNI util.ssl_.HAS_SNI = orig_util_HAS_SNI util.IS_SECURETRANSPORT = False util.ssl_.IS_SECURETRANSPORT = False
Undo monkey-patching by :func:`inject_into_urllib3`.
def cycle(self): messages = self.poll_datafeeds() notifications = self.process_notifications(messages) self.draw_notifications(notifications)
Cycles through notifications with latest results from data feeds.
def right(self): if self._has_real(): return self._data.real_right return self._data.right
Right coordinate.
def build_server_from_argparser(description=None, server_klass=None, handler_klass=None): import argparse def _argp_dir_type(arg): if not os.path.isdir(arg): raise argparse.ArgumentTypeError("{0} is not a valid directory".format(repr(arg))) return arg def _argp_port_type(arg): if not arg.isdigit(): r...
Build a server from command line arguments. If a ServerClass or HandlerClass is specified, then the object must inherit from the corresponding AdvancedHTTPServer base class. :param str description: Description string to be passed to the argument parser. :param server_klass: Alternative server class to use. :type ...
def hexstr(text): 0xff00ff000x0X text = text.strip().lower() if text.startswith((, )): text = text[2:] if not text: raise s_exc.BadTypeValu(valu=text, name=, mesg=) try: s_common.uhex(text) except (binascii.Error, ValueE...
Ensure a string is valid hex. Args: text (str): String to normalize. Examples: Norm a few strings: hexstr('0xff00') hexstr('ff00') Notes: Will accept strings prefixed by '0x' or '0X' and remove them. Returns: str: Normalized hex string.
def _create_network_doscript(self, network_file_path): LOG.debug( % network_file_path) network_doscript = os.path.join(network_file_path, ) tar = tarfile.open(network_doscript, "w") for file in os.listdir(network_file_path): file_name = os....
doscript: contains a invokeScript.sh which will do the special work The network.doscript contains network configuration files and it will be used by zvmguestconfigure to configure zLinux os network when it starts up
def gif_summary(name, tensor, max_outputs=3, fps=10, collections=None, family=None): tensor = tf.convert_to_tensor(tensor) if len(tensor.get_shape()) != 5: raise ValueError("Assuming videos given as tensors in the format " "[batch, time, height, width, channels] but got o...
Outputs a `Summary` protocol buffer with gif animations. Args: name: Name of the summary. tensor: A 5-D `uint8` `Tensor` of shape `[batch_size, time, height, width, channels]` where `channels` is 1 or 3. max_outputs: Max number of batch elements to generate gifs for. fps: frames per second of t...
def universal_anisotropy(self): return 5. * self.g_voigt / self.g_reuss + \ self.k_voigt / self.k_reuss - 6.
returns the universal anisotropy value
def _playsoundWin(sound, block = True): s mp3play: https://github.com/michaelgundlach/mp3play I never would have tried using windll.winmm without seeing his code. \n Error for command:\n \n playsound_open "" aliassettime format millisecondsstatuslengthplayfrom 0 to', durationInMS.decode(...
Utilizes windll.winmm. Tested and known to work with MP3 and WAVE on Windows 7 with Python 2.7. Probably works with more file formats. Probably works on Windows XP thru Windows 10. Probably works with all versions of Python. Inspired by (but not copied from) Michael Gundlach <gundlach@gmail.com>'s mp3p...
def p_unit_list(self, p): if isinstance(p[1], list): if len(p) >= 3: if isinstance(p[2], list): p[1].extend(p[2]) else: p[1].append(p[2]) else: p[1] = [p[1]] p[0] = p[1]
unit_list : unit_list unit | unit
def _process_datum(self, data, input_reader, ctx, transient_shard_state): if data is not input_readers.ALLOW_CHECKPOINT: self.slice_context.incr(context.COUNTER_MAPPER_CALLS) handler = transient_shard_state.handler if isinstance(handler, map_job.Mapper): handler(self.slice_context, ...
Process a single data piece. Call mapper handler on the data. Args: data: a datum to process. input_reader: input reader. ctx: mapreduce context transient_shard_state: transient shard state. Returns: True if scan should be continued, False if scan should be stopped.
def new_transaction(self, timeout, durability, transaction_type): connection = self._connect() return Transaction(self._client, connection, timeout, durability, transaction_type)
Creates a Transaction object with given timeout, durability and transaction type. :param timeout: (long), the timeout in seconds determines the maximum lifespan of a transaction. :param durability: (int), the durability is the number of machines that can take over if a member fails during a ...
def fit(sim_mat, D_len, cidx): min_energy = np.inf for j in range(3): inds = [np.argmin([sim_mat[idy].get(idx, 0) for idx in cidx]) for idy in range(D_len) if idy in sim_mat] cidx = [] energy = 0 for i in np.unique(inds): indsi = np.where(inds == i)[...
Algorithm maximizes energy between clusters, which is distinction in this algorithm. Distance matrix contains mostly 0, which are overlooked due to search of maximal distances. Algorithm does not try to retain k clusters. D: numpy array - Symmetric distance matrix k: int - number of clusters
def jupyter_notebook_skeleton(): py_version = sys.version_info notebook_skeleton = { "cells": [], "metadata": { "kernelspec": { "display_name": "Python " + str(py_version[0]), "language": "python", "name": "python" + str(py_version...
Returns a dictionary with the elements of a Jupyter notebook
def register_plugin(self): self.profiler.datatree.sig_edit_goto.connect(self.main.editor.load) self.profiler.redirect_stdio.connect( self.main.redirect_internalshell_stdio) self.main.add_dockwidget(self) profiler_act = create_action(self, _("Profile"), ...
Register plugin in Spyder's main window
def build(self): if ((self.allowMethods is None or len(self.allowMethods) == 0) and (self.denyMethods is None or len(self.denyMethods) == 0)): raise NameError() policy = { : self.principal_id, : { : self.version, ...
Generates the policy document based on the internal lists of allowed and denied conditions. This will generate a policy with two main statements for the effect: one statement for Allow and one statement for Deny. Methods that includes conditions will have their own statement in the polic...
def update_id(self, sequence_id=None): if sequence_id: self.sequence_id = sequence_id self._set_ids(force=True) if self.dataset: self._update_names()
Alter the sequence id, and all of the names and ids derived from it. This often needs to be done after an IntegrityError in a multiprocessing run
def List(self, *branches, **kwargs): gs = [ _parse(code)._f for code in branches ] def h(x, state): ys = [] for g in gs: y, state = g(x, state) ys.append(y) return (ys, state) return self.__then__(h, **kwargs)
While `Seq` is sequential, `phi.dsl.Expression.List` allows you to split the computation and get back a list with the result of each path. While the list literal should be the most incarnation of this expresion, it can actually be any iterable (implements `__iter__`) that is not a tuple and yields a valid expresion. T...
async def _clean_shutdown(self): remaining_tasks = [] for task in self._tasks.get(None, []): self._logger.debug("Cancelling task at shutdown %s", task) task.cancel() remaining_tasks.append(task) asyncio.gather(*remaining_tasks, return_exce...
Cleanly shutdown the emulation loop.
async def open(self): self.store.register(self) while not self.finished: message = await self.messages.get() await self.publish(message)
Register with the publisher.
def included_profiles(self): profiles = [] for directory in self.tcex_json.get() or []: profiles.extend(self._load_config_include(directory)) return profiles
Load all profiles.
def is_valid_geometry(self): has_sites = (self.sites is not None or in self.inputs or in self.inputs) if not has_sites and not self.ground_motion_fields: return True if ( in self.inputs and not has_sites and not self.inputs...
It is possible to infer the geometry only if exactly one of sites, sites_csv, hazard_curves_csv, gmfs_csv, region is set. You did set more than one, or nothing.
def log_decl_method(func): from functools import wraps @wraps(func) def with_logging(*args, **kwargs): self = args[0] decl = args[2] log(DEBUG, u" {}: {} {}".format( self.state[], decl.name, serialize(decl.value).strip()).encode()) return func...
Decorate do_declartion methods for debug logging.
def Validate(self): self.pathspec.Validate() if (self.HasField("start_time") and self.HasField("end_time") and self.start_time > self.end_time): raise ValueError("Start time must be before end time.") if not self.path_regex and not self.data_regex and not self.path_glob: raise Val...
Ensure the pathspec is valid.
def titles(self, unique=False): if unique: return tools.uniqued(s.title for s in self._items) return [s.title for s in self._items]
Return a list of contained worksheet titles. Args: unique (bool): drop duplicates Returns: list: list of titles/name strings
def append(self, child, *args, **kwargs): if self.set is False or self.set is None: if inspect.isclass(child): if issubclass(child,AbstractSpanAnnotation): if in kwargs: self.set = kwargs[] elif isinstance(chi...
See :meth:`AbstractElement.append`
def _expandDH(self, sampling, lmax, lmax_calc): if self.normalization == : norm = 1 elif self.normalization == : norm = 2 elif self.normalization == : norm = 3 elif self.normalization == : norm = 4 else: raise V...
Evaluate the coefficients on a Driscoll and Healy (1994) grid.
def define_example_values(self, http_method, route, values, update=False): self.defined_example_values[(http_method.lower(), route)] = { : update, : values }
Define example values for a given request. By default, example values are determined from the example properties in the schema. But if you want to change the example used in the documentation for a specific route, and this method lets you do that. :param str http_method: An HTTP method...
def unpersist(self, blocking=False): self.is_cached = False self._jrdd.unpersist(blocking) return self
Mark the RDD as non-persistent, and remove all blocks for it from memory and disk. .. versionchanged:: 3.0.0 Added optional argument `blocking` to specify whether to block until all blocks are deleted.
def get_process_cmdline(self): if not pid_exists(self.pid): raise NoSuchProcess(self.pid, self._process_name) return _psutil_osx.get_process_cmdline(self.pid)
Return process cmdline as a list of arguments.
def extend_variables(raw_variables, override_variables): if not raw_variables: override_variables_mapping = ensure_mapping_format(override_variables) return override_variables_mapping elif not override_variables: raw_variables_mapping = ensure_mapping_format(raw_variables) ...
extend raw_variables with override_variables. override_variables will merge and override raw_variables. Args: raw_variables (list): override_variables (list): Returns: dict: extended variables mapping Examples: >>> raw_variables = [{"var1": "val1"}, {"var2": "val2"...
def recognise(self): if not isinstance(self.cube, Cube): raise ValueError("Use Solver.feed(cube) to feed the cube to solver.") result = "" for face in "LFRB": for square in self.cube.get_face(face)[0]: result += str(int(square == self.cube["U"]["U...
Recognise which is Cube's OLL case.
def simplify_U(theta, phi, lam): gate = U3Gate(theta, phi, lam) if abs(gate.params[0] % (2.0 * math.pi)) < _CUTOFF_PRECISION: gate = U1Gate(gate.params[0] + gate.params[1] + gate.params[2]) if isinstance(gate, U3Gate): if abs((gate.params[0] - math.pi / 2) % (2.0 * ma...
Return the gate u1, u2, or u3 implementing U with the fewest pulses. The returned gate implements U exactly, not up to a global phase. Args: theta, phi, lam: input Euler rotation angles for a general U gate Returns: Gate: one of IdGate, U1Gate, U2Gate, U3Gate.
def do_AUTOCOMPLETE(cmd, s): s = list(preprocess_query(s))[0] keys = [k.decode() for k in DB.smembers(edge_ngram_key(s))] print(white(keys)) print(magenta(.format(len(keys))))
Shows autocomplete results for a given token.
def get_rectangle(self, src): min_lon, min_lat, max_lon, max_lat = ( self.integration_distance.get_affected_box(src)) return (min_lon, min_lat), (max_lon - min_lon) % 360, max_lat - min_lat
:param src: a source object :returns: ((min_lon, min_lat), width, height), useful for plotting
def _get_filehandler_with_formatter(logname, formatter=None): handler = logging.FileHandler(logname) if formatter is not None: handler.setFormatter(formatter) return handler
Return a logging FileHandler for given logname using a given logging formatter :param logname: Name of the file where logs will be stored, ".log" extension will be added :param formatter: An instance of logging.Formatter or None if the default should be used :return:
def processFlat(self): niter = self.config["niters"] F = self._preprocess() F = U.normalize(F, norm_type=self.config["norm_feats"]) if F.shape[0] >= self.config["h"]: F = median_filter(F, M=self.config["h"]) ...
Main process. Returns ------- est_idxs : np.array(N) Estimated indeces for the segment boundaries in frames. est_labels : np.array(N-1) Estimated labels for the segments.
def load(self, draw_bbox = False, **kwargs): im = Image.new(, self.img_size) draw = None if draw_bbox: draw = ImageDraw.Draw(im) for sprite in self.images: data = sprite.load() sprite_im = Image.open(BytesIO(data)) size = sprite....
Makes the canvas. This could be far speedier if it copied raw pixels, but that would take far too much time to write vs using Image inbuilts
def _check_for_crypto_done(self): cv = self._crypto_offload.done_cv while not self.termination_check: result = None cv.acquire() while True: result = self._crypto_offload.pop_done_queue() if result is None: ...
Check queue for crypto done :param Downloader self: this
def delete_service_version(self, service_id , service_version=, mode=): defaultproductiondefaultmy_service_id return self._call_rest_api(, +service_id++mode++service_version, error=)
delete_service(self, service_id, service_version='default', mode='production') Deletes a Service version from Opereto :Parameters: * *service_id* (`string`) -- Service identifier * *service_version* (`string`) -- Service version. Default is 'default' * *mode* (`string`) -- deve...
def find_all_primitives(pad): result = [] for primitive in pad.GetListOfPrimitives(): result.append(primitive) if hasattr(primitive, "GetListOfFunctions"): result.extend(primitive.GetListOfFunctions()) if hasattr(primitive, "GetHistogram"): p = primitive.GetH...
Recursively find all primities on a pad, even those hiding behind a GetListOfFunctions() of a primitive
def get_full_path(self, fn_attr): if fn_attr.header.attr_type_id is not AttrTypes.FILE_NAME: raise MFTError("Need a filename attribute to compute full path.") orphan, path = self._compute_full_path(fn_attr.content.parent_ref, fn_attr.content.parent_seq) return (orphan, "\\"...
Returns the full path of a FILENAME. The NTFS filesystem allows for things called hardlinks. Hard links are saved, internally, as different filename attributes. Because of this, an entry can, when dealing with full paths, have multiple full paths. As such, this function receives a fn_a...
def parse(type: Type): def decorator(parser): EnvVar.parsers[type] = parser return parser return decorator
Register a parser for a attribute type. Parsers will be used to parse `str` type objects from either the commandline arguments or environment variables. Args: type: the type the decorated function will be responsible for parsing a environment variable to.
def do_first(self): pid = os.getpid() self.basename = os.path.join(self.tmpdir, + str(pid)) outfile = self.basename + filetype = self.file_type(self.srcfile) if (filetype == ): if (self.shell_call(self.pngtopnm + + self.srcfile + + outfile)): ...
Create PNM file from input image file.
def enable(name, **kwargs): * if _service_is_upstart(name): return _upstart_enable(name) executable = _get_service_exec() cmd = .format(executable, name) return not __salt__[](cmd, python_shell=False)
Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name>
def get_index_quote(self, code, as_json=False): url = self.index_url if self.is_valid_index(code): req = Request(url, None, self.headers) resp = self.opener.open(req) resp = byte_adaptor(resp) resp_list = json.load(resp)[] ...
params: code : string index code as_json: True|False returns: a dict | json quote for the given index
def data(self, root): value = self.dict() children = [node for node in root if isinstance(node.tag, basestring)] for attr, attrval in root.attrib.items(): attr = attr if self.attr_prefix is None else self.attr_prefix + attr value[attr] = self._fromstring(attrval)...
Convert etree.Element into a dictionary
def step(self, observations, raw_rewards, processed_rewards, dones, actions): assert isinstance(observations, np.ndarray) assert isinstance(raw_rewards, np.ndarray) assert isinstance(processed_rewards, np.ndarray) assert isinstance(dones, np.ndarray) assert isinstance(actions, np.ndarray) ...
Record the information obtained from taking a step in all envs. Records (observation, rewards, done) in a new time-step and actions in the current time-step. If any trajectory gets done, we move that trajectory to completed_trajectories. Args: observations: ndarray of first dimension self.b...
def log_player_roll(self, player, roll): self._logln(.format(player.color, roll, if int(roll) == 2 else ))
:param player: catan.game.Player :param roll: integer or string, the sum of the dice
def run_from_argv(self, argv): try: return self.main(args=argv[2:], standalone_mode=False) except click.ClickException as e: if getattr(e.ctx, , False): raise e.show() sys.exit(e.exit_code)
Called when run from the command line.
def stft(func=None, **kwparams): from numpy.fft import fft, ifft return stft.base(transform=fft, inverse_transform=ifft)(func, **kwparams)
Short Time Fourier Transform for complex data. Same to the default STFT strategy, but with new defaults. This is the same to: .. code-block:: python stft.base(transform=numpy.fft.fft, inverse_transform=numpy.fft.ifft) See ``stft.base`` docs for more.
def to_struct(cls, name=None): if name is None: name = cls.__name__ basic_attrs = dict([(attr_name, value) for attr_name, value in cls.get_attrs() if isinstance(value, Column)]) if not basic_attrs: return No...
Convert the TreeModel into a compiled C struct
def latsph(radius, lon, lat): radius = ctypes.c_double(radius) lon = ctypes.c_double(lon) lat = ctypes.c_double(lat) rho = ctypes.c_double() colat = ctypes.c_double() lons = ctypes.c_double() libspice.latsph_c(radius, lon, lat, ctypes.byref(rho), ctypes.byref(colat), ...
Convert from latitudinal coordinates to spherical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latsph_c.html :param radius: Distance of a point from the origin. :param lon: Angle of the point from the XZ plane in radians. :param lat: Angle of the point from the XY plane in radi...
def is_logged_in(username=None): if username: if not isinstance(username, (list, tuple)): username = [username] return in session and get_username() in username return in session
Checks if user is logged in if `username` is passed check if specified user is logged in username can be a list
def check(self, line_info): "Allow ! and !! in multi-line statements if multi_line_specials is on" if line_info.continue_prompt \ and self.prefilter_manager.multi_line_specials: if line_info.esc == ESC_MAGIC: return self.prefilte...
Allow ! and !! in multi-line statements if multi_line_specials is on
def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if not os.path.exists(os.path.join(root, ".git")): if verbose: print("no .git in %s" % root) raise NotThisMethod("no .git directory") GITS = ["git"] if sys.platform == "win32": GITS = ["git...
Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree.
def find_all(string, sub, start=None, end=None, ignore_case=False, **kwargs): if ignore_case: sub = sub.lower() string = string.lower() while True: start = string.find(sub, start, end) if start == -1: return yield start start += len(sub)
Return all indices in string s where substring sub is found, such that sub is contained in the slice s[start:end]. >>> list(find_all('The quick brown fox jumps over the lazy dog', 'fox')) [16] >>> list(find_all('The quick brown fox jumps over the lazy dog', 'mountain')) [] >>> list(find_all('...
def user_sessions(self, user_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/sessions api_path = "/api/v2/users/{user_id}/sessions.json" api_path = api_path.format(user_id=user_id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/sessions#list-sessions
def get_keyvault(access_token, subscription_id, rgname, vault_name): endpoint = .join([get_rm_endpoint(), , subscription_id, , rgname, , vault_name, , KEYVAULT_API]) return do_get(endpoint, access_token)
Gets details about the named key vault. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. vault_name (str): Name of the key vault. Returns: HTTP response. JSON body of key...
def trigger_installed(connection: connection, table: str, schema: str=): installed = False log(.format(schema, table), logger_name=_LOGGER_NAME) statement = SELECT_TRIGGER_STATEMENT.format( table=table, schema=schema ) result = execute(connection, statement) if result: ...
Test whether or not a psycopg2-pgevents trigger is installed for a table. Parameters ---------- connection: psycopg2.extensions.connection Active connection to a PostGreSQL database. table: str Table whose trigger-existence will be checked. schema: str Schema to which the ta...
def _scrape_document(self): mock_response = self._new_mock_response( self._response, self._get_temp_path(, ) ) self._item_session.request = self._request self._item_session.response = mock_response self._processing_rule.scrape_document(item_session) ...
Extract links from the DOM.
def slack_ver(): if _meta_.slackware_version in ["off", "OFF"]: sv = Utils().read_file("/etc/slackware-version") version = re.findall(r"\d+", sv) if len(sv) > 2: return (".".join(version[:2])) else: return (".".join(version)) else: return _me...
Open file and read Slackware version
def get_matching_rules(tweet): if is_original_format(tweet): rules = tweet.get("matching_rules") else: gnip = tweet.get("gnip") rules = gnip.get("matching_rules") if gnip else None return rules
Retrieves the matching rules for a tweet with a gnip field enrichment. Args: tweet (Tweet): the tweet Returns: list: potential ``[{"tag": "user_tag", "value": "rule_value"}]`` pairs from standard rulesets or None if no rules or no matching_rules field is found. \n More...
def _postprocess_variants(record_file, data, ref_file, out_file): if not utils.file_uptodate(out_file, record_file): with file_transaction(data, out_file) as tx_out_file: cmd = ["dv_postprocess_variants.py", "--ref", ref_file, "--infile", record_file, "--outfile", tx_out_...
Post-process variants, converting into standard VCF file.
def ns_prefix(self, prefix, ns_uri): self._element.set_ns_prefix(prefix, ns_uri) return self
Set the namespace prefix of the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.set_ns_prefix`.
def element_type(self, type_): return self.__find_xxx_type( type_, self.element_type_index, self.element_type_typedef, )
returns reference to the class value\\mapped type declaration
def scp_data_length(self): if self._scp_data_length is None: data = self.get_software_version(255, 255, 0) self._scp_data_length = data.buffer_size return self._scp_data_length
The maximum SCP data field length supported by the machine (bytes).
def walk(self, where="/"): _tables() self._check_if_open() for g in self._handle.walk_groups(where): if getattr(g._v_attrs, , None) is not None: continue groups = [] leaves = [] for child in g._v_children.values(): ...
Walk the pytables group hierarchy for pandas objects This generator will yield the group path, subgroups and pandas object names for each group. Any non-pandas PyTables objects that are not a group will be ignored. The `where` group itself is listed first (preorder), then each of its ...
def get_image(conn, vm_): images = conn.list_images() vm_image = config.get_cloud_config_value(, vm_, __opts__) if not six.PY3: vm_image = vm_image.encode(, ) for img in images: if isinstance(img.id, six.string_types) and not six.PY3: img_id = img.id.encode(, ) ...
Return the image object to use
def nodeprep(string, allow_unassigned=False): chars = list(string) _nodeprep_do_mapping(chars) do_normalization(chars) check_prohibited_output( chars, ( stringprep.in_table_c11, stringprep.in_table_c12, stringprep.in_table_c21, string...
Process the given `string` using the Nodeprep (`RFC 6122`_) profile. In the error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is raised.
def _map_to_cfg(self): exit_statements_per_run = self.chosen_exits new_exit_statements_per_run = defaultdict(list) while len(exit_statements_per_run): for block_address, exits in exit_statements_per_run.items(): for stmt_idx, exit_target in exits: ...
Map our current slice to CFG. Based on self._statements_per_run and self._exit_statements_per_run, this method will traverse the CFG and check if there is any missing block on the path. If there is, the default exit of that missing block will be included in the slice. This is because Slicecutor...
def get_tasker2_slabs(self, tol=0.01, same_species_only=True): sites = list(self.sites) slabs = [] sortedcsites = sorted(sites, key=lambda site: site.c) nlayers_total = int(round(self.lattice.c / self.oriented_unit_cell.latti...
Get a list of slabs that have been Tasker 2 corrected. Args: tol (float): Tolerance to determine if atoms are within same plane. This is a fractional tolerance, not an absolute one. same_species_only (bool): If True, only that are of the exact same specie...
def schedule(self, callback, *args, **kwargs): self._executor.submit(callback, *args, **kwargs)
Schedule the callback to be called asynchronously in a thread pool. Args: callback (Callable): The function to call. args: Positional arguments passed to the function. kwargs: Key-word arguments passed to the function. Returns: None
def fgm(self, x, labels, targeted=False): with tf.GradientTape() as tape: tape.watch(x) loss_obj = LossCrossEntropy(self.model, smoothing=0.) loss = loss_obj.fprop(x=x, y=labels) if targeted: loss = -loss grad = tape.gradient(loss, x) optimal_per...
TensorFlow Eager implementation of the Fast Gradient Method. :param x: the input variable :param targeted: Is the attack targeted or untargeted? Untargeted, the default, will try to make the label incorrect. Targeted will instead try to move in the direction ...
def _iac_sniffer(self, byte): if self.telnet_got_iac is False: if byte == IAC: self.telnet_got_iac = True return elif self.telnet_got_sb is True: if len(self.telnet_sb_buffe...
Watches incomming data for Telnet IAC sequences. Passes the data, if any, with the IAC commands stripped to _recv_byte().
def tokenize_init(spec): tokens = [Token(, , 0)] re_token = .join([ .format(name, regex) for name, regex in spec ]) return tokens, re_token
Initialize a tokenizer. Should only be called by the :func:`~textparser.Parser.tokenize` method in the parser.
def load_agent(self, overall_index: int=None): if not self.index_manager.has_free_slots(): return None if overall_index is None: overall_index = self.index_manager.get_new_index() else: self.index_manager.use_index(overall_index) agent = self....
Loads all data for overall_index from the overall config and also loads both presets :param overall_index: the index of the targeted agent :return agent: an Agent (gui_agent) class with all loaded values
def add_port(self, port): self.ports.append(port) if port.io_type not in self.port_seqs: self.port_seqs[port.io_type] = 0 self.port_seqs[port.io_type] += 1 port.sequence = self.port_seqs[port.io_type] return self
Add a port object to the definition :param port: port definition :type port: PortDef
def run_report_from_console(output_file_name, callback): print("The report uses a read-only access to the book.") print("Now enter the data or ^Z to continue:") result = callback() output = save_to_temp(result, output_file_name) webbrowser.open(output)
Runs the report from the command line. Receives the book url from the console.
def relation_get(attribute=None, unit=None, rid=None): _args = [, ] if rid: _args.append() _args.append(rid) _args.append(attribute or ) if unit: _args.append(unit) try: return json.loads(subprocess.check_output(_args).decode()) except ValueError: ret...
Get relation information
def associate_psds_to_multi_ifo_segments(opt, fd_segments, gwstrain, flen, delta_f, flow, ifos, dyn_range_factor=1., precision=None): for ifo in ifos: if gwstrain is not None: strain = gwstrain[ifo] el...
Associate PSDs to segments for all ifos when using the multi-detector CLI
def build(python=PYTHON): clean() local( "LIBRARY_PATH={library_path} CPATH={include_path} {python} " "setup.py build_ext --inplace".format( library_path=LIBRARY_PATH, include_path=INCLUDE_PATH, python=python, ))
Build the bigfloat library for in-place testing.
def _is_mosaic(dicom_input): if type(dicom_input) is list and type(dicom_input[0]) is list: header = dicom_input[0][0] else: header = dicom_input[0] if not in header or not in header.ImageType: return False if not in header or header.AcquisitionMatrix is Non...
Use this function to detect if a dicom series is a siemens 4d dataset NOTE: Only the first slice will be checked so you can only provide an already sorted dicom directory (containing one series)
def remove(self, rel_path, propagate=False): key = self._get_boto_key(rel_path) if key: key.delete()
Delete the file from the cache, and from the upstream
def consume_arguments(self, argument_list): if len(argument_list) == 0: return [] if argument_list[0] == self.arg_name: argument_list = argument_list[1:] if self.constraint is bool: self.value = not self.value else: ...
Takes arguments from a list while this parameter can accept them
def asset_create(self, name, items, tag=, description=, atype=): data = { : name, : description, : atype, : tag } if atype == : data[] = .join(items) if atype == : data[] = data[] = .join(items)...
asset_create_static name, ips, tags, description Create a new asset list with the defined information. UN-DOCUMENTED CALL: This function is not considered stable. :param name: asset list name (must be unique) :type name: string :param items: list of IP Addresses, CIDR, and Netw...
def qteNextApplet(self, numSkip: int=1, ofsApp: (QtmacsApplet, str)=None, skipInvisible: bool=True, skipVisible: bool=False, skipMiniApplet: bool=True, windowObj: QtmacsWindow=None): if isinstance(ofsA...
Return the next applet in cyclic order. If ``ofsApp=None`` then start cycling at the currently active applet. If ``ofsApp`` does not fit the selection criteria, then the cycling starts at the next applet in cyclic order that does. The returned applet is ``numSkip`` items in cyc...
def AddEventTags(self, event_tags): self._RaiseIfNotWritable() for event_tag in event_tags: self.AddEventTag(event_tag)
Adds event tags. Args: event_tags (list[EventTag]): event tags. Raises: IOError: when the storage file is closed or read-only or if the event tags cannot be serialized. OSError: when the storage file is closed or read-only or if the event tags cannot be serialized.
def _SendStruct(self, fmt, *args): data = struct.pack(fmt, *args) data_len = len(data) + 1 checksum = (data_len + sum(bytearray(data))) % 256 out = struct.pack("B", data_len) + data + struct.pack("B", checksum) self.ser.write(out)
Pack a struct (without length or checksum) and send it.
def _ensure_slack(self, connector: Any, retries: int, backoff: Callable[[int], float]) -> None: connector = self._env_var if connector is None else connector slack: SlackClient = _create_slack(connector) self._slack = _SlackClientWrapper( slack=slack, ...
Ensure we have a SlackClient.
def _keyboard_access(self, element): if not element.has_attribute(): tag = element.get_tag_name() if (tag == ) and (not element.has_attribute()): element.set_attribute(, ) elif ( (tag != ) and (tag != ) ...
Provide keyboard access for element, if it not has. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement
def mutate(self, mutation, timeout=None, metadata=None, credentials=None): return self.stub.Mutate(mutation, timeout=timeout, metadata=metadata, credentials=credentials)
Runs mutate operation.
def remove_namespace(doc, namespace): ns = .format(namespace) nsl = len(ns) for elem in doc.getiterator(): if elem.tag.startswith(ns): elem.tag = elem.tag[nsl:] return doc
Takes in a ElementTree object and namespace value. The length of that namespace value is removed from all Element nodes within the document. This effectively removes the namespace from that document. :param doc: lxml.etree :param namespace: Namespace that needs to be removed. :return: Returns the ...
def nl_complete_msg(sk, msg): nlh = msg.nm_nlh if nlh.nlmsg_pid == NL_AUTO_PORT: nlh.nlmsg_pid = nl_socket_get_local_port(sk) if nlh.nlmsg_seq == NL_AUTO_SEQ: nlh.nlmsg_seq = sk.s_seq_next sk.s_seq_next += 1 if msg.nm_protocol == -1: msg.nm_protocol = sk.s_proto ...
Finalize Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L450 This function finalizes a Netlink message by completing the message with desirable flags and values depending on the socket configuration. - If not yet filled out, the source address of the message (`nlmsg_pid`)...
def clearAndSetComboBoxes(self, axesNames): logger.debug("Collector clearAndSetComboBoxes: {}".format(axesNames)) check_is_a_sequence(axesNames) row = 0 self._deleteComboBoxes(row) self.clear() self._setAxesNames(axesNames) self._createComboBoxes(row) ...
Removes all comboboxes.
def define_standalone_options(parser, extra_options=None): c = config.parse_service_config() parser.add_option(, , action=, dest=, type=, help=, default=c.db.host) parser.add_option(, , action=, dest=, type=, help=, ...
Adds the options specific to the database connection. Parses the agency configuration files and uses its configuration as the default values.
def update_coordinates(self, filename, update_port_locations=True): if update_port_locations: xyz_init = self.xyz self = load(filename, compound=self, coords_only=True) self._update_port_locations(xyz_init) else: self = load(filename, compound=sel...
Update the coordinates of this Compound from a file. Parameters ---------- filename : str Name of file from which to load coordinates. Supported file types are the same as those supported by load() update_port_locations : bool, optional, default=True ...
def feedforward(inputs, num_units, scope="multihead_attention"): with tf.variable_scope(scope): params = {"inputs": inputs, "filters": num_units[0], "kernel_size": 1, "activation": tf.nn.relu, "use_bias": True} outputs = tf.layers.conv1...
Point-wise feed forward net. Args: inputs: A 3d tensor with shape of [N, T, C]. num_units: A list of two integers. scope: Optional scope for `variable_scope`. reuse: Boolean, whether to reuse the weights of a previous layer by the same name. Returns: A 3d tensor with the ...
def setup_callbacks(self): if PYGIT2_VERSION >= _LooseVersion(): self.remotecallbacks = pygit2.RemoteCallbacks( credentials=self.credentials) if not self.ssl_verify: self.remotecallbacks.certificate_check = \ ...
Assign attributes for pygit2 callbacks