code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def calc_osc_accels(self, osc_freqs, osc_damping=0.05, tf=None): if tf is None: tf = np.ones_like(self.freqs) else: tf = np.asarray(tf).astype(complex) resp = np.array([ self.calc_peak(tf * self._calc_sdof_tf(of, osc_damping)) for of in osc_freqs ...
Compute the pseudo-acceleration spectral response of an oscillator with a specific frequency and damping. Parameters ---------- osc_freq : float Frequency of the oscillator (Hz). osc_damping : float Fractional damping of the oscillator (dec). For example,...
def letter2num(letters, zbase=False): letters = letters.upper() res = 0 weight = len(letters) - 1 assert weight >= 0, letters for i, c in enumerate(letters): assert 65 <= ord(c) <= 90, c res += (ord(c) - 64) * 26**(weight - i) if not zbase: return res return res - 1
A = 1, C = 3 and so on. Convert spreadsheet style column enumeration to a number. Answers: A = 1, Z = 26, AA = 27, AZ = 52, ZZ = 702, AMJ = 1024 >>> from channelpack.pullxl import letter2num >>> letter2num('A') == 1 True >>> letter2num('Z') == 26 True >>> letter2num('AZ') == 52 ...
def generate_term(self, **kwargs): term_map = kwargs.pop('term_map') if hasattr(term_map, "termType") and\ term_map.termType == NS_MGR.rr.BlankNode.rdflib: return rdflib.BNode() if not hasattr(term_map, 'datatype'): term_map.datatype = NS_MGR.xsd.anyURI.rdflib...
Method generates a rdflib.Term based on kwargs
def _wait_for_finishing(self): self.state_machine_running = True self.__running_state_machine.join() self.__set_execution_mode_to_finished() self.state_machine_manager.active_state_machine_id = None plugins.run_on_state_machine_execution_finished() self.state_machine_runn...
Observe running state machine and stop engine if execution has finished
def _finalize(self, all_msg_errors=None): if all_msg_errors is None: all_msg_errors = [] for key in self.stored(): try: getattr(self, key) except (ValueError, TypeError) as err: all_msg_errors.append(err.args[0]) if all_msg_erro...
Access all the instance descriptors This wil trigger an exception if a required parameter is not set
def get_mem(device_handle): try: memory_info = pynvml.nvmlDeviceGetMemoryInfo(device_handle) return memory_info.used * 100.0 / memory_info.total except pynvml.NVMLError: return None
Get GPU device memory consumption in percent.
def sum(self, axis=None, keepdims=False): return self.numpy().sum(axis=axis, keepdims=keepdims)
Return sum along specified axis
def from_fs_path(path): scheme = 'file' params, query, fragment = '', '', '' path, netloc = _normalize_win_path(path) return urlunparse((scheme, netloc, path, params, query, fragment))
Returns a URI for the given filesystem path.
def GetOutputClasses(cls): for _, output_class in iter(cls._output_classes.items()): yield output_class.NAME, output_class
Retrieves the available output classes its associated name. Yields: tuple[str, type]: output class name and type object.
def to_xml_string(self): self.update_xml_element() xml = self.xml_element return etree.tostring(xml, pretty_print=True).decode('utf-8')
Exports the element in XML format. :returns: element in XML format. :rtype: str
def update(self, id, name=None, description=None, image_url=None, office_mode=None, share=None, **kwargs): path = '{}/update'.format(id) url = utils.urljoin(self.url, path) payload = { 'name': name, 'description': description, 'image_url': image...
Update the details of a group. .. note:: There are significant bugs in this endpoint! 1. not providing ``name`` produces 400: "Topic can't be blank" 2. not providing ``office_mode`` produces 500: "sql: Scan error on column index 14: sql/driver: couldn't convert ...
def add(self, logical_id, property, value): if not logical_id or not property: raise ValueError("LogicalId and property must be a non-empty string") if not value or not isinstance(value, string_types): raise ValueError("Property value must be a non-empty string") if logic...
Add the information that resource with given `logical_id` supports the given `property`, and that a reference to `logical_id.property` resolves to given `value. Example: "MyApi.Deployment" -> "MyApiDeployment1234567890" :param logical_id: Logical ID of the resource (Ex: MyLambdaF...
def getitem(self, index, context=None): try: methods = dunder_lookup.lookup(self, "__getitem__") except exceptions.AttributeInferenceError as exc: raise exceptions.AstroidTypeError(node=self, context=context) from exc method = methods[0] new_context = contextmod.b...
Return the inference of a subscript. This is basically looking up the method in the metaclass and calling it. :returns: The inferred value of a subscript to this class. :rtype: NodeNG :raises AstroidTypeError: If this class does not define a ``__getitem__`` method.
def users_setPhoto(self, *, image: Union[str, IOBase], **kwargs) -> SlackResponse: self._validate_xoxp_token() return self.api_call("users.setPhoto", files={"image": image}, data=kwargs)
Set the user profile photo Args: image (str): Supply the path of the image you'd like to upload. e.g. 'myimage.png'
async def enable_events(self) -> asyncio.Task: return await self._connection.ws_connect( on_message=self._ws_on_message, on_error=self._ws_on_error )
Connects to the websocket. Returns a listening task.
def mutate_rows(self, rows, retry=DEFAULT_RETRY): retryable_mutate_rows = _RetryableMutateRowsWorker( self._instance._client, self.name, rows, app_profile_id=self._app_profile_id, timeout=self.mutation_timeout, ) return retryable_mutate...
Mutates multiple rows in bulk. For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable_mutate_rows] :end-before: [END bigtable_mutate_rows] The method tries to update all specified rows. If some of the rows weren't updated, it would not...
def table_drop(self): for engine in self.engines(): tables = self._get_tables(engine, create_drop=True) logger.info('Drop all tables for %s', engine) self.metadata.drop_all(engine, tables=tables)
Drops all tables.
def _generate_collection(group, ax, ctype, colors): color = TREE_COLOR[ctype] collection = PolyCollection(group, closed=False, antialiaseds=True, edgecolors='face', facecolors=color) ax.add_collection(collection) if color not in colors: label = str(ctype).replace(...
Render rectangle collection
def dispatch_hook(cls, _pkt=None, *args, **kargs): if _pkt: attr_type = orb(_pkt[0]) return cls.registered_attributes.get(attr_type, cls) return cls
Returns the right RadiusAttribute class for the given data.
def _serialize(self, value, attr, obj): value = super(PhoneNumberField, self)._serialize(value, attr, obj) if value: value = self._format_phone_number(value, attr) return value
Format and validate the phone number user libphonenumber.
def uniquecols(df): bool_idx = df.apply(lambda col: len(np.unique(col)) == 1, axis=0) df = df.loc[:, bool_idx].iloc[0:1, :].reset_index(drop=True) return df
Return unique columns This is used for figuring out which columns are constant within a group
def _latex_labels(self, labels): config = self._configuration.get("latex_labels", {}) return [config.get(label, label) for label in labels]
LaTeX-ify labels based on information provided in the configuration.
def check_learns_zero_output_rnn(model, sgd, X, Y, initial_hidden=None): outputs, get_dX = model.begin_update(X, initial_hidden) Yh, h_n = outputs tupleDy = (Yh - Y, h_n) dX = get_dX(tupleDy, sgd=sgd) prev = numpy.abs(Yh.sum()) print(prev) for i in range(1000): outputs, get_dX = mode...
Check we can learn to output a zero vector
def get_one_ping_per_client(pings): if isinstance(pings.first(), binary_type): pings = pings.map(lambda p: json.loads(p.decode('utf-8'))) filtered = pings.filter(lambda p: "clientID" in p or "clientId" in p) if not filtered: raise ValueError("Missing clientID/clientId attribute.") if "cl...
Returns a single ping for each client in the RDD. THIS METHOD IS NOT RECOMMENDED: The ping to be returned is essentially selected at random. It is also expensive as it requires data to be shuffled around. It should be run only after extracting a subset with get_pings_properties.
def delete_function(FunctionName, Qualifier=None, region=None, key=None, keyid=None, profile=None): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if Qualifier: conn.delete_function( FunctionName=FunctionName, Qualifier=Qualifier) else...
Given a function name and optional version qualifier, delete it. Returns {deleted: true} if the function was deleted and returns {deleted: false} if the function was not deleted. CLI Example: .. code-block:: bash salt myminion boto_lambda.delete_function myfunction
def replace_orig_field(self, option): if option: option_new = list(option) for opt in option: if opt in self.trans_opts.fields: index = option_new.index(opt) option_new[index:index + 1] = get_translation_fields(opt) ...
Replaces each original field in `option` that is registered for translation by its translation fields. Returns a new list with replaced fields. If `option` contains no registered fields, it is returned unmodified. >>> self = TranslationAdmin() # PyFlakes >>> print(self.trans_o...
def splitext(filepath): exts = getattr(CRE_FILENAME_EXT.search(filepath), 'group', str)() return (filepath[:(-len(exts) or None)], exts)
Like os.path.splitext except splits compound extensions as one long one >>> splitext('~/.bashrc.asciidoc.ext.ps4.42') ('~/.bashrc', '.asciidoc.ext.ps4.42') >>> splitext('~/.bash_profile') ('~/.bash_profile', '')
def stringify(obj): out = obj if isinstance(obj, uuid.UUID): out = str(obj) elif hasattr(obj, 'strftime'): out = obj.strftime('%Y-%m-%dT%H:%M:%S.%f%z') elif isinstance(obj, memoryview): out = obj.tobytes() elif isinstance(obj, bytearray): out = bytes(obj) elif sys...
Return the string representation of an object. :param obj: object to get the representation of :returns: unicode string representation of `obj` or `obj` unchanged This function returns a string representation for many of the types from the standard library. It does not convert numeric or Boolean ...
def _ps_extract_pid(self, line): this_pid = self.regex['pid'].sub(r'\g<1>', line) this_parent = self.regex['parent'].sub(r'\g<1>', line) return this_pid, this_parent
Extract PID and parent PID from an output line from the PS command
def closed(self): closed = self._closing or self._closed if not closed and self._reader and self._reader.at_eof(): self._closing = closed = True self._loop.call_soon(self._do_close, None) return closed
True if connection is closed.
def extract_rzip (archive, compression, cmd, verbosity, interactive, outdir): cmdlist = [cmd, '-d', '-k'] if verbosity > 1: cmdlist.append('-v') outfile = util.get_single_outfile(outdir, archive) cmdlist.extend(["-o", outfile, archive]) return cmdlist
Extract an RZIP archive.
def byte_to_housecode(bytecode): hc = list(HC_LOOKUP.keys())[list(HC_LOOKUP.values()).index(bytecode)] return hc.upper()
Return an X10 housecode value from a byte value.
def processor_coordinates_to_pnum(mesh_shape, coord): ret = 0 multiplier = 1 for c, d in zip(coord[::-1], mesh_shape.to_integer_list[::-1]): ret += multiplier * c multiplier *= d return ret
Inverse of pnum_to_processor_coordinates. Args: mesh_shape: a Shape coord: a list of integers with length len(mesh_shape) Returns: an integer less than len(mesh_shape)
def register_action (self, action_name, command='', bound_list = [], flags = [], function = None): assert isinstance(action_name, basestring) assert isinstance(command, basestring) assert is_iterable(bound_list) assert is_iterable(flags) assert function i...
Creates a new build engine action. Creates on bjam side an action named 'action_name', with 'command' as the command to be executed, 'bound_variables' naming the list of variables bound when the command is executed and specified flag. If 'function' is not None, it should be a ca...
def _default_next_char(particle): return particle.chars[ (len(particle.chars) - 1) * particle.time // particle.life_time]
Default next character implementation - linear progression through each character.
def process_file(vcs, commit, force, gitlint_config, file_data): filename, extra_data = file_data if force: modified_lines = None else: modified_lines = vcs.modified_lines( filename, extra_data, commit=commit) result = linters.lint(filename, modified_lines, gitlint_config) ...
Lint the file Returns: The results from the linter.
def write(self, *messages): for i in self.graph.outputs_of(BEGIN): for message in messages: self[i].write(message)
Push a list of messages in the inputs of this graph's inputs, matching the output of special node "BEGIN" in our graph.
def fix_type(typ, size, additional=None): if additional is not None: my_types = types + additional else: my_types = types for t, info in my_types: if callable(t): matches = t(typ) else: matches = t == typ if matches: if callable(inf...
Fix up creating the appropriate struct type based on the information in the column.
def secret_list(backend,path): click.echo(click.style('%s - Getting the list of secrets' % get_datetime(), fg='green')) check_and_print( DKCloudCommandRunner.secret_list(backend.dki,path))
List all Secrets
def images(self, filter='global'): if filter and filter not in ('my_images', 'global'): raise DOPException('"filter" must be either "my_images" or "global"') params = {} if filter: params['filter'] = filter json = self.request('/images', method='GET', params=param...
This method returns all the available images that can be accessed by your client ID. You will have access to all public images by default, and any snapshots or backups that you have created in your own account. Optional parameters filter: String, either "my_images" ...
def validate(self, raise_unsupported=False): fields = set(self.keys()) flattened_required_fields = set() required_errors = [] for field in self.required_fields: found = False if isinstance(field, (list, tuple)): for real_f in field: ...
Checks if the Entry instance includes all the required fields of its type. If ``raise_unsupported`` is set to ``True`` it will also check for potentially unsupported types. If a problem is found, an InvalidStructure exception is raised.
def intercalate(elems, list_): ensure_sequence(elems) ensure_sequence(list_) if len(list_) <= 1: return list_ return sum( (elems + list_[i:i+1] for i in xrange(1, len(list_))), list_[:1])
Insert given elements between existing elements of a list. :param elems: List of elements to insert between elements of ``list_` :param list_: List to insert the elements to :return: A new list where items from ``elems`` are inserted between every two elements of ``list_``
def to_bytes(s): if isinstance(s, six.binary_type): return s if isinstance(s, six.string_types): return s.encode('utf-8') raise TypeError('want string or bytes, got {}', type(s))
Return s as a bytes type, using utf-8 encoding if necessary. @param s string or bytes @return bytes
def unique(segments, digits=5): segments = np.asanyarray(segments, dtype=np.float64) inverse = grouping.unique_rows( segments.reshape((-1, segments.shape[2])), digits=digits)[1].reshape((-1, 2)) inverse.sort(axis=1) index = grouping.unique_rows(inverse) unique = segments[index[0]] ...
Find unique line segments. Parameters ------------ segments : (n, 2, (2|3)) float Line segments in space digits : int How many digits to consider when merging vertices Returns ----------- unique : (m, 2, (2|3)) float Segments with duplicates merged
def url(self, name): key = blobstore.create_gs_key('/gs' + name) return images.get_serving_url(key)
Ask blobstore api for an url to directly serve the file
def update_dimensions(self, dims): if isinstance(dims, collections.Mapping): dims = dims.itervalues() for dim in dims: if isinstance(dim, dict): self.update_dimension(**dim) elif isinstance(dim, Dimension): self._dims[dim.name] = dim ...
Update multiple dimension on the cube. .. code-block:: python cube.update_dimensions([ {'name' : 'ntime', 'global_size' : 10, 'lower_extent' : 2, 'upper_extent' : 7 }, {'name' : 'na', 'global_size' : 3, 'lower_extent' : 2, 'upper_exte...
def open(filename, frame='unspecified'): data = Image.load_data(filename).astype(np.uint8) return ColorImage(data, frame)
Creates a ColorImage from a file. Parameters ---------- filename : :obj:`str` The file to load the data from. Must be one of .png, .jpg, .npy, or .npz. frame : :obj:`str` A string representing the frame of reference in which the new image ...
def add_book(self, publisher=None, place=None, date=None): imprint = {} if date is not None: imprint['date'] = normalize_date(date) if place is not None: imprint['place'] = place if publisher is not None: imprint['publisher'] = publisher self._...
Make a dictionary that is representing a book. :param publisher: publisher name :type publisher: string :param place: place of publication :type place: string :param date: A (partial) date in any format. The date should contain at least a year :type date: ...
async def set_max_relative_mod(self, max_mod, timeout=OTGW_DEFAULT_TIMEOUT): if isinstance(max_mod, int) and not 0 <= max_mod <= 100: return None cmd = OTGW_CMD_MAX_MOD status = {} ret = await self._wait_for_cmd(cmd, max_mod, timeout) ...
Override the maximum relative modulation from the thermostat. Valid values are 0 through 100. Clear the setting by specifying a non-numeric value. Return the newly accepted value, '-' if a previous value was cleared, or None on failure. This method is a coroutine
def find_module_registrations(c_file): global pattern if c_file is None: return set() with io.open(c_file, encoding='utf-8') as c_file_obj: return set(re.findall(pattern, c_file_obj.read()))
Find any MP_REGISTER_MODULE definitions in the provided c file. :param str c_file: path to c file to check :return: List[(module_name, obj_module, enabled_define)]
def gui_call(self, method, *args, **kwdargs): my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait()
General method for synchronously calling into the GUI. This waits until the method has completed before returning.
def maybe_reverse_features(self, feature_map): if not self._was_reversed: return inputs = feature_map.pop("inputs", None) targets = feature_map.pop("targets", None) inputs_seg = feature_map.pop("inputs_segmentation", None) targets_seg = feature_map.pop("targets_segmentation", None) inputs_...
Reverse features between inputs and targets if the problem is '_rev'.
def _create_index(self): if not self.index_exists: index_settings = {} headers = {'Content-Type': 'application/json', 'DB-Method': 'POST'} url = '/v2/exchange/db/{}/{}'.format(self.domain, self.data_type) r = self.tcex.session.post(url, json=index_settings, header...
Create index if it doesn't exist.
def vecdiff(htilde, hinterp, sample_points, psd=None): vecdiffs = numpy.zeros(sample_points.size-1, dtype=float) for kk,thisf in enumerate(sample_points[:-1]): nextf = sample_points[kk+1] vecdiffs[kk] = abs(_vecdiff(htilde, hinterp, thisf, nextf, psd=psd)) return vecdiffs
Computes a statistic indicating between which sample points a waveform and the interpolated waveform differ the most.
def decode(codec, stream, image): OPENJP2.opj_decode.argtypes = [CODEC_TYPE, STREAM_TYPE_P, ctypes.POINTER(ImageType)] OPENJP2.opj_decode.restype = check_error OPENJP2.opj_decode(codec, stream, image)
Reads an entire image. Wraps the openjp2 library function opj_decode. Parameters ---------- codec : CODEC_TYPE The JPEG2000 codec stream : STREAM_TYPE_P The stream to decode. image : ImageType Output image structure. Raises ------ RuntimeError If th...
def _append_theme_dir(self, name): path = "[{}]".format(get_file_directory() + "/" + name) self.tk.call("lappend", "auto_path", path)
Append a theme dir to the Tk interpreter auto_path
def go_to_marker(self, row, col, table_type): if table_type == 'dataset': marker_time = self.idx_marker.property('start')[row] marker_end_time = self.idx_marker.property('end')[row] else: marker_time = self.idx_annot_list.property('start')[row] marker_end_...
Move to point in time marked by the marker. Parameters ---------- row : QtCore.int column : QtCore.int table_type : str 'dataset' table or 'annot' table, it works on either
def stop_all_periodic_tasks(self, remove_tasks=True): for task in self._periodic_tasks: task.stop(remove_task=remove_tasks)
Stop sending any messages that were started using bus.send_periodic :param bool remove_tasks: Stop tracking the stopped tasks.
def wrap_around_re(aClass, wildcard, advice): matcher = re.compile(wildcard) for aMember in dir(aClass): realMember = getattr(aClass, aMember) if callable(realMember) and aMember[:6]!="__wrap" and \ aMember[:9]!="__proceed" and \ matcher.match(aMember): wrap_aro...
Same as wrap_around but works with regular expression based wildcards to map which methods are going to be used.
def kwargstr(self): temp = [' [--' + k + (' ' + str(v) if v is not False else '') + ']' for k, v in self.defaults.items()] return ''.join(temp)
Concatenate keyword arguments into a string.
def lookup(self, name: str): if name in self._moduleMap: return self._moduleMap[name] (module_name, type_name, fragment_name) = self.split_typename(name) if not module_name and type_name: click.secho('not able to lookup symbol: {0}'.format(name), fg='red') ret...
lookup a symbol by fully qualified name.
def wnvald(insize, n, window): assert isinstance(window, stypes.SpiceCell) assert window.dtype == 1 insize = ctypes.c_int(insize) n = ctypes.c_int(n) libspice.wnvald_c(insize, n, ctypes.byref(window)) return window
Form a valid double precision window from the contents of a window array. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnvald_c.html :param insize: Size of window. :type insize: int :param n: Original number of endpoints. :type n: int :param window: Input window. :type wi...
def parse(response): tokens = {r[0]: r[1] for r in [r.split('=') for r in response.split("&")]} if 'dummy' in tokens: del tokens['dummy'] if re.match('\D\d+$', tokens.keys()[0]): set_tokens = [] for key, value in tokens: key = re.match('^(.+\D)...
Parse a postdata-style response format from the API into usable data
def get_ports(self, scan_id, target): if target: for item in self.scans_table[scan_id]['targets']: if target == item[0]: return item[1] return self.scans_table[scan_id]['targets'][0][1]
Get a scan's ports list. If a target is specified it will return the corresponding port for it. If not, it returns the port item of the first nested list in the target's list.
def UpdateInfo(self): ret = vmGuestLib.VMGuestLib_UpdateInfo(self.handle.value) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
Updates information about the virtual machine. This information is associated with the VMGuestLibHandle. VMGuestLib_UpdateInfo requires similar CPU resources to a system call and therefore can affect performance. If you are concerned about performance, minimize the number of...
def _coerce_topic(topic): if not isinstance(topic, string_types): raise TypeError('topic={!r} must be text'.format(topic)) if not isinstance(topic, text_type): topic = topic.decode('ascii') if len(topic) < 1: raise ValueError('invalid empty topic name') if len(topic) > 249: ...
Ensure that the topic name is text string of a valid length. :param topic: Kafka topic name. Valid characters are in the set ``[a-zA-Z0-9._-]``. :raises ValueError: when the topic name exceeds 249 bytes :raises TypeError: when the topic is not :class:`unicode` or :class:`str`
def generate(self, chars, format='png'): im = self.generate_image(chars) out = BytesIO() im.save(out, format=format) out.seek(0) return out
Generate an Image Captcha of the given characters. :param chars: text to be generated. :param format: image file format
def _convert_to_floats(self, data): for key, value in data.items(): data[key] = float(value) return data
Convert all values in a dict to floats
def load_all(self, group): for ep in iter_entry_points(group=group): plugin = ep.load() plugin(self.__config)
Loads all plugins advertising entry points with the given group name. The specified plugin needs to be a callable that accepts the everest configurator as single argument.
def fixtags(self, text): text = _guillemetLeftPat.sub(ur'\1&nbsp;\2', text) text = _guillemetRightPat.sub(ur'\1&nbsp;', text) return text
Clean up special characters, only run once, next-to-last before doBlockLevels
def save(self): if self.SacrificeDate: self.Active = False super(PlugEvents, self).save()
Over-rides the default save function for PlugEvents. If a sacrifice date is set for an object in this model, then Active is set to False.
def list_subdomains_next_page(self): uri = self._paging.get("subdomain", {}).get("next_uri") if uri is None: raise exc.NoMoreResults("There are no more pages of subdomains " "to list.") return self._list_subdomains(uri)
When paging through subdomain results, this will return the next page, using the same limit. If there are no more results, a NoMoreResults exception will be raised.
def send(self): self.log.info("Saying hello (%d)." % self.counter) f = stomper.Frame() f.unpack(stomper.send(DESTINATION, 'hello there (%d)' % self.counter)) self.counter += 1 self.transport.write(f.pack())
Send out a hello message periodically.
def lb_edit(lbn, settings, profile='default'): settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn return _do_http(settings, profile)['worker.result.type'] == 'OK'
Edit the loadbalancer settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" salt '*' modjk.lb_edit loadbalancer1 "{'vl...
def _extract_jump_targets(stmt): targets = [ ] if isinstance(stmt, ailment.Stmt.Jump): targets.append(stmt.target.value) elif isinstance(stmt, ailment.Stmt.ConditionalJump): targets.append(stmt.true_target.value) targets.append(stmt.false_target.value) ...
Extract goto targets from a Jump or a ConditionalJump statement. :param stmt: The statement to analyze. :return: A list of known concrete jump targets. :rtype: list
def build(self): monomers = [HelicalHelix(major_pitch=self.major_pitches[i], major_radius=self.major_radii[i], major_handedness=self.major_handedness[i], aa=self.aas[i], minor_heli...
Builds a model of a coiled coil protein using input parameters.
def shutdown(self): 'Close the hub connection' log.info("shutting down") self._peer.go_down(reconnect=False, expected=True)
Close the hub connection
def get_models(self): try: rels = self.rels_ext.content except RequestFailed: if "RELS-EXT" not in self.ds_list.keys(): return [] else: raise return list(rels.objects(self.uriref, modelns.hasModel))
Get a list of content models the object subscribes to.
def get_parser_class(): global distro if distro == 'Linux': Parser = parser.LinuxParser if not os.path.exists(Parser.get_command()[0]): Parser = parser.UnixIPParser elif distro in ['Darwin', 'MacOSX']: Parser = parser.MacOSXParser elif distro == 'Windows': Par...
Returns the parser according to the system platform
def _inject_addresses(self, subjects): logger.debug('Injecting addresses to %s: %s', self, subjects) with self._resolve_context(): addresses = tuple(subjects) thts, = self._scheduler.product_request(TransitiveHydratedTargets, [BuildFileAddresses(addresse...
Injects targets into the graph for each of the given `Address` objects, and then yields them. TODO: See #5606 about undoing the split between `_inject_addresses` and `_inject_specs`.
def add_rule(self, rule_class, target_class=_Nothing): if isinstance(target_class, Iterable): for cls in target_class: self._rules[cls] = rule_class else: self._rules[target_class] = rule_class
Adds an authorization rule. :param rule_class: a class of authorization rule. :param target_class: (optional) a class or an iterable with classes to associate the rule with.
def _update_visible_blocks(self, *args): self._visible_blocks[:] = [] block = self.firstVisibleBlock() block_nbr = block.blockNumber() top = int(self.blockBoundingGeometry(block).translated( self.contentOffset()).top()) bottom = top + int(self.blockBoundingRect(block)...
Updates the list of visible blocks
def add_hash(self, value): self.leaves.append(Node(codecs.decode(value, 'hex_codec'), prehashed=True))
Add a Node based on a precomputed, hex encoded, hash value.
def get_reader_factory_for(self, name, *, format=None): return self.get_factory_for(READER, name, format=format)
Returns a callable to build a reader for the provided filename, eventually forcing a format. :param name: filename :param format: format :return: type
def inverse_mod( a, m ): if a < 0 or m <= a: a = a % m c, d = a, m uc, vc, ud, vd = 1, 0, 0, 1 while c != 0: q, c, d = divmod( d, c ) + ( c, ) uc, vc, ud, vd = ud - q*uc, vd - q*vc, uc, vc assert d == 1 if ud > 0: return ud else: return ud + m
Inverse of a mod m.
def folder_name(self): name = self.site_packages_name if name is None: name = self.name return name
The name of the build folders containing this recipe.
def get_device_tree(self): root = DevNode(None, None, [], None) device_nodes = { dev.object_path: DevNode(dev, dev.parent_object_path, [], self._ignore_device(dev)) for dev in self.udisks } for node in device_nodes.values(): ...
Get a tree of all devices.
def retrieve_old_notifications(self): date = ago(days=DELETE_OLD) return Notification.objects.filter(added__lte=date)
Retrieve notifications older than X days, where X is specified in settings
def rpc_method(func=None, name=None, entry_point=ALL, protocol=ALL, str_standardization=settings.MODERNRPC_PY2_STR_TYPE, str_standardization_encoding=settings.MODERNRPC_PY2_STR_ENCODING): def decorated(_func): _func.modernrpc_enabled = True _func.modernrpc_name = name o...
Mark a standard python function as RPC method. All arguments are optional :param func: A standard function :param name: Used as RPC method name instead of original function name :param entry_point: Default: ALL. Used to limit usage of the RPC method for a specific set of entry points :param protoc...
def prepare_csv_read(data, field_names, *args, **kwargs): if hasattr(data, 'readlines') or isinstance(data, list): pass elif isinstance(data, basestring): data = open(data) else: raise TypeError('Unable to handle data of type %r' % type(data)) return csv.DictReader(data, field_na...
Prepare various input types for CSV parsing. Args: data (iter): Data to read field_names (tuple of str): Ordered names to assign to fields Returns: csv.DictReader: CSV reader suitable for parsing Raises: TypeError: Invalid value for data
def add_uniform_precip_event(self, intensity, duration): self.project_manager.setCard('PRECIP_UNIF', '') self.project_manager.setCard('RAIN_INTENSITY', str(intensity)) self.project_manager.setCard('RAIN_DURATION', str(duration.total_seconds()/60.0))
Add a uniform precip event
def get(): return { attr: getattr(Conf, attr) for attr in dir(Conf()) if not callable(getattr(Conf, attr)) and not attr.startswith("__") }
Gets the configuration as a dict
def list(self, full_properties=False, filter_args=None): uris_prop = self.adapter.port_uris_prop if not uris_prop: return [] uris = self.adapter.get_property(uris_prop) assert uris is not None uris = list(set(uris)) resource_obj_list = [] for uri in ur...
List the Ports of this Adapter. If the adapter does not have any ports, an empty list is returned. Authorization requirements: * Object-access permission to this Adapter. Parameters: full_properties (bool): Controls whether the full set of resource properties s...
def main(): argv = sys.argv[1:] returncode = 1 try: returncode = _main(os.environ, argv) except exceptions.InvalidArgument as error: if error.message: sys.stderr.write("Error: " + error.message + '\n') else: raise sys.exit(returncode)
The main command-line entry point, with system interactions.
def signal_wrapper(f): @wraps(f) def wrapper(*args, **kwds): args = map(convert, args) kwds = {convert(k): convert(v) for k, v in kwds.items()} return f(*args, **kwds) return wrapper
Decorator converts function's arguments from dbus types to python.
def finalize(self): super(StatisticsConsumer, self).finalize() self.result = zip(self.grid, map(self.statistics, self.result))
finalize for StatisticsConsumer
def to_records(cls, attr_names, value_matrix): return [cls.to_record(attr_names, record) for record in value_matrix]
Convert a value matrix to records to be inserted into a database. :param list attr_names: List of attributes for the converting records. :param value_matrix: Values to be converted. :type value_matrix: list of |dict|/|namedtuple|/|list|/|tuple| .. seealso:: :py:meth:`.to_re...
def ready_argument_list(self, arguments): ctype_args = [ None for _ in arguments] for i, arg in enumerate(arguments): if not isinstance(arg, (numpy.ndarray, numpy.number)): raise TypeError("Argument is not numpy ndarray or numpy scalar %s" % type(arg)) dtype_str =...
ready argument list to be passed to the C function :param arguments: List of arguments to be passed to the C function. The order should match the argument list on the C function. Allowed values are numpy.ndarray, and/or numpy.int32, numpy.float32, and so on. :type arguments: lis...
def send(self, msg_string, immediate=True): try: mailhost = api.get_tool("MailHost") mailhost.send(msg_string, immediate=immediate) except SMTPException as e: logger.error(e) return False except socket.error as e: logger.error(e) ...
Send the email via the MailHost tool
def generate_headline_from_description(sender, instance, *args, **kwargs): lines = instance.description.split('\n') headline = truncatewords(lines[0], 20) if headline[:-3] == '...': headline = truncatechars(headline.replace(' ...', ''), 250) else: headline = truncatechars(headline, 250) ...
Auto generate the headline of the node from the first lines of the description.