INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Send a delete request to the given path of the CRUD API. This deletes the object. Or at least tries to.
def delete(self, path): """Send a delete request to the given path of the CRUD API. This deletes the object. Or at least tries to.""" return self.handleresult(self.r.delete(urljoin(self.url + CRUD_PATH, path)))
Subscribe to the given stream with the callback
def subscribe(self, stream, callback, transform=""): """Subscribe to the given stream with the callback""" return self.ws.subscribe(stream, callback, transform)
Creates the given user - using the passed in email and password.
def create(self, email, password, role="user", public=True, **kwargs): """Creates the given user - using the passed in email and password. You can also set other default properties by passing in the relevant information:: usr.create("my@email","mypass",description="I like trains.") ...
Returns the list of devices that belong to the user
def devices(self): """Returns the list of devices that belong to the user""" result = self.db.read(self.path, {"q": "ls"}) if result is None or result.json() is None: return [] devices = [] for d in result.json(): dev = self[d["name"]] dev.met...
Returns the list of streams that belong to the user. The list can optionally be filtered in 3 ways: - public: when True returns only streams belonging to public devices - downlink: If True returns only downlink streams - visible: If True ( default ) returns only streams of visible devices
def streams(self, public=False, downlink=False, visible=True): """Returns the list of streams that belong to the user. The list can optionally be filtered in 3 ways: - public: when True, returns only streams belonging to public devices - downlink: If True, returns only downlink s...
Exports the ConnectorDB user into the given directory. The resulting export can be imported by using the import command ( cdb. import ( directory ))
def export(self, directory): """Exports the ConnectorDB user into the given directory. The resulting export can be imported by using the import command(cdb.import(directory)), Note that Python cannot export passwords, since the REST API does not expose password hashes. Therefore, the im...
Imports a device from the given directory. You export the device by using device. export ()
def import_device(self, directory): """Imports a device from the given directory. You export the device by using device.export() There are two special cases: user and meta devices. If the device name is meta, import_device will not do anything. If the device name is "user", impo...
Adapter trimming for RNA - seq data
def run_cutadapt(job, r1_id, r2_id, fwd_3pr_adapter, rev_3pr_adapter): """ Adapter trimming for RNA-seq data :param JobFunctionWrappingJob job: passed automatically by Toil :param str r1_id: FileStoreID of fastq read 1 :param str r2_id: FileStoreID of fastq read 2 (if paired data) :param str fw...
Use SAMtools to create reference index file
def run_samtools_faidx(job, ref_id): """ Use SAMtools to create reference index file :param JobFunctionWrappingJob job: passed automatically by Toil :param str ref_id: FileStoreID for the reference genome :return: FileStoreID for reference index :rtype: str """ job.fileStore.logToMaster...
Runs SAMtools index to create a BAM index file
def run_samtools_index(job, bam): """ Runs SAMtools index to create a BAM index file :param JobFunctionWrappingJob job: passed automatically by Toil :param str bam: FileStoreID of the BAM file :return: FileStoreID for BAM index file :rtype: str """ work_dir = job.fileStore.getLocalTempD...
Marks reads as PCR duplicates using Sambamba
def run_sambamba_markdup(job, bam): """ Marks reads as PCR duplicates using Sambamba :param JobFunctionWrappingJob job: passed automatically by Toil :param str bam: FileStoreID for BAM file :return: FileStoreID for sorted BAM file :rtype: str """ work_dir = job.fileStore.getLocalTempDir...
Marks reads as PCR duplicates using SAMBLASTER
def run_samblaster(job, sam): """ Marks reads as PCR duplicates using SAMBLASTER :param JobFunctionWrappingJob job: passed automatically by Toil :param str sam: FileStoreID for SAM file :return: FileStoreID for deduped SAM file :rtype: str """ work_dir = job.fileStore.getLocalTempDir() ...
Runs Picard MarkDuplicates on a BAM file. Requires that the BAM file be coordinate sorted.
def picard_mark_duplicates(job, bam, bai, validation_stringency='LENIENT'): """ Runs Picard MarkDuplicates on a BAM file. Requires that the BAM file be coordinate sorted. :param JobFunctionWrappingJob job: passed automatically by Toil :param str bam: FileStoreID for BAM file :param str bai: FileSto...
Sorts BAM file using Picard SortSam
def run_picard_sort(job, bam, sort_by_name=False): """ Sorts BAM file using Picard SortSam :param JobFunctionWrappingJob job: passed automatically by Toil :param str bam: FileStoreID for BAM file :param boolean sort_by_name: If true, sorts by read name instead of coordinate. :return: FileStoreI...
GATK Preprocessing Pipeline 0: Mark duplicates 1: Create INDEL realignment intervals 2: Realign INDELs 3: Recalibrate base quality scores 4: Apply base score recalibration
def run_gatk_preprocessing(job, bam, bai, ref, ref_dict, fai, g1k, mills, dbsnp, realign=False, unsafe=False): """ GATK Preprocessing Pipeline 0: Mark duplicates 1: Create INDEL realignment intervals 2: Realign INDELs 3: Recalibrate base quality scores 4: Apply base score recalibration ...
Creates recalibration table for Base Quality Score Recalibration
def run_base_recalibration(job, bam, bai, ref, ref_dict, fai, dbsnp, mills, unsafe=False): """ Creates recalibration table for Base Quality Score Recalibration :param JobFunctionWrappingJob job: passed automatically by Toil :param str bam: FileStoreID for BAM file :param str bai: FileStoreID for BA...
RNA quantification via Kallisto
def run_kallisto(job, r1_id, r2_id, kallisto_index_url): """ RNA quantification via Kallisto :param JobFunctionWrappingJob job: passed automatically by Toil :param str r1_id: FileStoreID of fastq (pair 1) :param str r2_id: FileStoreID of fastq (pair 2 if applicable, otherwise pass None for single-e...
RNA quantification with RSEM
def run_rsem(job, bam_id, rsem_ref_url, paired=True): """ RNA quantification with RSEM :param JobFunctionWrappingJob job: Passed automatically by Toil :param str bam_id: FileStoreID of transcriptome bam for quantification :param str rsem_ref_url: URL of RSEM reference (tarball) :param bool pair...
Parses RSEMs output to produce the separate. tab files ( TPM FPKM counts ) for both gene and isoform. These are two - column files: Genes and Quantifications. HUGO files are also provided that have been mapped from Gencode/ ENSEMBLE names.
def run_rsem_postprocess(job, rsem_gene_id, rsem_isoform_id): """ Parses RSEMs output to produce the separate .tab files (TPM, FPKM, counts) for both gene and isoform. These are two-column files: Genes and Quantifications. HUGO files are also provided that have been mapped from Gencode/ENSEMBLE names. ...
Set/ clear boolean field value for model object
def switch(request, url): """ Set/clear boolean field value for model object """ app_label, model_name, object_id, field = url.split('/') try: # django >= 1.7 from django.apps import apps model = apps.get_model(app_label, model_name) except ImportError: # django <...
Main fit method for SAR. Expects the dataframes to have row_id col_id columns which are indexes i. e. contain the sequential integer index of the original alphanumeric user and item IDs. Dataframe also contains rating and timestamp as floats ; timestamp is in seconds since Epoch by default.
def fit( self, df, similarity_type="jaccard", time_decay_coefficient=30, time_now=None, timedecay_formula=False, threshold=1, ): """Main fit method for SAR. Expects the dataframes to have row_id, col_id columns which are indexes, i.e. contain t...
Prepare test set for C ++ SAR prediction code. Find all items the test users have seen in the past.
def get_user_affinity(self, test): """Prepare test set for C++ SAR prediction code. Find all items the test users have seen in the past. Arguments: test (pySpark.DataFrame): input dataframe which contains test users. """ test.createOrReplaceTempView(self.f("{prefix}d...
Recommend top K items for all users which are in the test set.
def recommend_k_items_slow(self, test, top_k=10, remove_seen=True): """Recommend top K items for all users which are in the test set. Args: test: test Spark dataframe top_k: top n items to return remove_seen: remove items test users have already seen in the past from...
setauth can be used during runtime to make sure that authentication is reset. it can be used when changing passwords/ apikeys to make sure reconnects succeed
def setauth(self,basic_auth): """ setauth can be used during runtime to make sure that authentication is reset. it can be used when changing passwords/apikeys to make sure reconnects succeed """ self.headers = [] # If we have auth if basic_auth is not None: # we use a...
Send the given command thru the websocket
def send(self, cmd): """Send the given command thru the websocket""" with self.ws_sendlock: self.ws.send(json.dumps(cmd))
Given a stream a callback and an optional transform sets up the subscription
def subscribe(self, stream, callback, transform=""): """Given a stream, a callback and an optional transform, sets up the subscription""" if self.status == "disconnected" or self.status == "disconnecting" or self.status == "connecting": self.connect() if self.status is not "connected...
Unsubscribe from the given stream ( with the optional transform )
def unsubscribe(self, stream, transform=""): """Unsubscribe from the given stream (with the optional transform)""" if self.status is not "connected": return False logging.debug("Unsubscribing from %s", stream) self.send( {"cmd": "unsubscribe", "arg": ...
Attempt to connect to the websocket - and returns either True or False depending on if the connection was successful or not
def connect(self): """Attempt to connect to the websocket - and returns either True or False depending on if the connection was successful or not""" # Wait for the lock to be available (ie, the websocket is not being used (yet)) self.ws_openlock.acquire() self.ws_openlock.releas...
This is called when a connection is lost - it attempts to reconnect to the server
def __reconnect(self): """This is called when a connection is lost - it attempts to reconnect to the server""" self.status = "reconnecting" # Reset the disconnect time after 15 minutes if self.disconnected_time - self.connected_time > 15 * 60: self.reconnect_time = self.reco...
Send subscribe command for all existing subscriptions. This allows to resume a connection that was closed
def __resubscribe(self): """Send subscribe command for all existing subscriptions. This allows to resume a connection that was closed""" with self.subscription_lock: for sub in self.subscriptions: logging.debug("Resubscribing to %s", sub) stream_transf...
Called when the websocket is opened
def __on_open(self, ws): """Called when the websocket is opened""" logging.debug("ConnectorDB: Websocket opened") # Connection success - decrease the wait time for next connection self.reconnect_time /= self.reconnect_time_backoff_multiplier self.status = "connected" s...
Called when the websocket is closed
def __on_close(self, ws): """Called when the websocket is closed""" if self.status == "disconnected": return # This can be double-called on disconnect logging.debug("ConnectorDB:WS: Websocket closed") # Turn off the ping timer if self.pingtimer is not None: ...
Called when there is an error in the websocket
def __on_error(self, ws, err): """Called when there is an error in the websocket""" logging.debug("ConnectorDB:WS: Connection Error") if self.status == "connecting": self.status = "errored" self.ws_openlock.release()
This function is called whenever there is a message received from the server
def __on_message(self, ws, msg): """This function is called whenever there is a message received from the server""" msg = json.loads(msg) logging.debug("ConnectorDB:WS: Msg '%s'", msg["stream"]) # Build the subcription key stream_key = msg["stream"] + ":" if "transform" ...
The server periodically sends us websocket ping messages to keep the connection alive. To ensure that the connection to the server is still active we memorize the most recent ping s time and we periodically ensure that a ping was received in __ensure_ping
def __on_ping(self, ws, data): """The server periodically sends us websocket ping messages to keep the connection alive. To ensure that the connection to the server is still active, we memorize the most recent ping's time and we periodically ensure that a ping was received in __ensure_ping""" ...
Each time the server sends a ping message we record the timestamp. If we haven t received a ping within the given interval then we assume that the connection was lost close the websocket and attempt to reconnect
def __ensure_ping(self): """Each time the server sends a ping message, we record the timestamp. If we haven't received a ping within the given interval, then we assume that the connection was lost, close the websocket and attempt to reconnect""" logging.debug("ConnectorDB:WS: pingcheck"...
Isolates a particular variant type from a VCF file using GATK SelectVariants
def gatk_select_variants(job, mode, vcf_id, ref_fasta, ref_fai, ref_dict): """ Isolates a particular variant type from a VCF file using GATK SelectVariants :param JobFunctionWrappingJob job: passed automatically by Toil :param str mode: variant type (i.e. SNP or INDEL) :param str vcf_id: FileStoreI...
Filters VCF file using GATK VariantFiltration. Fixes extra pair of quotation marks in VCF header that may interfere with other VCF tools.
def gatk_variant_filtration(job, vcf_id, filter_name, filter_expression, ref_fasta, ref_fai, ref_dict): """ Filters VCF file using GATK VariantFiltration. Fixes extra pair of quotation marks in VCF header that may interfere with other VCF tools. :param JobFunctionWrappingJob job: passed automatically b...
Runs either SNP or INDEL variant quality score recalibration using GATK VariantRecalibrator. Because the VQSR method models SNPs and INDELs differently VQSR must be run separately for these variant types.
def gatk_variant_recalibrator(job, mode, vcf, ref_fasta, ref_fai, ref_dict, annotations, hapmap=None, omni=None, phase=None, dbsnp=None, mills=None, ...
Applies variant quality score recalibration to VCF file using GATK ApplyRecalibration
def gatk_apply_variant_recalibration(job, mode, vcf, recal_table, tranches, ref_fasta, ref_fai, ref_dict, ts_filter_level=99.0, ...
Merges VCF files using GATK CombineVariants
def gatk_combine_variants(job, vcfs, ref_fasta, ref_fai, ref_dict, merge_option='UNIQUIFY'): """ Merges VCF files using GATK CombineVariants :param JobFunctionWrappingJob job: Toil Job instance :param dict vcfs: Dictionary of VCF FileStoreIDs {sample identifier: FileStoreID} :param str ref_fasta: F...
Perform a quick check on a BAM via samtools quickcheck. This will detect obvious BAM errors such as truncation.
def bam_quickcheck(bam_path): """ Perform a quick check on a BAM via `samtools quickcheck`. This will detect obvious BAM errors such as truncation. :param str bam_path: path to BAM file to checked :rtype: boolean :return: True if the BAM is valid, False is BAM is invalid or something related t...
Given a dictionary mapping which looks like the following import the objects based on the dotted path and yield the packet type and handler as pairs.
def load_handlers(handler_mapping): """ Given a dictionary mapping which looks like the following, import the objects based on the dotted path and yield the packet type and handler as pairs. If the special string '*' is passed, don't process that, pass it on as it is a wildcard. If an non-...
Helper to write the JSON configuration to a file
def write_config(configuration): """Helper to write the JSON configuration to a file""" with open(CONFIG_PATH, 'w') as f: json.dump(configuration, f, indent=2, sort_keys=True)
Gets the configuration for this project from the default JSON file or writes one if it doesn t exist
def get_config(): """Gets the configuration for this project from the default JSON file, or writes one if it doesn't exist :rtype: dict """ if not os.path.exists(CONFIG_PATH): write_config({}) with open(CONFIG_PATH) as f: return json.load(f)
Gets the metadata for a given ontology
def get_ontology(self, ontology): """Gets the metadata for a given ontology :param str ontology: The name of the ontology :return: The dictionary representing the JSON from the OLS :rtype: dict """ url = self.ontology_metadata_fmt.format(ontology=ontology) respon...
Gets the data for a given term
def get_term(self, ontology, iri): """Gets the data for a given term :param str ontology: The name of the ontology :param str iri: The IRI of a term :rtype: dict """ url = self.ontology_term_fmt.format(ontology, iri) response = requests.get(url) return r...
Searches the OLS with the given term
def search(self, name, query_fields=None): """Searches the OLS with the given term :param str name: :param list[str] query_fields: Fields to query :return: dict """ params = {'q': name} if query_fields is not None: params['queryFields'] = '{{{}}}'.for...
Suggest terms from an optional list of ontologies
def suggest(self, name, ontology=None): """Suggest terms from an optional list of ontologies :param str name: :param list[str] ontology: :rtype: dict .. seealso:: https://www.ebi.ac.uk/ols/docs/api#_suggest_term """ params = {'q': name} if ontology: ...
Iterates over all terms lazily with paging
def _iter_terms_helper(url, size=None, sleep=None): """Iterates over all terms, lazily with paging :param str url: The url to query :param int size: The size of each page. Defaults to 500, which is the maximum allowed by the EBI. :param int sleep: The amount of time to sleep between pag...
Iterates over all terms lazily with paging
def iter_terms(self, ontology, size=None, sleep=None): """Iterates over all terms, lazily with paging :param str ontology: The name of the ontology :param int size: The size of each page. Defaults to 500, which is the maximum allowed by the EBI. :param int sleep: The amount of time to s...
Iterates over the descendants of a given term
def iter_descendants(self, ontology, iri, size=None, sleep=None): """Iterates over the descendants of a given term :param str ontology: The name of the ontology :param str iri: The IRI of a term :param int size: The size of each page. Defaults to 500, which is the maximum allowed by the...
Iterates over the labels for the descendants of a given term
def iter_descendants_labels(self, ontology, iri, size=None, sleep=None): """Iterates over the labels for the descendants of a given term :param str ontology: The name of the ontology :param str iri: The IRI of a term :param int size: The size of each page. Defaults to 500, which is the ...
Iterates over the labels of terms in the ontology. Automatically wraps the pager returned by the OLS.
def iter_labels(self, ontology, size=None, sleep=None): """Iterates over the labels of terms in the ontology. Automatically wraps the pager returned by the OLS. :param str ontology: The name of the ontology :param int size: The size of each page. Defaults to 500, which is the maximum allowed by...
Iterates over parent - child relations
def iter_hierarchy(self, ontology, size=None, sleep=None): """Iterates over parent-child relations :param str ontology: The name of the ontology :param int size: The size of each page. Defaults to 500, which is the maximum allowed by the EBI. :param int sleep: The amount of time to slee...
Run Fastqc on the input reads
def run_fastqc(job, r1_id, r2_id): """ Run Fastqc on the input reads :param JobFunctionWrappingJob job: passed automatically by Toil :param str r1_id: FileStoreID of fastq read 1 :param str r2_id: FileStoreID of fastq read 2 :return: FileStoreID of fastQC output (tarball) :rtype: str ""...
Adds the given stream to the query construction. The function supports both stream names and Stream objects.
def addStream(self, stream, t1=None, t2=None, limit=None, i1=None, i2=None, transform=None): """Adds the given stream to the query construction. The function supports both stream names and Stream objects.""" params = query_maker(t1, t2, limit, i1, i2, transform) params["stream"] = ...
This needs some tidying up. To avoid circular imports we import everything here but it makes this method a bit more gross.
def create_app(config=None): """ This needs some tidying up. To avoid circular imports we import everything here but it makes this method a bit more gross. """ # Initialise the app from home.config import TEMPLATE_FOLDER, STATIC_FOLDER app = Flask(__name__, static_folder=STATIC_FOLDER, ...
: param numWorkers: The number of worker nodes to have in the cluster. \ Must be greater than or equal to 1.: param cores: Optional parameter to set the number of cores per node. \ If not provided we use the number of cores on the node that launches \ the service.: param memory: Optional parameter to set the memory req...
def spawn_spark_cluster(job, numWorkers, cores=None, memory=None, disk=None, overrideLeaderIP=None): ''' :param numWorkers: The number of worker nodes to have in the cluster. \ Must be gre...
Start spark and hdfs master containers
def start(self, job): """ Start spark and hdfs master containers :param job: The underlying job. """ if self.hostname is None: self.hostname = subprocess.check_output(["hostname", "-f",])[:-1] _log.info("Started Spark master container.") self.sparkC...
Start spark and hdfs worker containers
def start(self, job): """ Start spark and hdfs worker containers :param job: The underlying job. """ # start spark and our datanode self.sparkContainerID = dockerCheckOutput(job=job, defer=STOP, ...
Launches the Hadoop datanode.
def __start_datanode(self, job): """ Launches the Hadoop datanode. :param job: The underlying job. """ self.hdfsContainerID = dockerCheckOutput(job=job, defer=STOP, workDir=os.getcw...
Stop spark and hdfs worker containers
def stop(self, fileStore): """ Stop spark and hdfs worker containers :param job: The underlying job. """ subprocess.call(["docker", "exec", self.sparkContainerID, "rm", "-r", "/ephemeral/spark"]) subprocess.call(["docker", "stop", self.sparkContainerID]) subproc...
Checks to see if Spark worker and HDFS datanode are still running.
def check(self): """ Checks to see if Spark worker and HDFS datanode are still running. """ status = _checkContainerStatus(self.sparkContainerID, self.hdfsContainerID, sparkNoun='worker', ...
Tokenizer. Generates tokens stream from text
def base_tokenizer(fp): 'Tokenizer. Generates tokens stream from text' if isinstance(fp, StringIO): template_file = fp size = template_file.len else: #empty file check if os.fstat(fp.fileno()).st_size == 0: yield TOKEN_EOF, 'EOF', 0, 0 return t...
This function is wrapper to normal parsers ( tag_parser block_parser etc. ). Returns mint tree.
def get_mint_tree(tokens_stream): ''' This function is wrapper to normal parsers (tag_parser, block_parser, etc.). Returns mint tree. ''' smart_stack = RecursiveStack() block_parser.parse(tokens_stream, smart_stack) return MintTemplate(body=smart_stack.stack)
Look up a zone ID for a zone string.
def lookup_zone(conn, zone): """Look up a zone ID for a zone string. Args: conn: boto.route53.Route53Connection zone: string eg. foursquare.com Returns: zone ID eg. ZE2DYFZDWGSL4. Raises: ZoneNotFoundError if zone not found.""" all_zones = conn.get_all_hosted_zones() for resp in all_zones['ListHost...
Fetch all pieces of a Route 53 config from Amazon.
def fetch_config(zone, conn): """Fetch all pieces of a Route 53 config from Amazon. Args: zone: string, hosted zone id. conn: boto.route53.Route53Connection Returns: list of ElementTrees, one for each piece of config.""" more_to_fetch = True cfg_chunks = [] next_name = None next_type = None nex...
Merge a set of fetched Route 53 config Etrees into a canonical form.
def merge_config(cfg_chunks): """Merge a set of fetched Route 53 config Etrees into a canonical form. Args: cfg_chunks: [ lxml.etree.ETree ] Returns: lxml.etree.Element""" root = lxml.etree.XML('<ResourceRecordSets xmlns="%s"></ResourceRecordSets>' % R53_XMLNS, parser=XML_PARSER) for chunk in cfg_chunks: ...
Lexically sort the order of every ResourceRecord in a ResourceRecords element so we don t generate spurious changes: ordering of e. g. NS records is irrelevant to the DNS line protocol but XML sees it differently.
def normalize_rrs(rrsets): """Lexically sort the order of every ResourceRecord in a ResourceRecords element so we don't generate spurious changes: ordering of e.g. NS records is irrelevant to the DNS line protocol, but XML sees it differently. Also rewrite any wildcard records to use the ascii hex code: somewh...
Diff two XML configs and return an object with changes to be written.
def generate_changeset(old, new, comment=None): """Diff two XML configs and return an object with changes to be written. Args: old, new: lxml.etree.Element (<ResourceRecordSets>). Returns: lxml.etree.ETree (<ChangeResourceRecordSetsRequest>) or None""" rrsets_tag = '{%s}ResourceRecordSets' % R53_XMLNS if rrs...
Validate a changeset is compatible with Amazon s API spec.
def validate_changeset(changeset): """Validate a changeset is compatible with Amazon's API spec. Args: changeset: lxml.etree.Element (<ChangeResourceRecordSetsRequest>) Returns: [ errors ] list of error strings or [].""" errors = [] changes = changeset.findall('.//{%s}Change' % R53_XMLNS) num_changes = len...
Orders population members from lowest fitness to highest fitness
def minimize_best_n(Members): ''' Orders population members from lowest fitness to highest fitness Args: Members (list): list of PyGenetics Member objects Returns: lsit: ordered lsit of Members, from highest fitness to lowest fitness ''' return(list(reversed(sorted( Me...
Population fitness == average member fitness score
def fitness(self): '''Population fitness == average member fitness score''' if len(self.__members) != 0: if self.__num_processes > 1: members = [m.get() for m in self.__members] else: members = self.__members return sum(m.fitness_score...
Returns average cost function return value for all members
def ave_cost_fn_val(self): '''Returns average cost function return value for all members''' if len(self.__members) != 0: if self.__num_processes > 1: members = [m.get() for m in self.__members] else: members = self.__members return sum...
Returns median cost function return value for all members
def med_cost_fn_val(self): '''Returns median cost function return value for all members''' if len(self.__members) != 0: if self.__num_processes > 1: members = [m.get() for m in self.__members] else: members = self.__members return medi...
Population parameter vals == average member parameter vals
def parameters(self): '''Population parameter vals == average member parameter vals''' if len(self.__members) != 0: if self.__num_processes > 1: members = [m.get() for m in self.__members] else: members = self.__members params = {} ...
Returns Member objects of population
def members(self): '''Returns Member objects of population''' if self.__num_processes > 1: return [m.get() for m in self.__members] else: return self.__members
Adds a paramber to the Population
def add_parameter(self, name, min_val, max_val): '''Adds a paramber to the Population Args: name (str): name of the parameter min_val (int or float): minimum value for the parameter max_val (int or float): maximum value for the parameter ''' self.__p...
Generates self. __pop_size Members with randomly initialized values for each parameter added with add_parameter () evaluates their fitness
def generate_population(self): '''Generates self.__pop_size Members with randomly initialized values for each parameter added with add_parameter(), evaluates their fitness ''' if self.__num_processes > 1: process_pool = Pool(processes=self.__num_processes) self.__mem...
Generates the next population from a previously evaluated generation
def next_generation(self, mut_rate=0, max_mut_amt=0, log_base=10): '''Generates the next population from a previously evaluated generation Args: mut_rate (float): mutation rate for new members (0.0 - 1.0) max_mut_amt (float): how much the member is allowed to mutate ...
Private static method: mutates parameter
def __mutate_parameter(value, param, mut_rate, max_mut_amt): '''Private, static method: mutates parameter Args: value (int or float): current value for Member's parameter param (Parameter): parameter object mut_rate (float): mutation rate of the value max...
Private method: determines if any current population members have a fitness score better than the current best
def __determine_best_member(self): '''Private method: determines if any current population members have a fitness score better than the current best ''' if self.__num_processes > 1: members = [m.get() for m in self.__members] else: members = self.__member...
Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options ( lists ).
def update_defaults(self, defaults): """Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists).""" # Then go and look for the other sources of configuration: config = {} # 1. config...
Return a config dictionary with normalized keys regardless of whether the keys were specified in environment variables or in config files
def normalize_keys(self, items): """Return a config dictionary with normalized keys regardless of whether the keys were specified in environment variables or in config files""" normalized = {} for key, val in items: key = key.replace('_', '-') if not key.s...
Returns a generator with all environmental vars with prefix PIP_
def get_environ_vars(self): """Returns a generator with all environmental vars with prefix PIP_""" for key, val in os.environ.items(): if _environ_prefix_re.search(key): yield (_environ_prefix_re.sub("", key).lower(), val)
Return True if the callable throws the specified exception
def throws_exception(callable, *exceptions): """ Return True if the callable throws the specified exception >>> throws_exception(lambda: int('3')) False >>> throws_exception(lambda: int('a')) True >>> throws_exception(lambda: int('a'), KeyError) False """ with context.ExceptionTrap(): with context.Exceptio...
The list from pypi is really a list of versions. We want a list of packages with the list of versions stored inline. This converts the list from pypi into one we can use.
def transform_hits(hits): """ The list from pypi is really a list of versions. We want a list of packages with the list of versions stored inline. This converts the list from pypi into one we can use. """ packages = {} for hit in hits: name = hit['name'] summary = hit['summar...
Convert the result back into the input type.
def _transform_result(typ, result): """Convert the result back into the input type. """ if issubclass(typ, bytes): return tostring(result, encoding='utf-8') elif issubclass(typ, unicode): return tostring(result, encoding='unicode') else: return result
Parses several HTML elements returning a list of elements.
def fragments_fromstring(html, no_leading_text=False, base_url=None, parser=None, **kw): """ Parses several HTML elements, returning a list of elements. The first item in the list may be a string (though leading whitespace is removed). If no_leading_text is true, then it will ...
Parses a single HTML element ; it is an error if there is more than one element or if anything but whitespace precedes or follows the element.
def fragment_fromstring(html, create_parent=False, base_url=None, parser=None, **kw): """ Parses a single HTML element; it is an error if there is more than one element, or if anything but whitespace precedes or follows the element. If ``create_parent`` is true (or is a tag ...
Parse the html returning a single element/ document.
def fromstring(html, base_url=None, parser=None, **kw): """ Parse the html, returning a single element/document. This tries to minimally parse the chunk of text, without knowing if it is a fragment or a document. base_url will set the document's base_url attribute (and the tree's docinfo.URL) ...
Parse a filename URL or file - like object into an HTML document tree. Note: this returns a tree not an element. Use parse (... ). getroot () to get the document root.
def parse(filename_or_url, parser=None, base_url=None, **kw): """ Parse a filename, URL, or file-like object into an HTML document tree. Note: this returns a tree, not an element. Use ``parse(...).getroot()`` to get the document root. You can override the base URL with the ``base_url`` keyword. ...
Helper function to submit a form. Returns a file - like object as from urllib. urlopen (). This object also has a. geturl () function which shows the URL if there were any redirects.
def submit_form(form, extra_values=None, open_http=None): """ Helper function to submit a form. Returns a file-like object, as from ``urllib.urlopen()``. This object also has a ``.geturl()`` function, which shows the URL if there were any redirects. You can use this like:: form = doc.for...
Convert all tags in an HTML tree to XHTML by moving them to the XHTML namespace.
def html_to_xhtml(html): """Convert all tags in an HTML tree to XHTML by moving them to the XHTML namespace. """ try: html = html.getroot() except AttributeError: pass prefix = "{%s}" % XHTML_NAMESPACE for el in html.iter(etree.Element): tag = el.tag if tag[0]...
Convert all tags in an XHTML tree to HTML by removing their XHTML namespace.
def xhtml_to_html(xhtml): """Convert all tags in an XHTML tree to HTML by removing their XHTML namespace. """ try: xhtml = xhtml.getroot() except AttributeError: pass prefix = "{%s}" % XHTML_NAMESPACE prefix_len = len(prefix) for el in xhtml.iter(prefix + "*"): el...
Return an HTML string representation of the document.
def tostring(doc, pretty_print=False, include_meta_content_type=False, encoding=None, method="html", with_tail=True, doctype=None): """Return an HTML string representation of the document. Note: if include_meta_content_type is true this will create a ``<meta http-equiv="Content-Type" ...>`` ta...
Open the HTML document in a web browser saving it to a temporary file to open it. Note that this does not delete the file after use. This is mainly meant for debugging.
def open_in_browser(doc, encoding=None): """ Open the HTML document in a web browser, saving it to a temporary file to open it. Note that this does not delete the file after use. This is mainly meant for debugging. """ import os import webbrowser import tempfile if not isinstance(d...
Get or set any <label > element associated with this element.
def _label__get(self): """ Get or set any <label> element associated with this element. """ id = self.get('id') if not id: return None result = _label_xpath(self, id=id) if not result: return None else: return result[0]
Removes this element from the tree including its children and text. The tail text is joined to the previous element or parent.
def drop_tree(self): """ Removes this element from the tree, including its children and text. The tail text is joined to the previous element or parent. """ parent = self.getparent() assert parent is not None if self.tail: previous = self.getp...