code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def createVertex(self, collectionName, docAttributes, waitForSync = False) : url = "%s/vertex/%s" % (self.URL, collectionName) store = DOC.DocumentStore(self.database[collectionName], validators=self.database[collectionName]._fields, initDct=docAttributes) store.validate() r = self.conne...
adds a vertex to the graph and returns it
def file_search(self, query, offset=None, timeout=None): params = dict(apikey=self.api_key, query=query, offset=offset) try: response = requests.get(self.base + 'file/search', params=params, proxies=self.proxies, timeout=timeout) except requests.RequestException as e: ret...
Search for samples. In addition to retrieving all information on a particular file, VirusTotal allows you to perform what we call "advanced reverse searches". Reverse searches take you from a file property to a list of files that match that property. For example, this functionality enables you ...
def getbit(self, key, offset): key = self._encode(key) index, bits, mask = self._get_bits_and_offset(key, offset) if index >= len(bits): return 0 return 1 if (bits[index] & mask) else 0
Returns the bit value at ``offset`` in ``key``.
def _md5(path, blocksize=2 ** 20): m = hashlib.md5() with open(path, 'rb') as f: while True: buf = f.read(blocksize) if not buf: break m.update(buf) return m.hexdigest()
Compute the checksum of a file.
def is_accessable_by_others(filename): mode = os.stat(filename)[stat.ST_MODE] return mode & (stat.S_IRWXG | stat.S_IRWXO)
Check if file is group or world accessable.
def list_service_profiles(self, retrieve_all=True, **_params): return self.list('service_profiles', self.service_profiles_path, retrieve_all, **_params)
Fetches a list of all Neutron service flavor profiles.
def atomic(self, func): @wraps(func) def wrapper(*args, **kwargs): session = self.session session_info = session.info if session_info.get(_ATOMIC_FLAG_SESSION_INFO_KEY): return func(*args, **kwargs) f = retry_on_deadlock(session)(func) ...
A decorator that wraps a function in an atomic block. Example:: db = CustomSQLAlchemy() @db.atomic def f(): write_to_db('a message') return 'OK' assert f() == 'OK' This code defines the function ``f``, which is wrapped in an ...
def days_since_last_snowfall(self, value=99): if value is not None: try: value = int(value) except ValueError: raise ValueError( 'value {} need to be of type int ' 'for field `days_since_last_snowfall`'.format(value)...
Corresponds to IDD Field `days_since_last_snowfall` Args: value (int): value for IDD Field `days_since_last_snowfall` Missing value: 99 if `value` is None it will not be checked against the specification and is assumed to be a missing value R...
def pvalues(self): self.compute_statistics() lml_alts = self.alt_lmls() lml_null = self.null_lml() lrs = -2 * lml_null + 2 * asarray(lml_alts) from scipy.stats import chi2 chi2 = chi2(df=1) return chi2.sf(lrs)
Association p-value for candidate markers.
def _register_service_type(cls, subclass): if hasattr(subclass, '__service_type__'): cls._service_type_mapping[subclass.__service_type__] = subclass if subclass.__service_type__: setattr(subclass, subclass.__service_type__, ...
Registers subclass handlers of various service-type-specific service implementations. Look for classes decorated with @Folder._register_service_type for hints on how this works.
def get_nodes(n=8, exclude=[], loop=None): report = _get_ukko_report() nodes = _parse_ukko_report(report) ret = [] while len(ret) < n and len(nodes) > 0: node = nodes[0] if node not in exclude: reachable = True if loop is not None: reachable = loop...
Get Ukko nodes with the least amount of load. May return less than *n* nodes if there are not as many nodes available, the nodes are reserved or the nodes are on the exclude list. :param int n: Number of Ukko nodes to return. :param list exclude: Nodes to exclude from the returned list. :param loo...
def shape_list(x): x = tf.convert_to_tensor(x) if x.get_shape().dims is None: return tf.shape(x) static = x.get_shape().as_list() shape = tf.shape(x) ret = [] for i, dim in enumerate(static): if dim is None: dim = shape[i] ret.append(dim) return ret
Return list of dims, statically where possible.
def _is_builtin_module(module): if (not hasattr(module, '__file__')) or module.__name__ in sys.builtin_module_names: return True if module.__name__ in _stdlib._STD_LIB_MODULES: return True amp = os.path.abspath(module.__file__) if 'site-packages' in amp: return False if amp....
Is builtin or part of standard library
def _randomized_roundoff_to_bfloat16(x, noise, cand1, cand2): cand1_f = tf.to_float(cand1) cand2_f = tf.to_float(cand2) step_size = cand2_f - cand1_f fpart = (x - cand1_f) / step_size ret = tf.where(tf.greater(fpart, noise), cand2, cand1) return ret
Round-off x to cand1 or to cand2 in an unbiased way. Cand1 and cand2 are the same shape as x. For every element of x, the corresponding elements of cand1 and cand2 should be the two closest bfloat16 values to x. Order does not matter. cand1 and cand2 must differ from each other. Args: x: A float32 Tens...
def eval_str_to_list(input_str: str) -> List[str]: inner_cast = ast.literal_eval(input_str) if isinstance(inner_cast, list): return inner_cast else: raise ValueError
Turn str into str or tuple.
def weighted_mean(X, embedding, neighbors, distances): n_samples = X.shape[0] n_components = embedding.shape[1] partial_embedding = np.zeros((n_samples, n_components)) for i in range(n_samples): partial_embedding[i] = np.average( embedding[neighbors[i]], axis=0, weights=distances[i],...
Initialize points onto an existing embedding by placing them in the weighted mean position of their nearest neighbors on the reference embedding. Parameters ---------- X: np.ndarray embedding: TSNEEmbedding neighbors: np.ndarray distances: np.ndarray Returns ------- np.ndarray
def degrees_of_freedom(self): if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None r = self.studentized_residuals() if r == None: return N = 0.0 for i in range(len(r)): N += len(r[i]) return N-len(self._pnames)
Returns the number of degrees of freedom.
def process_mixcloud(vargs): artist_url = vargs['artist_url'] if 'mixcloud.com' in artist_url: mc_url = artist_url else: mc_url = 'https://mixcloud.com/' + artist_url filenames = scrape_mixcloud_url(mc_url, num_tracks=vargs['num_tracks'], folders=vargs['folders'], custom_path=vargs['path...
Main MixCloud path.
def print_docs(self): docs = {} for name, func in six.iteritems(self.minion.functions): if name not in docs: if func.__doc__: docs[name] = func.__doc__ for name in sorted(docs): if name.startswith(self.opts.get('fun', '')): ...
Pick up the documentation for all of the modules and print it out.
def face_colors(self, values): if values is None: if 'face_colors' in self._data: self._data.data.pop('face_colors') return colors = to_rgba(values) if (self.mesh is not None and colors.shape == (4,)): count = len(self.mesh.face...
Set the colors for each face of a mesh. This will apply these colors and delete any previously specified color information. Parameters ------------ colors: (len(mesh.faces), 3), set each face to the specified color (len(mesh.faces), 4), set each face to the spec...
def wrap_value(self, value): try: return self.item_type.wrap_value(value) except BadValueException: pass try: return self.wrap(value) except BadValueException: pass self._fail_validation(value, 'Could not wrap value as the correct t...
A function used to wrap a value used in a comparison. It will first try to wrap as the sequence's sub-type, and then as the sequence itself
def add_fields(self, fields): if isinstance(fields, string_types): fields = [fields] elif type(fields) is tuple: fields = list(fields) field_objects = [self.add_field(field) for field in fields] return field_objects
Adds all of the passed fields to the table's current field list :param fields: The fields to select from ``table``. This can be a single field, a tuple of fields, or a list of fields. Each field can be a string or ``Field`` instance :type fields: str or tuple or list of str or l...
def broadcast_status(self, status): self._broadcast( "transient.status", json.dumps(status), headers={"expires": str(int((15 + time.time()) * 1000))}, )
Broadcast transient status information to all listeners
def rank(tensor: BKTensor) -> int: if isinstance(tensor, np.ndarray): return len(tensor.shape) return len(tensor[0].size())
Return the number of dimensions of a tensor
def logical_drives(self): return logical_drive.HPELogicalDriveCollection( self._conn, utils.get_subresource_path_by( self, ['Links', 'LogicalDrives']), redfish_version=self.redfish_version)
Gets the resource HPELogicalDriveCollection of ArrayControllers
def prepare_input(self, extracted_str): if self.options['remove_whitespace']: optimized_str = re.sub(' +', '', extracted_str) else: optimized_str = extracted_str if self.options['remove_accents']: optimized_str = unidecode(optimized_str) if self.option...
Input raw string and do transformations, as set in template file.
def _parse_account_information(self, rows): acc_info = {} if not rows: return for row in rows: cols_raw = row.find_all('td') cols = [ele.text.strip() for ele in cols_raw] field, value = cols field = field.replace("\xa0", "_").replace(" ...
Parses the character's account information Parameters ---------- rows: :class:`list` of :class:`bs4.Tag`, optional A list of all rows contained in the table.
def make_module_reload_func(module_name=None, module_prefix='[???]', module=None): module = _get_module(module_name, module, register=False) if module_name is None: module_name = str(module.__name__) def rrr(verbose=True): if not __RELOAD_OK__: raise Exception('Reloading has been...
Injects dynamic module reloading
def _process_loop(self): while not self._web_client_session.done(): self._item_session.request = self._web_client_session.next_request() verdict, reason = self._should_fetch_reason() _logger.debug('Filter verdict {} reason {}', verdict, reason) if not verdict: ...
Fetch URL including redirects. Coroutine.
def set_max_entries(self): if self.cache: self.max_entries = float(max([i[0] for i in self.cache.values()]))
Define the maximum of entries for computing the priority of each items later.
def _advertisement(self): flags = int(self.device.pending_data) | (0 << 1) | (0 << 2) | (1 << 3) | (1 << 4) return struct.pack("<LH", self.device.iotile_id, flags)
Create advertisement data.
def get_attachment_size(self, attachment): fsize = 0 file = attachment.getAttachmentFile() if file: fsize = file.get_size() if fsize < 1024: fsize = '%s b' % fsize else: fsize = '%s Kb' % (fsize / 1024) return fsize
Get the human readable size of the attachment
def _parse_ppt_segment(self, fptr): offset = fptr.tell() - 2 read_buffer = fptr.read(3) length, zppt = struct.unpack('>HB', read_buffer) length = length zppt = zppt numbytes = length - 3 ippt = fptr.read(numbytes) return PPTsegment(zppt, ippt, length, offs...
Parse the PPT segment. The packet headers are not parsed, i.e. they remain "uninterpreted" raw data beffers. Parameters ---------- fptr : file object The file to parse. Returns ------- PPTSegment The current PPT segment.
def branch_inlet_outlet(data, commdct, branchname): objkey = 'Branch'.upper() theobjects = data.dt[objkey] theobject = [obj for obj in theobjects if obj[1] == branchname] theobject = theobject[0] inletindex = 6 outletindex = len(theobject) - 2 return [theobject[inletindex], theobject[outleti...
return the inlet and outlet of a branch
def handle_unset_evidence(self, line: str, position: int, tokens: ParseResults) -> ParseResults: if self.evidence is None: raise MissingAnnotationKeyWarning(self.get_line_number(), line, position, tokens[EVIDENCE]) self.evidence = None return tokens
Unset the evidence, or throws an exception if it is not already set. The value for ``tokens[EVIDENCE]`` corresponds to which alternate of SupportingText or Evidence was used in the BEL script. :raises: MissingAnnotationKeyWarning
def create_dir(entry, section, domain, output): full_output_dir = os.path.join(output, section, domain, entry['assembly_accession']) try: os.makedirs(full_output_dir) except OSError as err: if err.errno == errno.EEXIST and os.path.isdir(full_output_dir): pass else: ...
Create the output directory for the entry if needed.
def delete_topic(self, topic): nsq.assert_valid_topic_name(topic) return self._request('POST', '/topic/delete', fields={'topic': topic})
Delete a topic.
def engine(self): return self.backend({ 'APP_DIRS': True, 'DIRS': [str(ROOT / self.backend.app_dirname)], 'NAME': 'djangoforms', 'OPTIONS': {}, })
Return Render Engine.
def includeme(config): from .models import ( AuthUserMixin, random_uuid, lower_strip, encrypt_password, ) add_proc = config.add_field_processors add_proc( [random_uuid, lower_strip], model=AuthUserMixin, field='username') add_proc([lower_strip], model=...
Set up event subscribers.
def _post_parse_request(self, request, client_id='', **kwargs): request = RefreshAccessTokenRequest(**request.to_dict()) try: keyjar = self.endpoint_context.keyjar except AttributeError: keyjar = "" request.verify(keyjar=keyjar, opponent_id=client_id) if "...
This is where clients come to refresh their access tokens :param request: The request :param authn: Authentication info, comes from HTTP header :returns:
def _get_api_key_ops(): auth_header = request.authorization if not auth_header: logging.debug('API request lacks authorization header') abort(flask.Response( 'API key required', 401, {'WWW-Authenticate': 'Basic realm="API key required"'})) return operations.ApiKeyOps(...
Gets the operations.ApiKeyOps instance for the current request.
def check_ensembl_api_version(self): self.attempt = 0 headers = {"content-type": "application/json"} ext = "/info/rest" r = self.ensembl_request(ext, headers) response = json.loads(r) self.cache.set_ensembl_api_version(response["release"])
check the ensembl api version matches a currently working version This function is included so when the api version changes, we notice the change, and we can manually check the responses for the new version.
def by_youtube_id(cls, youtube_id): qset = cls.objects.filter( encoded_videos__profile__profile_name='youtube', encoded_videos__url=youtube_id ).prefetch_related('encoded_videos', 'courses') return qset
Look up video by youtube id
def update(self, eid, data, token): final_dict = {"data": {"id": eid, "type": "libraryEntries", "attributes": data}} final_headers = self.header final_headers['Authorization'] = "Bearer {}".format(token) r = requests.patch(self.apiurl + "/library-entries/{}".format(eid), json=final_dict,...
Update a given Library Entry. :param eid str: Entry ID :param data dict: Attributes :param token str: OAuth token :return: True or ServerError :rtype: Bool or Exception
def reportFailed(self, *args, **kwargs): return self._makeApiCall(self.funcinfo["reportFailed"], *args, **kwargs)
Report Run Failed Report a run failed, resolving the run as `failed`. Use this to resolve a run that failed because the task specific code behaved unexpectedly. For example the task exited non-zero, or didn't produce expected output. Do not use this if the task couldn't be run because ...
def memory_write32(self, addr, data, zone=None): return self.memory_write(addr, data, zone, 32)
Writes words to memory of a target system. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of words to write zone (str): optional memory zone to access Returns: Number of words written to target. ...
def _get_nn_layers(spec): layers = [] if spec.WhichOneof('Type') == 'pipeline': layers = [] for model_spec in spec.pipeline.models: if not layers: return _get_nn_layers(model_spec) else: layers.extend(_get_nn_layers(model_spec)) elif sp...
Returns a list of neural network layers if the model contains any. Parameters ---------- spec: Model_pb A model protobuf specification. Returns ------- [NN layer] list of all layers (including layers from elements of a pipeline
def _enable_cleanup(func): @functools.wraps(func) def wrapper(*args, **kwargs): self = args[0] result = func(*args, **kwargs) self.cleanup(self) return result return wrapper
Execute cleanup operation when the decorated function completed.
def get_extname(self): name = self._info['extname'] if name.strip() == '': name = self._info['hduname'] return name.strip()
Get the name for this extension, can be an empty string
def download(self, filename, representation, overwrite=False): download(self.input, filename, representation, overwrite, self.resolvers, self.get3d, **self.kwargs)
Download the resolved structure as a file. :param string filename: File path to save to :param string representation: Desired output representation :param bool overwrite: (Optional) Whether to allow overwriting of an existing file
def summarize(self): data = [ ['Sequence ID', self.seqrecord.id], ['G domain', ' '.join(self.gdomain_regions) if self.gdomain_regions else None], ['E-value vs rab db', self.evalue_bh_rabs], ['E-value vs non-rab db', self.evalue_bh_non_rabs], ['RabF mot...
G protein annotation summary in a text format :return: A string summary of the annotation :rtype: str
def guess_strategy_type(file_name_or_ext): if '.' not in file_name_or_ext: ext = file_name_or_ext else: name, ext = os.path.splitext(file_name_or_ext) ext = ext.lstrip('.') file_type_map = get_file_type_map() return file_type_map.get(ext, None)
Guess strategy type to use for file by extension. Args: file_name_or_ext: Either a file name with an extension or just an extension Returns: Strategy: Type corresponding to extension or None if there's no corresponding strategy type
def _register_resources(self, api_dirs, do_checks): msg = 'Looking-up for APIs in the following directories: {}' log.debug(msg.format(api_dirs)) if do_checks: check_and_load(api_dirs) else: msg = 'Loading module "{}" from directory "{}"' for loader, mn...
Register all Apis, Resources and Models with the application.
def is_pod_running(self, pod): is_running = ( pod is not None and pod.status.phase == 'Running' and pod.status.pod_ip is not None and pod.metadata.deletion_timestamp is None and all([cs.ready for cs in pod.status.container_statuses]) ) ...
Check if the given pod is running pod must be a dictionary representing a Pod kubernetes API object.
def get_totals_by_payee(self, account, start_date=None, end_date=None): qs = Transaction.objects.filter(account=account, parent__isnull=True) qs = qs.values('payee').annotate(models.Sum('value_gross')) qs = qs.order_by('payee__name') return qs
Returns transaction totals grouped by Payee.
def defaults(self): (start, end) = get_week_window(timezone.now() - relativedelta(days=7)) return { 'from_date': start, 'to_date': end, 'billable': True, 'non_billable': False, 'paid_leave': False, 'trunc': 'day', 'proje...
Default filter form data when no GET data is provided.
def launch(self): import subprocess try: retcode = subprocess.call(self.fullname, shell=True) if retcode < 0: print("Child was terminated by signal", -retcode, file=sys.stderr) return False else: print("Child returned", ...
launch a file - used for starting html pages
def confirm_execution(self): permit = '' while permit.lower() not in ('yes', 'no'): permit = input('Execute Proposed Plan? [yes/no] ') if permit.lower() == 'yes': return True else: return False
Confirm from your if proposed-plan be executed.
def set_current_time(self, current_time): current_time = c_double(current_time) try: self.library.set_current_time.argtypes = [POINTER(c_double)] self.library.set_current_time.restype = None self.library.set_current_time(byref(current_time)) except AttributeEr...
sets current time of simulation
def _container_whitelist(self): if self.__container_whitelist is None: self.__container_whitelist = \ set(self.CLOUD_BROWSER_CONTAINER_WHITELIST or []) return self.__container_whitelist
Container whitelist.
def describe_security_groups(self, *names): group_names = {} if names: group_names = dict([("GroupName.%d" % (i + 1), name) for i, name in enumerate(names)]) query = self.query_factory( action="DescribeSecurityGroups", creds=self.creds, ...
Describe security groups. @param names: Optionally, a list of security group names to describe. Defaults to all security groups in the account. @return: A C{Deferred} that will fire with a list of L{SecurityGroup}s retrieved from the cloud.
def htmlMarkup(self, realm, return_to=None, immediate=False, form_tag_attrs=None): return oidutil.autoSubmitHTML(self.formMarkup(realm, return_to, immediate, ...
Get an autosubmitting HTML page that submits this request to the IDP. This is just a wrapper for formMarkup. @see: formMarkup @returns: str
def next_line(last_line, next_line_8bit): base_line = last_line - (last_line & 255) line = base_line + next_line_8bit lower_line = line - 256 upper_line = line + 256 if last_line - lower_line <= line - last_line: return lower_line if upper_line - last_line < last_line - line: ret...
Compute the next line based on the last line and a 8bit next line. The behaviour of the function is specified in :ref:`reqline`. :param int last_line: the last line that was processed :param int next_line_8bit: the lower 8 bits of the next line :return: the next line closest to :paramref:`last_line` ...
def backwardeuler(dfun, xzero, timerange, timestep): return zip(*list(BackwardEuler(dfun, xzero, timerange, timestep)))
Backward Euler method integration. This function wraps BackwardEuler. :param dfun: Derivative function of the system. The differential system arranged as a series of first-order equations: \dot{X} = dfun(t, x) :param xzero: The initial condition of the sy...
def addDataFrameColumn(self, columnName, dtype=str, defaultValue=None): if not self.editable or dtype not in SupportedDtypes.allTypes(): return False elements = self.rowCount() columnPosition = self.columnCount() newColumn = pandas.Series([defaultValue]*elements, index=self._...
Adds a column to the dataframe as long as the model's editable property is set to True and the dtype is supported. :param columnName: str name of the column. :param dtype: qtpandas.models.SupportedDtypes option :param defaultValue: (object) to default the...
def send_custom_hsm(self, whatsapp_id, template_name, language, variables): data = { "to": whatsapp_id, "type": "hsm", "hsm": { "namespace": self.hsm_namespace, "element_name": template_name, "language": {"policy": "deterministi...
Sends an HSM with more customizable fields than the send_hsm function
def append(self, filename_in_zip, file_contents): self.in_memory_zip.seek(-1, io.SEEK_END) zf = zipfile.ZipFile(self.in_memory_zip, "a", zipfile.ZIP_DEFLATED, False) zf.writestr(filename_in_zip, file_contents) for zfile in zf.filelist: zfile.create_system = 0 zf.close...
Appends a file with name filename_in_zip and contents of file_contents to the in-memory zip.
def point_consensus(self, consensus_type): if "mean" in consensus_type: consensus_data = np.mean(self.data, axis=0) elif "std" in consensus_type: consensus_data = np.std(self.data, axis=0) elif "median" in consensus_type: consensus_data = np.median(self.data, ...
Calculate grid-point statistics across ensemble members. Args: consensus_type: mean, std, median, max, or percentile_nn Returns: EnsembleConsensus containing point statistic
def get(self, url, headers=None, **kwargs): if headers is None: headers = [] if kwargs: url = url + UrlEncoded('?' + _encode(**kwargs), skip_encode=True) return self.request(url, { 'method': "GET", 'headers': headers })
Sends a GET request to a URL. :param url: The URL. :type url: ``string`` :param headers: A list of pairs specifying the headers for the HTTP response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``). :type headers: ``list`` :param kwargs: Add...
def get_effective_agent_id_with_proxy(proxy): if is_authenticated_with_proxy(proxy): if proxy.has_effective_agent(): return proxy.get_effective_agent_id() else: return proxy.get_authentication().get_agent_id() else: return Id( identifier='MC3GUE$T@MIT....
Given a Proxy, returns the Id of the effective Agent
def _construct_location_to_filter_list(match_query): location_to_filters = {} for match_traversal in match_query.match_traversals: for match_step in match_traversal: current_filter = match_step.where_block if current_filter is not None: current_location = match_st...
Return a dict mapping location -> list of filters applied at that location. Args: match_query: MatchQuery object from which to extract location -> filters dict Returns: dict mapping each location in match_query to a list of Filter objects applied at that location
def arg_strings(parsed_args, name=None): name = name or 'arg_strings' value = getattr(parsed_args, name, []) if isinstance(value, str): return [value] try: return [v for v in value if isinstance(v, str)] except TypeError: return []
A list of all strings for the named arg
def _add_secondary_if_exists(secondary, out, get_retriever): secondary = [_file_local_or_remote(y, get_retriever) for y in secondary] secondary = [z for z in secondary if z] if secondary: out["secondaryFiles"] = [{"class": "File", "path": f} for f in secondary] return out
Add secondary files only if present locally or remotely.
def generate_optimized_y_move_down_x_SOL(y_dist): string = "\x1b[{0}E".format(y_dist) if y_dist < len(string): string = '\n' * y_dist return string
move down y_dist, set x=0
def validate(self, *args): super(self.__class__, self).validate(*args) if not self.name: raise ValidationError('name is required for Data')
Validate contents of class
def run_coral(clus_obj, out_dir, args): if not args.bed: raise ValueError("This module needs the bed file output from cluster subcmd.") workdir = op.abspath(op.join(args.out, 'coral')) safe_dirs(workdir) bam_in = op.abspath(args.bam) bed_in = op.abspath(args.bed) reference = op.abspath(a...
Run some CoRaL modules to predict small RNA function
def fromexportupdate(cls, bundle, export_reg): exc = export_reg.get_exception() if exc: return RemoteServiceAdminEvent( RemoteServiceAdminEvent.EXPORT_ERROR, bundle, export_reg.get_export_container_id(), export_reg.get_remoteser...
Creates a RemoteServiceAdminEvent object from the update of an ExportRegistration
def drop_invalid_columns(feed: "Feed") -> "Feed": feed = feed.copy() for table, group in cs.GTFS_REF.groupby("table"): f = getattr(feed, table) if f is None: continue valid_columns = group["column"].values for col in f.columns: if col not in valid_columns:...
Drop all DataFrame columns of the given "Feed" that are not listed in the GTFS. Return the resulting new "Feed".
def epoch(self): epoch_sec = pytz.utc.localize(datetime.utcfromtimestamp(0)) now_sec = pytz.utc.normalize(self._dt) delta_sec = now_sec - epoch_sec return get_total_second(delta_sec)
Returns the total seconds since epoch associated with the Delorean object. .. testsetup:: from datetime import datetime from delorean import Delorean .. doctest:: >>> d = Delorean(datetime(2015, 1, 1), timezone='US/Pacific') >>> d.epoch ...
def add_interrupt(self, interrupt): self.interrupts.append(interrupt) self.constants[interrupt.name] = interrupt.address
Adds the interrupt to the internal interrupt storage ``self.interrupts`` and registers the interrupt address in the internal constants.
def query_plugins(entry_point_name): entries = {} for entry_point in pkg_resources.iter_entry_points(entry_point_name): entries[entry_point.name] = entry_point.load() return entries
Find everything with a specific entry_point. Results will be returned as a dictionary, with the name as the key and the entry_point itself as the value. Arguments: entry_point_name - the name of the entry_point to populate
def explode(self, hosts, hostgroups, contactgroups): for i in self: self.explode_host_groups_into_hosts(i, hosts, hostgroups) self.explode_contact_groups_into_contacts(i, contactgroups)
Loop over all escalation and explode hostsgroups in host and contactgroups in contacts Call Item.explode_host_groups_into_hosts and Item.explode_contact_groups_into_contacts :param hosts: host list to explode :type hosts: alignak.objects.host.Hosts :param hostgroups: hostgroup ...
def get_mapping(self, meta_fields=True): return {'properties': dict((name, field.json()) for name, field in iteritems(self.fields) if meta_fields or name not in AbstractField.meta_fields)}
Returns the mapping for the index as a dictionary. :param meta_fields: Also include elasticsearch meta fields in the dictionary. :return: a dictionary which can be used to generate the elasticsearch index mapping for this doctype.
def get_include_fields(request): include_fields = [] rif = request.get("include_fields", "") if "include_fields" in request: include_fields = [x.strip() for x in rif.split(",") if x.strip()] if "include_fields[]" in request: include_fie...
Retrieve include_fields values from the request
def _start(self): self._enable_logpersist() logcat_file_path = self._configs.output_file_path if not logcat_file_path: f_name = 'adblog,%s,%s.txt' % (self._ad.model, self._ad._normalized_serial) logcat_file_path = os.path.join(se...
The actual logic of starting logcat.
def discard_queue_messages(self): zmq_stream_queue = self.handler().stream()._send_queue while not zmq_stream_queue.empty(): try: zmq_stream_queue.get(False) except queue.Empty: continue zmq_stream_queue.task_done()
Sometimes it is necessary to drop undelivered messages. These messages may be stored in different caches, for example in a zmq socket queue. With different zmq flags we can tweak zmq sockets and contexts no to keep those messages. But inside ZMQStream class there is a queue that can not be cleaned other way then ...
def cli(env, identifier): nw_mgr = SoftLayer.NetworkManager(env.client) result = nw_mgr.get_nas_credentials(identifier) table = formatting.Table(['username', 'password']) table.add_row([result.get('username', 'None'), result.get('password', 'None')]) env.fout(table)
List NAS account credentials.
def pickle_save(thing,fname=None): if fname is None: fname=os.path.expanduser("~")+"/%d.pkl"%time.time() assert type(fname) is str and os.path.isdir(os.path.dirname(fname)) pickle.dump(thing, open(fname,"wb"),pickle.HIGHEST_PROTOCOL) print("saved",fname)
save something to a pickle file
def set_process(self, process = None): if process is None: self.__process = None else: global Process if Process is None: from winappdbg.process import Process if not isinstance(process, Process): msg = "Parent process must...
Manually set the parent process. Use with care! @type process: L{Process} @param process: (Optional) Process object. Use C{None} for no process.
def camera_position(self, camera_location): if camera_location is None: return if isinstance(camera_location, str): camera_location = camera_location.lower() if camera_location == 'xy': self.view_xy() elif camera_location == 'xz': ...
Set camera position of all active render windows
def header_id_from_text(self, text, prefix, n): header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id...
Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for he...
def write_mesh(fname, vertices, faces, normals, texcoords, name='', format='obj', overwrite=False, reshape_faces=True): if op.isfile(fname) and not overwrite: raise IOError('file "%s" exists, use overwrite=True' % fname) if format not in ('obj'): raise ValueError('Only "obj" forma...
Write mesh data to file. Parameters ---------- fname : str Filename to write. Must end with ".obj" or ".gz". vertices : array Vertices. faces : array | None Triangle face definitions. normals : array Normals for the mesh. texcoords : array | None Text...
def getPositionByName(self, name): try: return self.__nameToPosMap[name] except KeyError: raise error.PyAsn1Error('Name %s not found' % (name,))
Return field position by filed name. Parameters ---------- name: :py:class:`str` Field name Returns ------- : :py:class:`int` Field position in fields set Raises ------ : :class:`~pyasn1.error.PyAsn1Error` If ...
def rotate(self, azimuth, axis=None): target = self._target y_axis = self._n_pose[:3, 1].flatten() if axis is not None: y_axis = axis x_rot_mat = transformations.rotation_matrix(azimuth, y_axis, target) self._n_pose = x_rot_mat.dot(self._n_pose) y_axis = self....
Rotate the trackball about the "Up" axis by azimuth radians. Parameters ---------- azimuth : float The number of radians to rotate.
def edit(directory=None, revision='current'): if alembic_version >= (0, 8, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.edit(config, revision) else: raise RuntimeError('Alembic 0.8.0 or greater is required')
Edit current revision.
def trim_req(req): reqfirst = next(iter(req)) if '.' in reqfirst: return {reqfirst.split('.')[0]: req[reqfirst]} return req
Trim any function off of a requisite
def _get_validated_stages(stages): if not isinstance(stages, list): raise WorkflowBuilderException("Stages must be specified as a list of dictionaries") validated_stages = [] for index, stage in enumerate(stages): validated_stages.append(_get_validated_stage(stage, index)) return validat...
Validates stages of the workflow as a list of dictionaries.
def post_build(self, p, pay): p += pay if self.type in [0, 0x31, 0x32, 0x22]: p = p[:1]+chr(0)+p[2:] if self.chksum is None: ck = checksum(p[:2]+p[4:]) p = p[:2]+ck.to_bytes(2, 'big')+p[4:] return p
Called implicitly before a packet is sent to compute and place IGMPv3 checksum. Parameters: self The instantiation of an IGMPv3 class p The IGMPv3 message in hex in network byte order pay Additional payload for the IGMPv3 message
def draw_variable(loc, scale, shape, skewness, nsims): return loc + scale*Skewt.rvs(shape, skewness, nsims)
Draws random variables from Skew t distribution Parameters ---------- loc : float location parameter for the distribution scale : float scale parameter for the distribution shape : float tail thickness parameter for the distribution ...
def request_eval(self, req, expression): r = str(eval(expression)) self._eval_result.set_value(r) return ("ok", r)
Evaluate a Python expression.