code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def dump_stack_peek(data, separator = ' ', width = 16, arch = None): if data is None: return '' if arch is None: arch = win32.arch pointers = compat.keys(data) pointers.sort() result = '' if pointers: if arch == win32.ARCH_I386: ...
Dump data from pointers guessed within the given stack dump. @type data: str @param data: Dictionary mapping stack offsets to the data they point to. @type separator: str @param separator: Separator between the hexadecimal representation of each character. @type ...
def cmp(self,range2,overlap_size=0): if self.overlaps(range2,padding=overlap_size): return 0 if self.chr < range2.chr: return -1 elif self.chr > range2.chr: return 1 elif self.end < range2.start: return -1 elif self.start > range2.end: return 1 sys.stderr.write("ERROR: cmp function unexpcted sta...
the comparitor for ranges * return 1 if greater than range2 * return -1 if less than range2 * return 0 if overlapped :param range2: :param overlap_size: allow some padding for an 'equal' comparison (default 0) :type range2: GenomicRange :type overlap_size: int
def applyns(self, ns): if ns is None: return if not isinstance(ns, (list, tuple)): raise Exception("namespace must be a list or a tuple") if ns[0] is None: self.expns = ns[1] else: self.prefix = ns[0] self.nsprefixes[ns[0]] = ns...
Apply the namespace to this node. If the prefix is I{None} then this element's explicit namespace I{expns} is set to the URI defined by I{ns}. Otherwise, the I{ns} is simply mapped. @param ns: A namespace. @type ns: (I{prefix}, I{URI})
def Any(*validators): @wraps(Any) def built(value): error = None for validator in validators: try: return validator(value) except Error as e: error = e raise error return built
Combines all the given validator callables into one, running the given value through them in sequence until a valid result is given.
def row_sparse_data(self, row_id): if self._stype != 'row_sparse': raise RuntimeError("Cannot return a copy of Parameter %s via row_sparse_data() " \ "because its storage type is %s. Please use data() instead." \ %(self.name, self._stype)...
Returns a copy of the 'row_sparse' parameter on the same context as row_id's. The copy only retains rows whose ids occur in provided row ids. The parameter must have been initialized on this context before. Parameters ---------- row_id: NDArray Row ids to retain for ...
def validate_get_dbs(connection): remote_dbs = set(rethinkdb.db_list().run(connection)) assert remote_dbs return remote_dbs
validates the connection object is capable of read access to rethink should be at least one test database by default :param connection: <rethinkdb.net.DefaultConnection> :return: <set> list of databases :raises: ReqlDriverError AssertionError
def bonded(self, n1, n2, distance): if distance > self.max_length * self.bond_tolerance: return None deviation = 0.0 pair = frozenset([n1, n2]) result = None for bond_type in bond_types: bond_length = self.lengths[bond_type].get(pair) if (bond_...
Return the estimated bond type Arguments: | ``n1`` -- the atom number of the first atom in the bond | ``n2`` -- the atom number of the second atom the bond | ``distance`` -- the distance between the two atoms This method checks whether for the given pair...
def _get_go2nthdridx(self, gos_all): go2nthdridx = {} obj = GrouperInit.NtMaker(self) for goid in gos_all: go2nthdridx[goid] = obj.get_nt(goid) return go2nthdridx
Get GO IDs header index for each user GO ID and corresponding parent GO IDs.
def _request(self): caller_frame = inspect.getouterframes(inspect.currentframe())[1] args, _, _, values = inspect.getargvalues(caller_frame[0]) caller_name = caller_frame[3] kwargs = {arg: values[arg] for arg in args if arg != 'self'} func = reduce( lambda resource, n...
retrieve the caller frame, extract the parameters from the caller function, find the matching function, and fire the request
def get_all_completed_tasks(self, api_token, **kwargs): params = { 'token': api_token } return self._get('get_all_completed_items', params, **kwargs)
Return a list of a user's completed tasks. .. warning:: Requires Todoist premium. :param api_token: The user's login api_token. :type api_token: str :param project_id: Filter the tasks by project. :type project_id: str :param limit: The maximum number of tasks to return...
def change_view(self, change_in_depth): self.current_view_depth += change_in_depth if self.current_view_depth < 0: self.current_view_depth = 0 self.collapseAll() if self.current_view_depth > 0: for item in self.get_items(maxlevel=self.current_view_depth-1): ...
Change the view depth by expand or collapsing all same-level nodes
def compose_tree_path(tree, issn=False): if issn: return join( "/", ISSN_DOWNLOAD_KEY, basename(tree.issn) ) return join( "/", PATH_DOWNLOAD_KEY, quote_plus(tree.path).replace("%2F", "/"), )
Compose absolute path for given `tree`. Args: pub (obj): :class:`.Tree` instance. issn (bool, default False): Compose URL using ISSN. Returns: str: Absolute path of the tree, without server's address and protocol.
def start_http_server(self, port, args): LOGGER.info("Starting Tornado v%s HTTPServer on port %i Args: %r", tornado_version, port, args) http_server = httpserver.HTTPServer(self.app, **args) http_server.bind(port, family=socket.AF_INET) http_server.start(1) re...
Start the HTTPServer :param int port: The port to run the HTTPServer on :param dict args: Dictionary of arguments for HTTPServer :rtype: tornado.httpserver.HTTPServer
def file_length(in_file): fid = open(in_file) data = fid.readlines() fid.close() return len(data)
Function to return the length of a file.
def widget_from_tuple(o): if _matches(o, (Real, Real)): min, max, value = _get_min_max_value(o[0], o[1]) if all(isinstance(_, Integral) for _ in o): cls = IntSlider else: cls = FloatSlider return cls(value=value, min=min, max=max) ...
Make widgets from a tuple abbreviation.
def parse_xhtml_reaction_notes(entry): properties = {} if entry.xml_notes is not None: cobra_notes = dict(parse_xhtml_notes(entry)) if 'subsystem' in cobra_notes: properties['subsystem'] = cobra_notes['subsystem'] if 'gene_association' in cobra_notes: properties['...
Return reaction properties defined in the XHTML notes. Older SBML models often define additional properties in the XHTML notes section because structured methods for defining properties had not been developed. This will try to parse the following properties: ``SUBSYSTEM``, ``GENE ASSOCIATION``, ``EC NU...
def _load_profile(self, profile_name): default_profile = self._profile_list[0] for profile in self._profile_list: if profile.get('default', False): default_profile = profile if profile['display_name'] == profile_name: break else: ...
Load a profile by name Called by load_user_options
def make_primitive_extrapolate_ends(cas_coords, smoothing_level=2): try: smoothed_primitive = make_primitive_smoothed( cas_coords, smoothing_level=smoothing_level) except ValueError: smoothed_primitive = make_primitive_smoothed( cas_coords, smoothing_level=smoothing_level...
Generates smoothed helix primitives and extrapolates lost ends. Notes ----- From an input list of CA coordinates, the running average is calculated to form a primitive. The smoothing_level dictates how many times to calculate the running average. A higher smoothing_level generates a 'smoother' ...
def chage(username, lastday=None, expiredate=None, inactive=None, mindays=None, maxdays=None, root=None, warndays=None): cmd = ['chage'] if root: cmd.extend(['--root', root]) if lastday: cmd.extend(['--lastday', lastday]) if expiredate: cmd.extend(['--expiredate', expir...
Change user password expiry information :param str username: User to update :param str lastday: Set when password was changed in YYYY-MM-DD format :param str expiredate: Set when user's account will no longer be accessible in YYYY-MM-DD format. -1 will ...
def get_by_id(self, id): for child in self.children: if child[self.child_id_attribute] == id: return child else: continue return None
Return object based on ``child_id_attribute``. Parameters ---------- val : str Returns ------- object Notes ----- Based on `.get()`_ from `backbone.js`_. .. _backbone.js: http://backbonejs.org/ .. _.get(): http://backbonejs.org/...
def attach_tracker(self, stanza, tracker=None): if stanza.xep0184_received is not None: raise ValueError( "requesting delivery receipts for delivery receipts is not " "allowed" ) if stanza.type_ == aioxmpp.MessageType.ERROR: raise Value...
Return a new tracker or modify one to track the stanza. :param stanza: Stanza to track. :type stanza: :class:`aioxmpp.Message` :param tracker: Existing tracker to attach to. :type tracker: :class:`.tracking.MessageTracker` :raises ValueError: if the stanza is of type ...
def k_array_rank_jit(a): k = len(a) idx = a[0] for i in range(1, k): idx += comb_jit(a[i], i+1) return idx
Numba jit version of `k_array_rank`. Notes ----- An incorrect value will be returned without warning or error if overflow occurs during the computation. It is the user's responsibility to ensure that the rank of the input array fits within the range of possible values of `np.intp`; a sufficient...
def reset(self, index=None): points_handler_count = len(self.registration_view.points) if index is None: indexes = range(points_handler_count) else: indexes = [index] indexes = [i for i in indexes if i < points_handler_count] for i in indexes: ...
Reset the points for the specified index position. If no index is specified, reset points for all point handlers.
def naccess_available(): available = False try: subprocess.check_output(['naccess'], stderr=subprocess.DEVNULL) except subprocess.CalledProcessError: available = True except FileNotFoundError: print("naccess has not been found on your path. If you have already " "in...
True if naccess is available on the path.
def _fix_time(self, dt): if dt.tzinfo is not None: dt = dt.replace(tzinfo=None) return dt
Stackdistiller converts all times to utc. We store timestamps as utc datetime. However, the explicit UTC timezone on incoming datetimes causes comparison issues deep in sqlalchemy. We fix this by converting all datetimes to naive utc timestamps
def setup_task_signals(self, ): log.debug("Setting up task page signals.") self.task_user_view_pb.clicked.connect(self.task_view_user) self.task_user_add_pb.clicked.connect(self.task_add_user) self.task_user_remove_pb.clicked.connect(self.task_remove_user) self.task_dep_view_pb.c...
Setup the signals for the task page :returns: None :rtype: None :raises: None
def UsesArtifact(self, artifacts): if isinstance(artifacts, string_types): return artifacts in self.artifacts else: return any(True for artifact in artifacts if artifact in self.artifacts)
Determines if the check uses the specified artifact. Args: artifacts: Either a single artifact name, or a list of artifact names Returns: True if the check uses a specific artifact.
def execute_return_result(cmd): ret = _run_all(cmd) if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower(): msg = 'Command Failed: {0}\n'.format(cmd) msg += 'Return Code: {0}\n'.format(ret['retcode']) msg += 'Output: {0}\n'.format(ret['stdout']) msg += 'Error: {0}\n'....
Executes the passed command. Returns the standard out if successful :param str cmd: The command to run :return: The standard out of the command if successful, otherwise returns an error :rtype: str :raises: Error if command fails or is not supported
def indices_from_symbol(self, symbol: str) -> tuple: return tuple((i for i, specie in enumerate(self.species) if specie.symbol == symbol))
Returns a tuple with the sequential indices of the sites that contain an element with the given chemical symbol.
def load_modules(self): if self.INTERFACES_MODULE is None: raise NotImplementedError("A module containing interfaces modules " "should be setup in INTERFACES_MODULE !") else: for module, permission in self.modules.items(): i =...
Should instance interfaces and set them to interface, following `modules`
def rename(self, newpath): "Move folder to a new name, possibly a whole new path" params = {'mvDir':'/%s%s' % (self.jfs.username, newpath)} r = self.jfs.post(self.path, extra_headers={'Content-Type':'application/octet-stream'}, params=params) ...
Move folder to a new name, possibly a whole new path
def evaluate(condition): success = False if len(condition) > 0: try: rule_name, ast_tokens, evaluate_function = Condition.find_rule(condition) if not rule_name == 'undefined': success = evaluate_function(ast_tokens) except Attri...
Evaluate simple condition. >>> Condition.evaluate(' 2 == 2 ') True >>> Condition.evaluate(' not 2 == 2 ') False >>> Condition.evaluate(' not "abc" == "xyz" ') True >>> Condition.evaluate('2 in [2, 4, 6, 8, 10]') True >>> Condition.ev...
def build_absolute_uri(request, relative_url): webroot = getattr(settings, 'WEBROOT', '') if webroot.endswith("/") and relative_url.startswith("/"): webroot = webroot[:-1] return request.build_absolute_uri(webroot + relative_url)
Ensure absolute_uri are relative to WEBROOT.
def form_number(self): k1, o1, m2, s2 = ( np.extract(self.model['constituent'] == c, self.model['amplitude']) for c in [constituent._K1, constituent._O1, constituent._M2, constituent._S2] ) return (k1+o1)/(m2+s2)
Returns the model's form number, a helpful heuristic for classifying tides.
def assume_script(self) -> 'Language': if self._assumed is not None: return self._assumed if self.language and not self.script: try: self._assumed = self.update_dict({'script': DEFAULT_SCRIPTS[self.language]}) except KeyError: self._ass...
Fill in the script if it's missing, and if it can be assumed from the language subtag. This is the opposite of `simplify_script`. >>> Language.make(language='en').assume_script() Language.make(language='en', script='Latn') >>> Language.make(language='yi').assume_script() Langua...
def _element_path_create_new(element_path): element_names = element_path.split('/') start_element = ET.Element(element_names[0]) end_element = _element_append_path(start_element, element_names[1:]) return start_element, end_element
Create an entirely new element path. Return a tuple where the first item is the first element in the path, and the second item is the final element in the path.
def create_module_rst_file(module_name): return_text = 'Module: ' + module_name dash = '=' * len(return_text) return_text += '\n' + dash + '\n\n' return_text += '.. automodule:: ' + module_name + '\n' return_text += ' :members:\n\n' return return_text
Function for creating content in each .rst file for a module. :param module_name: name of the module. :type module_name: str :returns: A content for auto module. :rtype: str
def buffer_read_into(self, buffer, dtype): ctype = self._check_dtype(dtype) cdata, frames = self._check_buffer(buffer, ctype) frames = self._cdata_io('read', cdata, ctype, frames) return frames
Read from the file into a given buffer object. Fills the given `buffer` with frames in the given data format starting at the current read/write position (which can be changed with :meth:`.seek`) until the buffer is full or the end of the file is reached. This advances the read/write po...
def will_print(level=1): if level == 1: return quiet is None or quiet == False else: return ((isinstance(verbosity, int) and level <= verbosity) or (isinstance(verbosity, bool) and verbosity == True))
Returns True if the current global status of messaging would print a message using any of the printing functions in this module.
def role_create(name, profile=None, **connection_args): kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=pro...
Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin
def cudaGetDevice(): dev = ctypes.c_int() status = _libcudart.cudaGetDevice(ctypes.byref(dev)) cudaCheckStatus(status) return dev.value
Get current CUDA device. Return the identifying number of the device currently used to process CUDA operations. Returns ------- dev : int Device number.
def psnr(data1, data2, method='starck', max_pix=255): r if method == 'starck': return (20 * np.log10((data1.shape[0] * np.abs(np.max(data1) - np.min(data1))) / np.linalg.norm(data1 - data2))) elif method == 'wiki': return (20 * np.log10(max_pix) - 10 * np.log1...
r"""Peak Signal-to-Noise Ratio This method calculates the Peak Signal-to-Noise Ratio between an two data sets Parameters ---------- data1 : np.ndarray First data set data2 : np.ndarray Second data set method : str {'starck', 'wiki'}, optional PSNR implementation, de...
def get_display_label(choices, status): for (value, label) in choices: if value == (status or '').lower(): display_label = label break else: display_label = status return display_label
Get a display label for resource status. This method is used in places where a resource's status or admin state labels need to assigned before they are sent to the view template.
def _start_auth_proc(self): log.debug('Computing the signing key hex') verify_key = self.__signing_key.verify_key sgn_verify_hex = verify_key.encode(encoder=nacl.encoding.HexEncoder) log.debug('Starting the authenticator subprocess') auth = NapalmLogsAuthProc(self.certificate, ...
Start the authenticator process.
def get_tree(root=None): from insights import run return run(MultipathConfTree, root=root).get(MultipathConfTree)
This is a helper function to get a multipath configuration component for your local machine or an archive. It's for use in interactive sessions.
def get_notebook_app_versions(): notebook_apps = dxpy.find_apps(name=NOTEBOOK_APP, all_versions=True) versions = [str(dxpy.describe(app['id'])['version']) for app in notebook_apps] return versions
Get the valid version numbers of the notebook app.
def _on_axes_updated(self): self.attrs["axes"] = [a.identity.encode() for a in self._axes] while len(self._current_axis_identities_in_natural_namespace) > 0: key = self._current_axis_identities_in_natural_namespace.pop(0) try: delattr(self, key) except...
Method to run when axes are changed in any way. Propagates updated axes properly.
def branch_order(h,section, path=[]): path.append(section) sref = h.SectionRef(sec=section) if sref.has_parent() < 0.9: return 0 else: nchild = len(list(h.SectionRef(sec=sref.parent).child)) if nchild <= 1.1: return branch_order(h,sref.parent,path) else: ...
Returns the branch order of a section
def play_Note(self, note): velocity = 64 channel = 1 if hasattr(note, 'dynamics'): if 'velocity' in note.dynamics: velocity = note.dynamics['velocity'] if 'channel' in note.dynamics: channel = note.dynamics['channel'] if hasattr(not...
Convert a Note object to a midi event and adds it to the track_data. To set the channel on which to play this note, set Note.channel, the same goes for Note.velocity.
def import_module_or_none(module_label): try: return importlib.import_module(module_label) except ImportError: __, __, exc_traceback = sys.exc_info() frames = traceback.extract_tb(exc_traceback) frames = [f for f in frames if f[0] != "<frozen importlib._bootstra...
Imports the module with the given name. Returns None if the module doesn't exist, but it does propagates import errors in deeper modules.
def union(self, *sets): cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet containers = map(list, it.chain([self], sets)) items = it.chain.from_iterable(containers) return cls(items)
Combines all unique items. Each items order is defined by its first appearance. Example: >>> oset = OrderedSet.union(OrderedSet([3, 1, 4, 1, 5]), [1, 3], [2, 0]) >>> print(oset) OrderedSet([3, 1, 4, 5, 2, 0]) >>> oset.union([8, 9]) OrderedSet(...
def collect_data(self, correct_only): self.results = [] def get_value_from_logfile(lines, identifier): return load_tool(self).get_value_from_output(lines, identifier) log_zip_cache = {} try: for xml_result, result_file in self._xml_results: self.re...
Load the actual result values from the XML file and the log files. This may take some time if many log files have to be opened and parsed.
def add_component(self, entity: int, component_instance: Any) -> None: component_type = type(component_instance) if component_type not in self._components: self._components[component_type] = set() self._components[component_type].add(entity) if entity not in self._entities: ...
Add a new Component instance to an Entity. Add a Component instance to an Entiy. If a Component of the same type is already assigned to the Entity, it will be replaced. :param entity: The Entity to associate the Component with. :param component_instance: A Component instance.
def CreateChatWith(self, *Usernames): return Chat(self, chop(self._DoCommand('CHAT CREATE %s' % ', '.join(Usernames)), 2)[1])
Creates a chat with one or more users. :Parameters: Usernames : str One or more Skypenames of the users. :return: A chat object :rtype: `Chat` :see: `Chat.AddMembers`
def get_blink_cookie(self, name): value = self.get_cookie(name) if value != None: self.clear_cookie(name) return escape.url_unescape(value)
Gets a blink cookie value
def com_google_fonts_check_metadata_valid_copyright(font_metadata): import re string = font_metadata.copyright does_match = re.search(r'Copyright [0-9]{4} The .* Project Authors \([^\@]*\)', string) if does_match: yield PASS, "METADATA.pb copyright string is good" else: yiel...
Copyright notices match canonical pattern in METADATA.pb
def from_json(cls, stream, json_data): type_converter = _get_decoder_method(stream.get_data_type()) data = type_converter(json_data.get("data")) return cls( stream_id=stream.get_stream_id(), data_type=stream.get_data_type(), units=stream.get_units(), ...
Create a new DataPoint object from device cloud JSON data :param DataStream stream: The :class:`~DataStream` out of which this data is coming :param dict json_data: Deserialized JSON data from Device Cloud about this device :raises ValueError: if the data is malformed :return: (:class:`...
def format_query_result(self, query_result, query_path, return_type=list, preceding_depth=None): if type(query_result) != return_type: converted_result = self.format_with_handler(query_result, return_type) else: converted_result = query_result converted_result = self.add_...
Formats the query result based on the return type requested. :param query_result: (dict or str or list), yaml query result :param query_path: (str, list(str)), representing query path :param return_type: type, return type of object user desires :param preceding_depth: int, the depth to ...
def get(cls, bucket, key, upload_id, with_completed=False): q = cls.query.filter_by( upload_id=upload_id, bucket_id=as_bucket_id(bucket), key=key, ) if not with_completed: q = q.filter(cls.completed.is_(False)) return q.one_or_none()
Fetch a specific multipart object.
def get_file(type_str, open_files, basedir): if type_str not in open_files: filename = type_str+".html" encoding = 'utf-8' fd = codecs.open(os.path.join(basedir, filename), 'w', encoding) open_files[type_str] = fd write_html_header(fd, type_str, encoding) return open_file...
Get already opened file, or open and initialize a new one.
def createZone(self, zone, zoneFile=None, callback=None, errback=None, **kwargs): import ns1.zones zone = ns1.zones.Zone(self.config, zone) return zone.create(zoneFile=zoneFile, callback=callback, errback=errback, **kwargs)
Create a new zone, and return an associated high level Zone object. Several optional keyword arguments are available to configure the SOA record. If zoneFile is specified, upload the specific zone definition file to populate the zone with. :param str zone: zone name, like 'exam...
def internal_assert(condition, message=None, item=None, extra=None): if DEVELOP and callable(condition): condition = condition() if not condition: if message is None: message = "assertion failed" if item is None: item = condition raise CoconutInter...
Raise InternalException if condition is False. If condition is a function, execute it on DEVELOP only.
def _cache_get(self, date): if date in self.cache_data: logger.debug('Using class-cached data for date %s', date.strftime('%Y-%m-%d')) return self.cache_data[date] logger.debug('Getting data from cache for date %s', date.strftime('%Y-...
Return cache data for the specified day; cache locally in this class. :param date: date to get data for :type date: datetime.datetime :return: cache data for date :rtype: dict
def _zmq_socket_context(context, socket_type, bind_endpoints): socket = context.socket(socket_type) try: for endpoint in bind_endpoints: try: socket.bind(endpoint) except Exception: _logger.fatal("Could not bind to '%s'.", endpoint) ...
A ZeroMQ socket context that both constructs a socket and closes it.
def insert_local_var(self, vname, vtype, position): "Inserts a new local variable" index = self.insert_id(vname, SharedData.KINDS.LOCAL_VAR, [SharedData.KINDS.LOCAL_VAR, SharedData.KINDS.PARAMETER], vtype) self.table[index].attribute = position
Inserts a new local variable
def init_log_file(self): self.old_stdout = sys.stdout sys.stdout = open(os.path.join(self.WD, "demag_gui.log"), 'w+')
redirects stdout to a log file to prevent printing to a hanging terminal when dealing with the compiled binary.
def fromXMLname(string): retval = sub(r'_xFFFF_','', string ) def fun( matchobj ): return _fromUnicodeHex( matchobj.group(0) ) retval = sub(r'_x[0-9A-Za-z]+_', fun, retval ) return retval
Convert XML name to unicode string.
def size(self): "The canonical serialized size of this branch." if getattr(self, '_size', None) is None: self._size = getattr(self.node, 'size', 0) return self._size
The canonical serialized size of this branch.
def ensure_hbounds(self): self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)
Ensure the cursor is within horizontal screen bounds.
def csv_dict(d): if len(d) == 0: return "{}" return "{" + ', '.join(["'{}': {}".format(k, quotable(v)) for k, v in d.items()]) + "}"
Format dict to a string with comma-separated values.
def _add_identities_xml(self, document): for fingerprint in self.identities: identity_element = document.createElement( 'allow-access-from-identity' ) signatory_element = document.createElement( 'signatory' ) certificate...
Generates the XML elements for allowed digital signatures.
def construct_scratch_path(self, dirname, basename): return os.path.join(self.scratchdir, dirname, basename)
Construct and return a path in the scratch area. This will be <self.scratchdir>/<dirname>/<basename>
def load_plug_in(self, name): if not isinstance(name, basestring): raise TypeError("name can only be an instance of type basestring") plug_in_name = self._call("loadPlugIn", in_p=[name]) return plug_in_name
Loads a DBGF plug-in. in name of type str The plug-in name or DLL. Special name 'all' loads all installed plug-ins. return plug_in_name of type str The name of the loaded plug-in.
def delete_intel_notifications(self, ids, timeout=None): if not isinstance(ids, list): raise TypeError("ids must be a list") data = json.dumps(ids) try: response = requests.post( self.base + 'hunting/delete-notifications/programmatic/?key=' + self.api_key,...
Programmatically delete notifications via the Intel API. :param ids: A list of IDs to delete from the notification feed. :returns: The post response.
def copy_keys(source, destination, keys=None): if keys is None: keys = destination.keys() for k in set(source) & set(keys): destination[k] = source[k] return destination
Add keys in source to destination Parameters ---------- source : dict destination: dict keys : None | iterable The keys in source to be copied into destination. If None, then `keys = destination.keys()`
def asDict(self): ret = {} for field in BackgroundTaskInfo.FIELDS: ret[field] = getattr(self, field) return ret
asDict - Returns a copy of the current state as a dictionary. This copy will not be updated automatically. @return <dict> - Dictionary with all fields in BackgroundTaskInfo.FIELDS
def set_timestamp(self, data): if 'hittime' in data: data['qt'] = self.hittime(timestamp=data.pop('hittime', None)) if 'hitage' in data: data['qt'] = self.hittime(age=data.pop('hitage', None))
Interpret time-related options, apply queue-time parameter as needed
def unique_list(seq: Iterable[Any]) -> List[Any]: seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
Returns a list of all the unique elements in the input list. Args: seq: input list Returns: list of unique elements As per http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-whilst-preserving-order
def _GetSqliteSchema(self, proto_struct_class, prefix=""): schema = collections.OrderedDict() for type_info in proto_struct_class.type_infos: if type_info.__class__ is rdf_structs.ProtoEmbedded: schema.update( self._GetSqliteSchema( type_info.type, prefix="%s%s." % (pre...
Returns a mapping of SQLite column names to Converter objects.
def highlightBlock(self, text): cb = self.currentBlock() p = cb.position() text = str(self.document().toPlainText()) + '\n' highlight(text, self.lexer, self.formatter) for i in range(len(str(text))): try: self.setFormat(i, 1, self.formatter.data[p + i]...
Takes a block, applies format to the document. according to what's in it.
def getStorageLevel(self): java_storage_level = self._jrdd.getStorageLevel() storage_level = StorageLevel(java_storage_level.useDisk(), java_storage_level.useMemory(), java_storage_level.useOffHeap(), ...
Get the RDD's current storage level. >>> rdd1 = sc.parallelize([1,2]) >>> rdd1.getStorageLevel() StorageLevel(False, False, False, False, 1) >>> print(rdd1.getStorageLevel()) Serialized 1x Replicated
def write(self, file_or_filename): if isinstance(file_or_filename, basestring): self._fcn_name, _ = splitext(basename(file_or_filename)) else: self._fcn_name = self.case.name self._fcn_name = self._fcn_name.replace(",", "").replace(" ", "_") super(MATPOWERWriter, ...
Writes case data to file in MATPOWER format.
def _cleanup(self): for filename in os.listdir(self._storage_dir): file_path = path.join(self._storage_dir, filename) file_stat = os.stat(file_path) evaluate = max(file_stat.st_ctime, file_stat.st_mtime) if evaluate + self._duration < time.time(): ...
Remove any stale files from the session storage directory
def import_related_module(package, pkg_path, related_name, ignore_exceptions=False): try: imp.find_module(related_name, pkg_path) except ImportError: return try: return getattr( __import__('%s' % (package), globals(), locals(), [related_name]), ...
Import module from given path.
def _on_open(self, _): nick = self._format_nick(self._nick, self._pwd) data = {"cmd": "join", "channel": self._channel, "nick": nick} self._send_packet(data) self._thread = True threading.Thread(target=self._ping).start()
Joins the hack.chat channel and starts pinging.
def drain_events(self, allowed_methods=None, timeout=None): return self.wait_multi(self.channels.values(), timeout=timeout)
Wait for an event on any channel.
def save_code(self, authorization_code): self.write(authorization_code.code, {"client_id": authorization_code.client_id, "code": authorization_code.code, "expires_at": authorization_code.expires_at, "redirect_uri": authorization_code...
Stores the data belonging to an authorization code token in redis. See :class:`oauth2.store.AuthCodeStore`.
def get_objects_dex(self): for digest, d in self.analyzed_dex.items(): yield digest, d, self.analyzed_vms[digest]
Yields all dex objects inclduing their Analysis objects :returns: tuple of (sha256, DalvikVMFormat, Analysis)
def set_params(self, subs=None, numticks=None): if numticks is not None: self.numticks = numticks if subs is not None: self._subs = subs
Set parameters within this locator. Parameters ---------- subs : array, optional Subtick values, as multiples of the main ticks. numticks : array, optional Number of ticks.
def find_one(self, filter=None): if self.table is None: self.build_table() allcond = self.parse_query(filter) return self.table.get(allcond)
Finds one matching query element :param query: dictionary representing the mongo query :return: the resulting document (if found)
def get_field_type(cls, name): python_type = cls._get_field_python_type(cls.model, name) if python_type in _COLUMN_FIELD_MAP: field_class = _COLUMN_FIELD_MAP[python_type] return field_class(name) return BaseField(name)
Takes a field name and gets an appropriate BaseField instance for that column. It inspects the Model that is set on the manager to determine what the BaseField subclass should be. :param unicode name: :return: A BaseField subclass that is appropriate for translating a strin...
def get_instance(self, payload): return VoipInstance( self._version, payload, account_sid=self._solution['account_sid'], country_code=self._solution['country_code'], )
Build an instance of VoipInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.available_phone_number.voip.VoipInstance :rtype: twilio.rest.api.v2010.account.available_phone_number.voip.VoipInstance
def getWorker(self, name): if not name in self.worker_list: self.logger.error("Worker {0} is not registered!".format(name)) raise Exception("Worker {0} is not registered!".format(name)) return self.worker_list[name]
Retrieve the Worker registered under the given name. If the given name does not exists in the Worker list, an Exception is raised. Parameters ---------- name: string Name of the Worker to retrieve
def is_expired(self): if self.window is not None: return (self._time() - self.start_time) >= self.window return False
Returns true if the time is beyond the window
def send(self, *args, **kwargs): return self.send_with_options(args=args, kwargs=kwargs)
Asynchronously send a message to this actor. Parameters: *args(tuple): Positional arguments to send to the actor. **kwargs(dict): Keyword arguments to send to the actor. Returns: Message: The enqueued message.
def rfcformat(dt, localtime=False): if not localtime: return formatdate(timegm(dt.utctimetuple())) else: return local_rfcformat(dt)
Return the RFC822-formatted representation of a datetime object. :param datetime dt: The datetime. :param bool localtime: If ``True``, return the date relative to the local timezone instead of UTC, displaying the proper offset, e.g. "Sun, 10 Nov 2013 08:23:45 -0600"
def set_country(self, country): country = _convert_to_charp(country) self._set_country_func(self.alpr_pointer, country)
This sets the country for detecting license plates. For example, setting country to "us" for United States or "eu" for Europe. :param country: A unicode/ascii string (Python 2/3) or bytes array (Python 3) :return: None
def _get_version(): version_string = __salt__['cmd.run']( [_check_pkgin(), '-v'], output_loglevel='trace') if version_string is None: return False version_match = VERSION_MATCH.search(version_string) if not version_match: return False return version_match.group(1).spl...
Get the pkgin version
def _ParseLogline(self, parser_mediator, structure): month, day_of_month, year, hours, minutes, seconds, milliseconds = ( structure.date_time) time_elements_tuple = ( year, month, day_of_month, hours, minutes, seconds, milliseconds) try: date_time = dfdatetime_time_elements.TimeElement...
Parse a logline and store appropriate attributes. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. structure (pyparsing.ParseResults): structure of tokens derived from a line of a text file.
def compile_tag_re(self, tags): return re.compile(self.raw_tag_re % tags, self.re_flags)
Return the regex used to look for Mustache tags compiled to work with specific opening tags, close tags, and tag types.