Search is not available for this dataset
text
stringlengths
75
104k
def get_logs(self, login=None, **kwargs): """Get a user's logs. :param str login: User's login (Default: self._login) :return: JSON """ _login = kwargs.get( 'login', login ) log_events_url = GSA_LOGS_URL.format(login=_login) retur...
def negotiate(cls, headers): """ Process headers dict to return the format class (not the instance) """ # set lower keys headers = {k.lower(): v for k, v in headers.items()} accept = headers.get('accept', "*/*") parsed_accept = accept.split(";") pars...
def register(self, collector): """ Registers a collector""" if not isinstance(collector, Collector): raise TypeError( "Can't register instance, not a valid type of collector") if collector.name in self.collectors: raise ValueError("Collector already exist...
def add(self, registry): """ Add works like replace, but only previously pushed metrics with the same name (and the same job and instance) will be replaced. (It uses HTTP method 'POST' to push to the Pushgateway.) """ # POST payload = self.formatter.marshall(regis...
def replace(self, registry): """ Push triggers a metric collection and pushes all collected metrics to the Pushgateway specified by addr Note that all previously pushed metrics with the same job and instance will be replaced with the metrics pushed by this call. (...
def marshall_lines(self, collector): """ Marshalls a collector and returns the storage/transfer format in a tuple, this tuple has reprensentation format per element. """ if isinstance(collector, collectors.Counter): exec_method = self._format_counter elif isinsta...
def marshall(self, registry): """Marshalls a full registry (various collectors)""" blocks = [] for i in registry.get_all(): blocks.append(self.marshall_collector(i)) # Sort? used in tests blocks = sorted(blocks) # Needs EOF blocks.append("") ...
def marshall(self, registry): """Returns bytes""" result = b"" for i in registry.get_all(): # Each message needs to be prefixed with a varint with the size of # the message (MetrycType) # https://github.com/matttproud/golang_protobuf_extensions/blob/master/ex...
def gather_data(registry): """Gathers the metrics""" # Get the host name of the machine host = socket.gethostname() # Create our collectors trig_metric = Gauge("trigonometry_example", "Various trigonometry examples.", {'host': host}) # register ...
def set_value(self, labels, value): """ Sets a value in the container""" if labels: self._label_names_correct(labels) with mutex: self.values[labels] = value
def _label_names_correct(self, labels): """Raise exception (ValueError) if labels not correct""" for k, v in labels.items(): # Check reserved labels if k in RESTRICTED_LABELS_NAMES: raise ValueError("Labels not correct") # Check prefixes ...
def get_all(self): """ Returns a list populated by tuples of 2 elements, first one is a dict with all the labels and the second elemnt is the value of the metric itself """ with mutex: items = self.values.items() result = [] for k, v in items:...
def add(self, labels, value): """ Add adds the given value to the Gauge. (The value can be negative, resulting in a decrease of the Gauge.) """ try: current = self.get_value(labels) except KeyError: current = 0 self.set_value(labels, current ...
def add(self, labels, value): """Add adds a single observation to the summary.""" if type(value) not in (float, int): raise TypeError("Summary only works with digits (int, float)") # We have already a lock for data but not for the estimator with mutex: try: ...
def get(self, labels): """ Get gets the data in the form of 0.5, 0.9 and 0.99 percentiles. Also you get sum and count, all in a dict """ return_data = {} # We have already a lock for data but not for the estimator with mutex: e = self.get_value(labels) ...
def gather_data(registry): """Gathers the metrics""" # Get the host name of the machine host = socket.gethostname() # Create our collectors ram_metric = Gauge("memory_usage_bytes", "Memory usage in bytes.", {'host': host}) cpu_metric = Gauge("cpu_usage_percent", "CPU usa...
def gather_data(registry): """Gathers the metrics""" # Get the host name of the machine host = socket.gethostname() # Create our collectors io_metric = Summary("write_file_io_example", "Writing io file in disk example.", {'host': host}) # regist...
def get_child(self, name, attribs=None): """ Returns the first child that matches the given name and attributes. """ if name == '.': if attribs is None or len(attribs) == 0: return self if attribs == self.attribs: return sel...
def create(self, path, data=None): """ Creates the given node, regardless of whether or not it already exists. Returns the new node. """ node = self.current[-1] path = self._splitpath(path) n_items = len(path) for n, item in enumerate(path): ...
def add(self, path, data=None, replace=False): """ Creates the given node if it does not exist. Returns the (new or existing) node. """ node = self.current[-1] for item in self._splitpath(path): tag, attribs = self._splittag(item) next_node = node....
def add_attribute(self, path, name, value): """ Creates the given attribute and sets it to the given value. Returns the (new or existing) node to which the attribute was added. """ node = self.add(path) node.attribs.append((name, value)) return node
def open(self, path): """ Creates and enters the given node, regardless of whether it already exists. Returns the new node. """ self.current.append(self.create(path)) return self.current[-1]
def enter(self, path): """ Enters the given node. Creates it if it does not exist. Returns the node. """ self.current.append(self.add(path)) return self.current[-1]
def generate(converter, input_file, format='xml', encoding='utf8'): """ Given a converter (as returned by compile()), this function reads the given input file and converts it to the requested output format. Supported output formats are 'xml', 'yaml', 'json', or 'none'. :type converter: compiler.C...
def generate_to_file(converter, input_file, output_file, format='xml', in_encoding='utf8', out_encoding='utf8'): """ Like generate(), but writes the output to the given output file instead. :type c...
def generate_string(converter, input, format='xml'): """ Like generate(), but reads the input from a string instead of from a file. :type converter: compiler.Context :param converter: The compiled converter. :type input: str :param input: The string to convert. :type format: str ...
def generate_string_to_file(converter, input, output_file, format='xml', out_encoding='utf8'): """ Like generate(), but reads the input from a string instead of from a file, and writes the output ...
def is_now(s, dt=None): ''' A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time. @input: s = cron-like string (minute, hour, day of month, month, day of week) dt = datetime to use as reference time, defaults to now @output: boolean of result...
def has_been(s, since, dt=None): ''' A parser to check whether a (cron-like) string has been true during a certain time period. Useful for applications which cannot check every minute or need to catch up during a restart. @input: s = cron-like string (minute, hour, day of month, month, day of we...
def auprc(y_true, y_pred): """Area under the precision-recall curve """ y_true, y_pred = _mask_value_nan(y_true, y_pred) return skm.average_precision_score(y_true, y_pred)
def best_trial_tid(self, rank=0): """Get tid of the best trial rank=0 means the best model rank=1 means second best ... """ candidates = [t for t in self.trials if t['result']['status'] == STATUS_OK] if len(candidates) == 0: retu...
def count_by_state_unsynced(self, arg): """Extends the original object in order to inject checking for stalled jobs and killing them if they are running for too long """ if self.kill_timeout is not None: self.delete_running(self.kill_timeout) return super(KMongoTrials...
def plot_history(self, tid, scores=["loss", "f1", "accuracy"], figsize=(15, 3)): """Plot the loss curves""" history = self.train_history(tid) import matplotlib.pyplot as plt fig = plt.figure(figsize=figsize) for i, score in enumerate(scores): plt...
def load_model(self, tid, custom_objects=None): """Load saved keras model of the trial. If tid = None, get the best model Not applicable for trials ran in cross validion (i.e. not applicable for `CompileFN.cv_n_folds is None` """ if tid is None: tid = self.b...
def n_ok(self): """Number of ok trials() """ if len(self.trials) == 0: return 0 else: return np.sum(np.array(self.statuses()) == "ok")
def get_ok_results(self, verbose=True): """Return a list of results with ok status """ if len(self.trials) == 0: return [] not_ok = np.where(np.array(self.statuses()) != "ok")[0] if len(not_ok) > 0 and verbose: print("{0}/{1} trials were not ok.".format(...
def VerifierMiddleware(verifier): """Common wrapper for the authentication modules. * Parses the request before passing it on to the authentication module. * Sets 'pyoidc' cookie if authentication succeeds. * Redirects the user to complete the authentication. * Allows the user to ret...
def pyoidcMiddleware(func): """Common wrapper for the underlying pyoidc library functions. Reads GET params and POST data before passing it on the library and converts the response from oic.utils.http_util to wsgi. :param func: underlying library function """ def wrapper(environ, start_response...
def resp2flask(resp): """Convert an oic.utils.http_util instance to Flask.""" if isinstance(resp, Redirect) or isinstance(resp, SeeOther): code = int(resp.status.split()[0]) raise cherrypy.HTTPRedirect(resp.message, code) return resp.message, resp.status, resp.headers
def setup_authentication_methods(authn_config, template_env): """Add all authentication methods specified in the configuration.""" routing = {} ac = AuthnBroker() for authn_method in authn_config: cls = make_cls_from_name(authn_method["class"]) instance = cls(template_env=template_env, *...
def setup_endpoints(provider): """Setup the OpenID Connect Provider endpoints.""" app_routing = {} endpoints = [ AuthorizationEndpoint( pyoidcMiddleware(provider.authorization_endpoint)), TokenEndpoint( pyoidcMiddleware(provider.token_endpoint)), UserinfoEndpo...
def _webfinger(provider, request, **kwargs): """Handle webfinger requests.""" params = urlparse.parse_qs(request) if params["rel"][0] == OIC_ISSUER: wf = WebFinger() return Response(wf.response(params["resource"][0], provider.baseurl), headers=[("Content-Type", "appli...
def featuresQuery(self, **kwargs): """ Converts a dictionary of keyword arguments into a tuple of SQL select statements and the list of SQL arguments """ # TODO: Optimize by refactoring out string concatenation sql = "" sql_rows = "SELECT * FROM FEATURE WHERE id >...
def searchFeaturesInDb( self, startIndex=0, maxResults=None, referenceName=None, start=None, end=None, parentId=None, featureTypes=None, name=None, geneSymbol=None): """ Perform a full features query in database. :param startIndex: int representin...
def getFeatureById(self, featureId): """ Fetch feature by featureID. :param featureId: the FeatureID as found in GFF3 records :return: dictionary representing a feature object, or None if no match is found. """ sql = "SELECT * FROM FEATURE WHERE id = ?" ...
def toProtocolElement(self): """ Returns the representation of this FeatureSet as the corresponding ProtocolElement. """ gaFeatureSet = protocol.FeatureSet() gaFeatureSet.id = self.getId() gaFeatureSet.dataset_id = self.getParentContainer().getId() gaFeatu...
def getCompoundIdForFeatureId(self, featureId): """ Returns server-style compound ID for an internal featureId. :param long featureId: id of feature in database :return: string representing ID for the specified GA4GH protocol Feature object in this FeatureSet. """ ...
def getFeature(self, compoundId): """ Fetches a simulated feature by ID. :param compoundId: any non-null string :return: A simulated feature with id set to the same value as the passed-in compoundId. ":raises: exceptions.ObjectWithIdNotFoundException if None is passe...
def getFeatures(self, referenceName=None, start=None, end=None, startIndex=None, maxResults=None, featureTypes=None, parentId=None, name=None, geneSymbol=None, numFeatures=10): """ Returns a set number of simulated features. :param ref...
def populateFromFile(self, dataUrl): """ Populates the instance variables of this FeatureSet from the specified data URL. """ self._dbFilePath = dataUrl self._db = Gff3DbBackend(self._dbFilePath)
def populateFromRow(self, featureSetRecord): """ Populates the instance variables of this FeatureSet from the specified DB row. """ self._dbFilePath = featureSetRecord.dataurl self.setAttributesJson(featureSetRecord.attributes) self._db = Gff3DbBackend(self._dbFil...
def getFeature(self, compoundId): """ Returns a protocol.Feature object corresponding to a compoundId :param compoundId: a datamodel.FeatureCompoundId object :return: a Feature object. :raises: exceptions.ObjectWithIdNotFoundException if invalid compoundId is provided...
def _gaFeatureForFeatureDbRecord(self, feature): """ :param feature: The DB Row representing a feature :return: the corresponding GA4GH protocol.Feature object """ gaFeature = protocol.Feature() gaFeature.id = self.getCompoundIdForFeatureId(feature['id']) if featu...
def getFeatures(self, referenceName=None, start=None, end=None, startIndex=None, maxResults=None, featureTypes=None, parentId=None, name=None, geneSymbol=None): """ method passed to runSearchRequest to fulfill the request :param str ref...
def addRnaQuantification(self, rnaQuantification): """ Add an rnaQuantification to this rnaQuantificationSet """ id_ = rnaQuantification.getId() self._rnaQuantificationIdMap[id_] = rnaQuantification self._rnaQuantificationIds.append(id_)
def toProtocolElement(self): """ Converts this rnaQuant into its GA4GH protocol equivalent. """ protocolElement = protocol.RnaQuantificationSet() protocolElement.id = self.getId() protocolElement.dataset_id = self._parentContainer.getId() protocolElement.name = se...
def populateFromFile(self, dataUrl): """ Populates the instance variables of this RnaQuantificationSet from the specified data URL. """ self._dbFilePath = dataUrl self._db = SqliteRnaBackend(self._dbFilePath) self.addRnaQuants()
def populateFromRow(self, quantificationSetRecord): """ Populates the instance variables of this RnaQuantificationSet from the specified DB row. """ self._dbFilePath = quantificationSetRecord.dataurl self.setAttributesJson(quantificationSetRecord.attributes) self....
def toProtocolElement(self): """ Converts this rnaQuant into its GA4GH protocol equivalent. """ protocolElement = protocol.RnaQuantification() protocolElement.id = self.getId() protocolElement.name = self._name protocolElement.description = self._description ...
def addRnaQuantMetadata(self, fields): """ data elements are: Id, annotations, description, name, readGroupId where annotations is a comma separated list """ self._featureSetIds = fields["feature_set_ids"].split(',') self._description = fields["description"] ...
def getRnaQuantMetadata(self): """ input is tab file with no header. Columns are: Id, annotations, description, name, readGroupId where annotation is a comma separated list """ rnaQuantId = self.getLocalId() with self._db as dataSource: rnaQuantReturn...
def populateFromFile(self, dataUrl): """ Populates the instance variables of this FeatureSet from the specified data URL. """ self._dbFilePath = dataUrl self._db = SqliteRnaBackend(self._dbFilePath) self.getRnaQuantMetadata()
def populateFromRow(self, row): """ Populates the instance variables of this FeatureSet from the specified DB row. """ self._dbFilePath = row[b'dataUrl'] self._db = SqliteRnaBackend(self._dbFilePath) self.getRnaQuantMetadata()
def getExpressionLevels( self, threshold=0.0, names=[], startIndex=0, maxResults=0): """ Returns the list of ExpressionLevels in this RNA Quantification. """ rnaQuantificationId = self.getLocalId() with self._db as dataSource: expressionsReturned = dataSou...
def searchRnaQuantificationsInDb( self, rnaQuantificationId=""): """ :param rnaQuantificationId: string restrict search by id :return an array of dictionaries, representing the returned data. """ sql = ("SELECT * FROM RnaQuantification") sql_args = () ...
def getRnaQuantificationById(self, rnaQuantificationId): """ :param rnaQuantificationId: the RNA Quantification ID :return: dictionary representing an RnaQuantification object, or None if no match is found. """ sql = ("SELECT * FROM RnaQuantification WHERE id = ?") ...
def searchExpressionLevelsInDb( self, rnaQuantId, names=[], threshold=0.0, startIndex=0, maxResults=0): """ :param rnaQuantId: string restrict search by quantification id :param threshold: float minimum expression values to return :return an array of dictionaries,...
def getExpressionLevelById(self, expressionId): """ :param expressionId: the ExpressionLevel ID :return: dictionary representing an ExpressionLevel object, or None if no match is found. """ sql = ("SELECT * FROM Expression WHERE id = ?") query = self._dbconn.e...
def populateFromRow(self, callSetRecord): """ Populates this CallSet from the specified DB row. """ self._biosampleId = callSetRecord.biosampleid self.setAttributesJson(callSetRecord.attributes)
def toProtocolElement(self): """ Returns the representation of this CallSet as the corresponding ProtocolElement. """ variantSet = self.getParentContainer() gaCallSet = protocol.CallSet( biosample_id=self.getBiosampleId()) if variantSet.getCreationTime...
def addVariantAnnotationSet(self, variantAnnotationSet): """ Adds the specified variantAnnotationSet to this dataset. """ id_ = variantAnnotationSet.getId() self._variantAnnotationSetIdMap[id_] = variantAnnotationSet self._variantAnnotationSetIds.append(id_)
def getVariantAnnotationSet(self, id_): """ Returns the AnnotationSet in this dataset with the specified 'id' """ if id_ not in self._variantAnnotationSetIdMap: raise exceptions.AnnotationSetNotFoundException(id_) return self._variantAnnotationSetIdMap[id_]
def addCallSet(self, callSet): """ Adds the specfied CallSet to this VariantSet. """ callSetId = callSet.getId() self._callSetIdMap[callSetId] = callSet self._callSetNameMap[callSet.getLocalId()] = callSet self._callSetIds.append(callSetId) self._callSetId...
def addCallSetFromName(self, sampleName): """ Adds a CallSet for the specified sample name. """ callSet = CallSet(self, sampleName) self.addCallSet(callSet)
def getCallSetByName(self, name): """ Returns a CallSet with the specified name, or raises a CallSetNameNotFoundException if it does not exist. """ if name not in self._callSetNameMap: raise exceptions.CallSetNameNotFoundException(name) return self._callSetNam...
def getCallSet(self, id_): """ Returns a CallSet with the specified id, or raises a CallSetNotFoundException if it does not exist. """ if id_ not in self._callSetIdMap: raise exceptions.CallSetNotFoundException(id_) return self._callSetIdMap[id_]
def toProtocolElement(self): """ Converts this VariantSet into its GA4GH protocol equivalent. """ protocolElement = protocol.VariantSet() protocolElement.id = self.getId() protocolElement.dataset_id = self.getParentContainer().getId() protocolElement.reference_set...
def _createGaVariant(self): """ Convenience method to set the common fields in a GA Variant object from this variant set. """ ret = protocol.Variant() if self._creationTime: ret.created = self._creationTime if self._updatedTime: ret.updated...
def getVariantId(self, gaVariant): """ Returns an ID string suitable for the specified GA Variant object in this variant set. """ md5 = self.hashVariant(gaVariant) compoundId = datamodel.VariantCompoundId( self.getCompoundId(), gaVariant.reference_name, ...
def getCallSetId(self, sampleName): """ Returns the callSetId for the specified sampleName in this VariantSet. """ compoundId = datamodel.CallSetCompoundId( self.getCompoundId(), sampleName) return str(compoundId)
def hashVariant(cls, gaVariant): """ Produces an MD5 hash of the ga variant object to distinguish it from other variants at the same genomic coordinate. """ hash_str = gaVariant.reference_bases + \ str(tuple(gaVariant.alternate_bases)) return hashlib.md5(hash_...
def generateVariant(self, referenceName, position, randomNumberGenerator): """ Generate a random variant for the specified position using the specified random number generator. This generator should be seeded with a value that is unique to this position so that the same variant w...
def populateFromRow(self, variantSetRecord): """ Populates this VariantSet from the specified DB row. """ self._created = variantSetRecord.created self._updated = variantSetRecord.updated self.setAttributesJson(variantSetRecord.attributes) self._chromFileMap = {} ...
def populateFromFile(self, dataUrls, indexFiles): """ Populates this variant set using the specified lists of data files and indexes. These must be in the same order, such that the jth index file corresponds to the jth data file. """ assert len(dataUrls) == len(indexFiles...
def populateFromDirectory(self, vcfDirectory): """ Populates this VariantSet by examing all the VCF files in the specified directory. This is mainly used for as a convenience for testing purposes. """ pattern = os.path.join(vcfDirectory, "*.vcf.gz") dataFiles = []...
def checkConsistency(self): """ Perform consistency check on the variant set """ for referenceName, (dataUrl, indexFile) in self._chromFileMap.items(): varFile = pysam.VariantFile(dataUrl, index_filename=indexFile) try: for chrom in varFile.index: ...
def _populateFromVariantFile(self, varFile, dataUrl, indexFile): """ Populates the instance variables of this VariantSet from the specified pysam VariantFile object. """ if varFile.index is None: raise exceptions.NotIndexedException(dataUrl) for chrom in varFi...
def _updateVariantAnnotationSets(self, variantFile, dataUrl): """ Updates the variant annotation set associated with this variant using information in the specified pysam variantFile. """ # TODO check the consistency of this between VCF files. if not self.isAnnotated(): ...
def _updateMetadata(self, variantFile): """ Updates the metadata for his variant set based on the specified variant file """ metadata = self._getMetadataFromVcf(variantFile) if self._metadata is None: self._metadata = metadata
def _checkMetadata(self, variantFile): """ Checks that metadata is consistent """ metadata = self._getMetadataFromVcf(variantFile) if self._metadata is not None and self._metadata != metadata: raise exceptions.InconsistentMetaDataException( variantFile...
def _checkCallSetIds(self, variantFile): """ Checks callSetIds for consistency """ if len(self._callSetIdMap) > 0: callSetIds = set([ self.getCallSetId(sample) for sample in variantFile.header.samples]) if callSetIds != set(self._ca...
def _updateCallSetIds(self, variantFile): """ Updates the call set IDs based on the specified variant file. """ if len(self._callSetIdMap) == 0: for sample in variantFile.header.samples: self.addCallSetFromName(sample)
def convertVariant(self, record, callSetIds): """ Converts the specified pysam variant record into a GA4GH Variant object. Only calls for the specified list of callSetIds will be included. """ variant = self._createGaVariant() variant.reference_name = record.conti...
def getPysamVariants(self, referenceName, startPosition, endPosition): """ Returns an iterator over the pysam VCF records corresponding to the specified query. """ if referenceName in self._chromFileMap: varFileName = self._chromFileMap[referenceName] refe...
def getVariants(self, referenceName, startPosition, endPosition, callSetIds=[]): """ Returns an iterator over the specified variants. The parameters correspond to the attributes of a GASearchVariantsRequest object. """ if callSetIds is None: callSe...
def getMetadataId(self, metadata): """ Returns the id of a metadata """ return str(datamodel.VariantSetMetadataCompoundId( self.getCompoundId(), 'metadata:' + metadata.key))
def _createGaVariantAnnotation(self): """ Convenience method to set the common fields in a GA VariantAnnotation object from this variant set. """ ret = protocol.VariantAnnotation() ret.created = self._creationTime ret.variant_annotation_set_id = self.getId() ...
def toProtocolElement(self): """ Converts this VariantAnnotationSet into its GA4GH protocol equivalent. """ protocolElement = protocol.VariantAnnotationSet() protocolElement.id = self.getId() protocolElement.variant_set_id = self._variantSet.getId() protocolElemen...
def hashVariantAnnotation(cls, gaVariant, gaVariantAnnotation): """ Produces an MD5 hash of the gaVariant and gaVariantAnnotation objects """ treffs = [treff.id for treff in gaVariantAnnotation.transcript_effects] return hashlib.md5( "{}\t{}\t{}\t".format( ...
def getVariantAnnotationId(self, gaVariant, gaAnnotation): """ Produces a stringified compoundId representing a variant annotation. :param gaVariant: protocol.Variant :param gaAnnotation: protocol.VariantAnnotation :return: compoundId String """ md5 = s...