Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def process(self, items_block): out_items = [] for hit in items_block: if __name__ == '__main__': hit['_source']['metadata__enriched_on'] = datetime.datetime_utcnow().isoformat() out_items.append(hit) ...
[ "Return items as they come, updating their metadata__enriched_on field.\n\n :param items_block:\n :return: hits blocks as they come, updating their metadata__enriched_on field. Namedtuple containing:\n - processed: number of processed hits\n - out_items: a list containing items r...
Please provide a description of the function:def get_arthur_params_from_url(cls, url): params = {} args = cls.get_perceval_params_from_url(url) parser = GitLabCommand.setup_cmd_parser() parsed_args = parser.parse(*args) params['owner'] = parsed_args.owner para...
[ " Get the arthur params given a URL for the data source " ]
Please provide a description of the function:def get_perceval_params_from_url(cls, url): params = [] tokens = url.split(' ') repo = tokens[0] owner = repo.split('/')[-2] repository = repo.split('/')[-1] params.append(owner) params.append(repository) ...
[ " Get the perceval params given a URL for the data source " ]
Please provide a description of the function:def get_identities(self, item): ''' Return the identities from an item ''' item = item['data'] # Creators if 'event_hosts' in item: user = self.get_sh_identity(item['event_hosts'][0]) yield user # rsvps ...
[]
Please provide a description of the function:def get_item_sh(self, item): sh_fields = {} # Not shared common get_item_sh because it is pretty specific if 'member' in item: # comment and rsvp identity = self.get_sh_identity(item['member']) elif 'event_ho...
[ " Add sorting hat enrichment fields " ]
Please provide a description of the function:def add_params(cls, cmdline_parser): parser = cmdline_parser parser.add_argument("-e", "--elastic_url", default="http://127.0.0.1:9200", help="Host with elastic search (default: http://127.0.0.1:9200)") parser.ad...
[ " Shared params in all backends " ]
Please provide a description of the function:def get_p2o_params_from_url(cls, url): # if the url doesn't contain a filter separator, return it if PRJ_JSON_FILTER_SEPARATOR not in url: return {"url": url} # otherwise, add the url to the params params = {'url': url.s...
[ " Get the p2o params given a URL for the data source " ]
Please provide a description of the function:def add_update_date(self, item): updated = unixtime_to_datetime(item['updated_on']) timestamp = unixtime_to_datetime(item['timestamp']) item['metadata__updated_on'] = updated.isoformat() # Also add timestamp used in incremental enrich...
[ " All item['updated_on'] from perceval is epoch " ]
Please provide a description of the function:def feed(self, from_date=None, from_offset=None, category=None, latest_items=None, arthur_items=None, filter_classified=None): if self.fetch_archive: items = self.perceval_backend.fetch_from_archive() self.feed_items(ite...
[ " Feed data in Elastic from Perceval or Arthur " ]
Please provide a description of the function:def _items_to_es(self, json_items): if len(json_items) == 0: return logger.info("Adding items to Ocean for %s (%i items)" % (self, len(json_items))) field_id = self.get_field_unique_id() inserted = ...
[ " Append items JSON to ES (data source state) " ]
Please provide a description of the function:def get_identities(self, item): def add_sh_github_identity(user, user_field, rol): github_repo = None if GITHUB in item['origin']: github_repo = item['origin'].replace(GITHUB, '') github_r...
[ " Return the identities from an item.\n If the repo is in GitHub, get the usernames from GitHub. ", " Add a new github identity to SH if it does not exists " ]
Please provide a description of the function:def get_github_login(self, user, rol, commit_hash, repo): login = None try: login = self.github_logins[user] except KeyError: # Get the login from github API GITHUB_API_URL = "https://api.github.com" ...
[ " rol: author or committer " ]
Please provide a description of the function:def __fix_field_date(self, item, attribute): field_date = str_to_datetime(item[attribute]) try: _ = int(field_date.strftime("%z")[0:3]) except ValueError: logger.warning("%s in commit %s has a wrong format", attribut...
[ "Fix possible errors in the field date" ]
Please provide a description of the function:def enrich_items(self, ocean_backend, events=False): headers = {"Content-Type": "application/json"} max_items = self.elastic.max_items_bulk current = 0 total = 0 bulk_json = "" total_signed_off = 0 total_mul...
[ " Implementation supporting signed-off and multiauthor/committer commits." ]
Please provide a description of the function:def update_items(self, ocean_backend, enrich_backend): fltr = { 'name': 'origin', 'value': [self.perceval_backend.origin] } logger.debug("[update-items] Checking commits for %s.", self.perceval_backend.origin) ...
[ "Retrieve the commits not present in the original repository and delete\n the corresponding documents from the raw and enriched indexes" ]
Please provide a description of the function:def delete_commit_branches(self, enrich_backend): fltr = % self.perceval_backend.origin # reset references in enrich index es_query = % fltr index = enrich_backend.elastic.index_url r = self.requests.post(index + "/_update...
[ "Delete the information about branches from the documents representing\n commits in the enriched index.\n\n :param enrich_backend: the enrich backend\n ", "\n \"filter\": [\n {\n \"term\": {\n \"origin\": \"%s\"\n ...
Please provide a description of the function:def add_commit_branches(self, git_repo, enrich_backend): to_process = [] for hash, refname in git_repo._discover_refs(remote=True): if not refname.startswith('refs/heads/'): continue commit_count = 0 ...
[ "Add the information about branches to the documents representing commits in\n the enriched index. Branches are obtained using the command `git ls-remote`,\n then for each branch, the list of commits is retrieved via the command `git rev-list branch-name` and\n used to update the corresponding ...
Please provide a description of the function:def remove_commits(self, items, index, attribute, origin): es_query = ''' { "query": { "bool": { "must": { "term": { "origin": "%s" ...
[ "Delete documents that correspond to commits deleted in the Git repository\n\n :param items: target items to be deleted\n :param index: target index\n :param attribute: name of the term attribute to search items\n :param origin: name of the origin from where the items must be deleted\n ...
Please provide a description of the function:def find_general_mappings(es_major_version): if es_major_version not in ES_SUPPORTED: print("Elasticsearch version not supported %s (supported %s)" % (es_major_version, ES_SUPPORTED)) sys.exit(1) # By default all strings are not analyzed in ES ...
[ "\n Find the general mappings applied to all data sources\n :param es_major_version: string with the major version for Elasticsearch\n :return: a dict with the mappings (raw and enriched)\n ", "\n {\n \"dynamic_templates\": [\n { \"notanalyzed\": {\n \"match...
Please provide a description of the function:def find_ds_mapping(data_source, es_major_version): mappings = {"raw": None, "enriched": None} # Backend connectors connectors = get_connectors() try: raw_klass = connectors[data_source][1] enrich_klass = connectors[data...
[ "\n Find the mapping given a perceval data source\n\n :param data_source: name of the perceval data source\n :param es_major_version: string with the major version for Elasticsearch\n :return: a dict with the mappings (raw and enriched)\n " ]
Please provide a description of the function:def areas_of_code(git_enrich, in_conn, out_conn, block_size=100): aoc = AreasOfCode(in_connector=in_conn, out_connector=out_conn, block_size=block_size, git_enrich=git_enrich) ndocs = aoc.analyze() return ndocs
[ "Build and index for areas of code from a given Perceval RAW index.\n\n :param block_size: size of items block.\n :param git_enrich: GitEnrich object to deal with SortingHat affiliations.\n :param in_conn: ESPandasConnector to read from.\n :param out_conn: ESPandasConnector to write to.\n :return: nu...
Please provide a description of the function:def make_hashcode(uuid, filepath, file_event): content = ':'.join([uuid, filepath, file_event]) hashcode = hashlib.sha1(content.encode('utf-8')) return hashcode.hexdigest()
[ "Generate a SHA1 based on the given arguments.\n :param uuid: perceval uuid of the item\n :param filepath: path of the corresponding file\n :param file_event: commit file event\n :returns: a SHA1 hash code\n " ]
Please provide a description of the function:def write(self, items): if self._read_only: raise IOError("Cannot write, Connector created as Read Only") # Uploading info to the new ES rows = items.to_dict("index") docs = [] for row_index in rows.keys(): ...
[ "Write items into ElasticSearch.\n\n :param items: Pandas DataFrame\n " ]
Please provide a description of the function:def process(self, items_block): logger.info(self.__log_prefix + " New commits: " + str(len(items_block))) # Create events from commits git_events = Git(items_block, self._git_enrich) events_df = git_events.eventize(2) logge...
[ "Process items to add file related information.\n\n Eventize items creating one new item per each file found in the commit (excluding\n files with no actions performed on them). For each event, file path, file name,\n path parts, file type and file extension are added as fields.\n\n :par...
Please provide a description of the function:def get_perceval_params_from_url(cls, url): params = [] dparam = cls.get_arthur_params_from_url(url) params.append(dparam['url']) params.append(dparam['channel']) return params
[ " Get the perceval params given a URL for the data source " ]
Please provide a description of the function:def get_repository_filter(perceval_backend, perceval_backend_name, term=False): from .github import GITHUB filter_ = {} if not perceval_backend: return filter_ field = 'origin' value = perceval_backend.origin ...
[ " Get the filter needed for get the items in a repository " ]
Please provide a description of the function:def get_time_diff_days(start, end): ''' Number of days between two dates in UTC format ''' if start is None or end is None: return None if type(start) is not datetime.datetime: start = parser.parse(start).replace(tzinfo=None) if type(end) i...
[]
Please provide a description of the function:def unixtime_to_datetime(ut): dt = datetime.datetime.utcfromtimestamp(ut) dt = dt.replace(tzinfo=tz.tzutc()) return dt
[ "Convert a unixtime timestamp to a datetime object.\n The function converts a timestamp in Unix format to a\n datetime object. UTC timezone will also be set.\n :param ut: Unix timestamp to convert\n :returns: a datetime object\n :raises InvalidDateError: when the given timestamp cannot be\n co...
Please provide a description of the function:def get_arthur_params_from_url(cls, url): # In the url the org and the repository are included params = url.split() params = {"owner": params[0], "repository": params[1]} return params
[ " Get the arthur params given a URL for the data source " ]
Please provide a description of the function:def get_identities(self, item): if 'authorData' in item['data']['fields']: user = self.get_sh_identity(item['data']['fields']['authorData']) yield user if 'ownerData' in item['data']['fields']: user = self.get_sh...
[ " Return the identities from an item " ]
Please provide a description of the function:def get_rich_events(self, item): # To get values from the task eitem = self.get_rich_item(item) # Fields that don't change never task_fields_nochange = ['author_userName', 'creation_date', 'url', 'id', 'bug_id'] # Follow cha...
[ "\n In the events there are some common fields with the task. The name\n of the field must be the same in the task and in the event\n so we can filer using it in task and event at the same time.\n\n * Fields that don't change: the field does not change with the events\n in a task ...
Please provide a description of the function:def __fill_phab_ids(self, item): for p in item['projects']: if p and 'name' in p and 'phid' in p: self.phab_ids_names[p['phid']] = p['name'] if 'authorData' not in item['fields'] or not item['fields']['authorData']: ...
[ " Get mappings between phab ids and names " ]
Please provide a description of the function:def starting_at(self, datetime_or_str): if isinstance(datetime_or_str, str): self._starting_at = parse(datetime_or_str) elif isinstance(datetime_or_str, datetime.datetime): self._starting_at = datetime_or_str else: ...
[ "\n Set the starting time for the cron job. If not specified, the starting time will always\n be the beginning of the interval that is current when the cron is started.\n\n :param datetime_or_str: a datetime object or a string that dateutil.parser can understand\n :return: self\n ...
Please provide a description of the function:def every(self, **kwargs): if len(kwargs) != 1: raise ValueError('.every() method must be called with exactly one keyword argument') self._every_kwargs = self._clean_kwargs(kwargs) return self
[ "\n Specify the interval at which you want the job run. Takes exactly one keyword argument.\n That argument must be one named one of [second, minute, hour, day, week, month, year] or\n their plural equivalents.\n\n :param kwargs: Exactly one keyword argument\n :return: self\n ...
Please provide a description of the function:def run(self, func, *func_args, **func__kwargs): self._func = func self._func_args = func_args self._func_kwargs = func__kwargs return self
[ "\n Specify the function to run at the scheduled times\n\n :param func: a callable\n :param func_args: the args to the callable\n :param func__kwargs: the kwargs to the callable\n :return:\n " ]
Please provide a description of the function:def _get_target(self): if None in [self._func, self._func_kwargs, self._func_kwargs, self._every_kwargs]: raise ValueError('You must call the .every() and .run() methods on every tab.') return self._loop
[ "\n returns a callable with no arguments designed\n to be the target of a Subprocess\n " ]
Please provide a description of the function:def wrapped_target(target, q_stdout, q_stderr, q_error, robust, name, *args, **kwargs): # pragma: no cover import sys sys.stdout = IOQueue(q_stdout) sys.stderr = IOQueue(q_stderr) try: target(*args, **kwargs) except: if not robust: ...
[ "\n Wraps a target with queues replacing stdout and stderr\n " ]
Please provide a description of the function:def loop(self, max_seconds=None): loop_started = datetime.datetime.now() self._is_running = True while self._is_running: self.process_error_queue(self.q_error) if max_seconds is not None: if (datetim...
[ "\n Main loop for the process. This will run continuously until maxiter\n " ]
Please provide a description of the function:def escape(string, escape_pattern): try: return string.translate(escape_pattern) except AttributeError: warnings.warn("Non-string-like data passed. " "Attempting to convert to 'str'.") return str(string).translate(ta...
[ "Assistant function for string escaping" ]
Please provide a description of the function:def _make_serializer(meas, schema, rm_none, extra_tags, placeholder): # noqa: C901 _validate_schema(schema, placeholder) tags = [] fields = [] ts = None meas = meas for k, t in schema.items(): if t is MEASUREMENT: meas = f"{{...
[ "Factory of line protocol parsers" ]
Please provide a description of the function:def lineprotocol( cls=None, *, schema: Optional[Mapping[str, type]] = None, rm_none: bool = False, extra_tags: Optional[Mapping[str, str]] = None, placeholder: bool = False ): def _lineprotocol(cls): _schema =...
[ "Adds ``to_lineprotocol`` method to arbitrary user-defined classes\n\n :param cls: Class to monkey-patch\n :param schema: Schema dictionary (attr/type pairs).\n :param rm_none: Whether apply a regex to remove ``None`` values.\n If ``False``, passing ``None`` values to boolean, integer or float or ti...
Please provide a description of the function:def serialize(point: Mapping, measurement=None, **extra_tags) -> bytes: tags = _serialize_tags(point, extra_tags) return ( f'{_serialize_measurement(point, measurement)}' f'{"," if tags else ""}{tags} ' f'{_serialize_fields(point)} ' ...
[ "Converts dictionary-like data into a single line protocol line (point)" ]
Please provide a description of the function:def _serialize_fields(point): output = [] for k, v in point['fields'].items(): k = escape(k, key_escape) if isinstance(v, bool): output.append(f'{k}={v}') elif isinstance(v, int): output.append(f'{k}={v}i') ...
[ "Field values can be floats, integers, strings, or Booleans." ]
Please provide a description of the function:def serialize(data, measurement=None, tag_columns=None, **extra_tags): if isinstance(data, bytes): return data elif isinstance(data, str): return data.encode('utf-8') elif hasattr(data, 'to_lineprotocol'): return data.to_lineprotocol(...
[ "Converts input data into line protocol format" ]
Please provide a description of the function:def iterpoints(resp: dict, parser: Optional[Callable] = None) -> Iterator[Any]: for statement in resp['results']: if 'series' not in statement: continue for series in statement['series']: if parser is None: ret...
[ "Iterates a response JSON yielding data point by point.\n\n Can be used with both regular and chunked responses.\n By default, returns just a plain list of values representing each point,\n without column names, or other metadata.\n\n In case a specific format is needed, an optional ``parser`` argument ...
Please provide a description of the function:def parse(resp) -> DataFrameType: statements = [] for statement in resp['results']: series = {} for s in statement.get('series', []): series[_get_name(s)] = _drop_zero_index(_serializer(s)) statements.append(series) if le...
[ "Makes a dictionary of DataFrames from a response object" ]
Please provide a description of the function:def _itertuples(df): cols = [df.iloc[:, k] for k in range(len(df.columns))] return zip(df.index, *cols)
[ "Custom implementation of ``DataFrame.itertuples`` that\n returns plain tuples instead of namedtuples. About 50% faster.\n " ]
Please provide a description of the function:def serialize(df, measurement, tag_columns=None, **extra_tags) -> bytes: # Pre-processing if measurement is None: raise ValueError("Missing 'measurement'") if not isinstance(df.index, pd.DatetimeIndex): raise ValueError('DataFrame index is no...
[ "Converts a Pandas DataFrame into line protocol format" ]
Please provide a description of the function:def runner(coro): @wraps(coro) def inner(self, *args, **kwargs): if self.mode == 'async': return coro(self, *args, **kwargs) return self._loop.run_until_complete(coro(self, *args, **kwargs)) return inner
[ "Function execution decorator." ]
Please provide a description of the function:async def create_session(self, **kwargs): self.opts.update(kwargs) self._session = aiohttp.ClientSession(**self.opts, loop=self._loop) if self.redis_opts: if aioredis: self._redis = await aioredis.create_redis(**se...
[ "Creates an :class:`aiohttp.ClientSession`\n\n Override this or call it with ``kwargs`` to use other :mod:`aiohttp`\n functionality not covered by :class:`~.InfluxDBClient.__init__`\n " ]
Please provide a description of the function:async def ping(self) -> dict: if not self._session: await self.create_session() async with self._session.get(self.url.format(endpoint='ping')) as resp: logger.debug(f'{resp.status}: {resp.reason}') return dict(resp...
[ "Pings InfluxDB\n\n Returns a dictionary containing the headers of the response from ``influxd``.\n " ]
Please provide a description of the function:async def write( self, data: Union[PointType, Iterable[PointType]], measurement: Optional[str] = None, db: Optional[str] = None, precision: Optional[str] = None, rp: Optional[str] = None, tag_columns: Optional[Iterable]...
[ "Writes data to InfluxDB.\n Input can be:\n\n 1. A mapping (e.g. ``dict``) containing the keys:\n ``measurement``, ``time``, ``tags``, ``fields``\n 2. A Pandas :class:`~pandas.DataFrame` with a :class:`~pandas.DatetimeIndex`\n 3. A user defined class decorated w/\n :...
Please provide a description of the function:async def query( self, q: AnyStr, *, epoch: str = 'ns', chunked: bool = False, chunk_size: Optional[int] = None, db: Optional[str] = None, use_cache: bool = False, ) -> Union[AsyncGenerator[ResultType, None]...
[ "Sends a query to InfluxDB.\n Please refer to the InfluxDB documentation for all the possible queries:\n https://docs.influxdata.com/influxdb/latest/query_language/\n\n :param q: Raw query string\n :param db: Database to be queried. Defaults to `self.db`.\n :param epoch: Precision...
Please provide a description of the function:def _check_error(response): if 'error' in response: raise InfluxDBError(response['error']) elif 'results' in response: for statement in response['results']: if 'error' in statement: msg = '{...
[ "Checks for JSON error messages and raises Python exception" ]
Please provide a description of the function:def create_magic_packet(macaddress): if len(macaddress) == 12: pass elif len(macaddress) == 17: sep = macaddress[2] macaddress = macaddress.replace(sep, '') else: raise ValueError('Incorrect MAC address format') # Pad the...
[ "\n Create a magic packet.\n\n A magic packet is a packet that can be used with the for wake on lan\n protocol to wake up a computer. The packet is constructed from the\n mac address given as a parameter.\n\n Args:\n macaddress (str): the mac address that should be parsed into a\n m...
Please provide a description of the function:def send_magic_packet(*macs, **kwargs): packets = [] ip = kwargs.pop('ip_address', BROADCAST_IP) port = kwargs.pop('port', DEFAULT_PORT) for k in kwargs: raise TypeError('send_magic_packet() got an unexpected keyword ' 'ar...
[ "\n Wake up computers having any of the given mac addresses.\n\n Wake on lan must be enabled on the host device.\n\n Args:\n macs (str): One or more macaddresses of machines to wake.\n\n Keyword Args:\n ip_address (str): the ip address of the host to send the magic packet\n ...
Please provide a description of the function:def main(argv=None): parser = argparse.ArgumentParser( description='Wake one or more computers using the wake on lan' ' protocol.') parser.add_argument( 'macs', metavar='mac address', nargs='+', help='T...
[ "\n Run wake on lan as a CLI application.\n\n " ]
Please provide a description of the function:def mjml(parser, token): nodelist = parser.parse(('endmjml',)) parser.delete_first_token() tokens = token.split_contents() if len(tokens) != 1: raise template.TemplateSyntaxError("'%r' tag doesn't receive any arguments." % tokens[0]) return M...
[ "\n Compile MJML template after render django template.\n\n Usage:\n {% mjml %}\n .. MJML template code ..\n {% endmjml %}\n " ]
Please provide a description of the function:def build_models_dict(annotated_models): logger = getLogger(__name__) logger.debug("Parsing models {0}".format(annotated_models) ) parsed_models = {} for family_annotation in annotated_models: family_id = family_annotation.split(':')[0] ...
[ "\n Take a list with annotated genetic inheritance patterns for each\n family and returns a dictionary with family_id as key and a list of\n genetic models as value.\n \n Args:\n annotated_models : A list on the form ['1:AD','2:AR_comp|AD_dn']\n \n Returns:\n parsed_models ...
Please provide a description of the function:def split_variants(variant_dict, header_parser, allele_symbol='0'): logger = getLogger(__name__) logger.info("Allele symbol {0}".format(allele_symbol)) alternatives = variant_dict['ALT'].split(',') reference = variant_dict['REF'] number_of_values = 1...
[ "\n Checks if there are multiple alternative alleles and splitts the \n variant.\n If there are multiple alternatives the info fields, vep annotations \n and genotype calls will be splitted in the correct way\n \n Args:\n variant_dict: a dictionary with the variant information\n \n Yi...
Please provide a description of the function:def build_rank_score_dict(rank_scores): logger = getLogger(__name__) logger.debug("Checking rank scores: {0}".format(rank_scores)) scores = {} for family in rank_scores: entry = family.split(':') try: family_id = entry[0] ...
[ "\n Take a list with annotated rank scores for each family and returns a \n dictionary with family_id as key and a list of genetic models as value.\n \n Args:\n rank_scores : A list on the form ['1:12','2:20']\n \n Returns:\n scores : A dictionary with family id:s as key and...
Please provide a description of the function:def check_info_annotation(annotation, info, extra_info, alternatives, individuals=[]): number = extra_info['Number'] if is_number(number): number_of_entrys = float(number) if number_of_entrys != 0: if len(annotation) != number_of...
[ "\n Check if the info annotation corresponds to the metadata specification\n \n Arguments:\n annotation (list): The annotation from the vcf file\n info (str): Name of the info field\n extra_info (dict): The metadata specification\n alternatives (list): A list with the alternativ...
Please provide a description of the function:def format_variant(line, header_parser, check_info=False): logger = getLogger(__name__) individuals = [] vcf_header = header_parser.header individuals = header_parser.individuals variant_line = line.rstrip().split('\t') logger.debug("Checkin...
[ "\n Yield the variant in the right format. \n \n If the variants should be splitted on alternative alles one variant \n for each alternative will be yielded.\n \n Arguments:\n line (str): A string that represents a variant line in the vcf format\n header_parser (HeaderParser): A Head...
Please provide a description of the function:def build_info_string(info): info_list = [] for annotation in info: if info[annotation]: info_list.append('='.join([annotation, ','.join(info[annotation])])) else: info_list.append(annotation) return...
[ "\n Build a new vcf INFO string based on the information in the info_dict.\n \n The info is a dictionary with vcf info keys as keys and lists of vcf values\n as values. If there is no value False is value in info\n \n Args:\n info (dict): A dictionary with information from the vcf file\n ...
Please provide a description of the function:def build_info_dict(vcf_info): logger = logging.getLogger(__name__) logger.debug("Building info dict") info_dict = OrderedDict() for info in vcf_info.split(';'): info = info.split('=') if len(info) > 1: # If the INFO entr...
[ "\n Build a dictionary from the info of a vcf line\n \n The dictionary will have the info keys as keys and info values as values.\n Values will allways be lists that are splitted on ','\n \n Arguments:\n vcf_info (str): A string with vcf info\n \n Returns:\n info_dict (OrderedD...
Please provide a description of the function:def split_genotype(genotype, gt_format, alternative_number, allele_symbol = '0'): logger = getLogger(__name__) logger.info("Allele symbol {0}".format(allele_symbol)) splitted_genotype = genotype.split(':') logger.debug("Parsing genotype {0}".format...
[ "\n Take a genotype call and make a new one that is working for the new\n splitted variant\n \n Arguments:\n genotype (str): The original genotype call\n gt_format (str): The format of the gt call\n alternative_number (int): What genotype call should we return\n allele_symbol...
Please provide a description of the function:def parse_header_line(self, line): self.header = line[1:].rstrip().split('\t') if len(self.header) < 9: self.header = line[1:].rstrip().split() self.individuals = self.header[9:]
[ "docstring for parse_header_line" ]
Please provide a description of the function:def print_header(self): lines_to_print = [] lines_to_print.append('##fileformat='+self.fileformat) if self.filedate: lines_to_print.append('##fileformat='+self.fileformat) for filt in self.filter_dict: ...
[ "Returns a list with the header lines if proper format" ]
Please provide a description of the function:def add_info(self, info_id, number, entry_type, description): info_line = '##INFO=<ID={0},Number={1},Type={2},Description="{3}">'.format( info_id, number, entry_type, description ) self.logger.info("Adding info line to vcf: {0}".f...
[ "\n Add an info line to the header.\n \n Arguments:\n info_id (str): The id of the info line\n number (str): Integer or any of [A,R,G,.]\n entry_type (str): Any of [Integer,Float,Flag,Character,String]\n description (str): A description of the info li...
Please provide a description of the function:def add_version_tracking(self, info_id, version, date, command_line=''): other_line = '##Software=<ID={0},Version={1},Date="{2}",CommandLineOptions="{3}">'.format( info_id, version, date, command_line) self.other_dict[info_id] = other_li...
[ "\n Add a line with information about which software that was run and when \n to the header.\n \n Arguments:\n info_id (str): The id of the info line\n version (str): The version of the software used\n date (str): Date when software was run\n c...
Please provide a description of the function:def build_compounds_dict(compounds): logger = getLogger(__name__) logger.debug("Parsing compounds: {0}".format(compounds)) parsed_compounds = {} for family_info in compounds: logger.debug("Parsing entry {0}".format(family_info)) spli...
[ "\n Take a list with annotated compound variants for each family and \n returns a dictionary with family_id as key and a list of dictionarys\n that holds the information about the compounds.\n \n Args:\n compounds : A list that can be either on the form \n [\n ...
Please provide a description of the function:def cli(variant_file, vep, split, outfile, verbose, silent, check_info, allele_symbol, logfile, loglevel): from vcf_parser import logger, init_log if not loglevel: if verbose: loglevel = 'INFO' init_log(logger, logfile, loglevel...
[ "\n Tool for parsing vcf files.\n \n Prints the vcf file to output. \n If --split/-s is used all multiallelic calls will be splitted and printed \n as single variant calls.\n For more information, please see github.com/moonso/vcf_parser.\n " ]
Please provide a description of the function:def cli(variant_file, vep, split): from datetime import datetime from pprint import pprint as pp if variant_file == '-': my_parser = VCFParser(fsock=sys.stdin, split_variants=split) else: my_parser = VCFParser(infile = variant_file, split...
[ "Parses a vcf file.\\n\n \\n\n Usage:\\n\n parser infile.vcf\\n\n If pipe:\\n\n parser - \n " ]
Please provide a description of the function:def add_variant(self, chrom, pos, rs_id, ref, alt, qual, filt, info, form=None, genotypes=[]): variant_info = [chrom, pos, rs_id, ref, alt, qual, filt, info] if form: variant_info.append(form) for individual in genotypes: ...
[ "\n Add a variant to the parser.\n \n This function is for building a vcf. It takes the relevant parameters \n and make a vcf variant in the proper format.\n " ]
Please provide a description of the function:def build_vep_string(vep_info, vep_columns): logger = getLogger(__name__) logger.debug("Building vep string from {0}".format(vep_info)) logger.debug("Found vep headers {0}".format(vep_columns)) vep_strings = [] for vep_annotation in vep_info: ...
[ "\n Build a vep string formatted string.\n \n Take a list with vep annotations and build a new vep string\n \n Args:\n vep_info (list): A list with vep annotation dictionaries\n vep_columns (list): A list with the vep column names found in the\n header of the vcf\n \n Retur...
Please provide a description of the function:def build_vep_annotation(csq_info, reference, alternatives, vep_columns): logger = getLogger(__name__) # The keys in the vep dict are the vcf formatted alternatives, values are the # dictionaries with vep annotations vep_dict = {} # If we have seve...
[ "\n Build a dictionary with the vep information from the vep annotation.\n \n Indels are handled different by vep depending on the number of \n alternative alleles there is for a variant.\n \n If only one alternative:\n \n Insertion: vep represents the alternative by removing the fir...
Please provide a description of the function:def user_login(self, email=None, password=None): email = six.moves.input("Email: ") if email is None else email password = getpass.getpass() if password is None else password login_data = { "method": "user.login", "pa...
[ "Login with email, password and get back a session cookie\n\n :type email: str\n :param email: The email used for authentication\n :type password: str\n :param password: The password used for authentication\n " ]
Please provide a description of the function:def demo_login(self, auth=None, url=None): assert all([ auth or url, # Must provide at least one not (auth and url) # Cannot provide more than one ]) if url is None: url = "https://piazza.com/demo_login" ...
[ "Authenticate with a \"Share Your Class\" URL using a demo user.\n\n You may provide either the entire ``url`` or simply the ``auth``\n parameter.\n\n :param url: Example - \"https://piazza.com/demo_login?nid=hbj11a1gcvl1s6&auth=06c111b\"\n :param auth: Example - \"06c111b\"\n " ]
Please provide a description of the function:def content_get(self, cid, nid=None): r = self.request( method="content.get", data={"cid": cid}, nid=nid ) return self._handle_error(r, "Could not get post {}.".format(cid))
[ "Get data from post `cid` in network `nid`\n\n :type nid: str\n :param nid: This is the ID of the network (or class) from which\n to query posts. This is optional and only to override the existing\n `network_id` entered when created the class\n :type cid: str|int\n ...
Please provide a description of the function:def content_create(self, params): r = self.request( method="content.create", data=params ) return self._handle_error( r, "Could not create object {}.".format(repr(params)) )
[ "Create a post or followup.\n\n :type params: dict\n :param params: A dict of options to pass to the endpoint. Depends on\n the specific type of content being created.\n :returns: Python object containing returned data\n " ]
Please provide a description of the function:def add_students(self, student_emails, nid=None): r = self.request( method="network.update", data={ "from": "ClassSettingsPage", "add_students": student_emails }, nid=nid, ...
[ "Enroll students in a network `nid`.\n\n Piazza will email these students with instructions to\n activate their account.\n\n :type student_emails: list of str\n :param student_emails: A listing of email addresses to enroll\n in the network (or class). This can be a list of le...
Please provide a description of the function:def get_all_users(self, nid=None): r = self.request( method="network.get_all_users", nid=nid ) return self._handle_error(r, "Could not get users.")
[ "Get a listing of data for each user in a network `nid`\n\n :type nid: str\n :param nid: This is the ID of the network to get users\n from. This is optional and only to override the existing\n `network_id` entered when created the class\n :returns: Python object containin...
Please provide a description of the function:def get_users(self, user_ids, nid=None): r = self.request( method="network.get_users", data={"ids": user_ids}, nid=nid ) return self._handle_error(r, "Could not get users.")
[ "Get a listing of data for specific users `user_ids` in\n a network `nid`\n\n :type user_ids: list of str\n :param user_ids: a list of user ids. These are the same\n ids that are returned by get_all_users.\n :type nid: str\n :param nid: This is the ID of the network t...
Please provide a description of the function:def remove_users(self, user_ids, nid=None): r = self.request( method="network.update", data={"remove_users": user_ids}, nid=nid, nid_key="id" ) return self._handle_error(r, "Could not remove use...
[ "Remove users from a network `nid`\n\n :type user_ids: list of str\n :param user_ids: a list of user ids. These are the same\n ids that are returned by get_all_users.\n :type nid: str\n :param nid: This is the ID of the network to remove students\n from. This is o...
Please provide a description of the function:def get_my_feed(self, limit=150, offset=20, sort="updated", nid=None): r = self.request( method="network.get_my_feed", nid=nid, data=dict( limit=limit, offset=offset, sort=so...
[ "Get my feed\n\n :type limit: int\n :param limit: Number of posts from feed to get, starting from ``offset``\n :type offset: int\n :param offset: Offset starting from bottom of feed\n :type sort: str\n :param sort: How to sort feed that will be retrieved; only current\n ...
Please provide a description of the function:def filter_feed(self, updated=False, following=False, folder=False, filter_folder="", sort="updated", nid=None): assert sum([updated, following, folder]) == 1 if folder: assert filter_folder if updated: ...
[ "Get filtered feed\n\n Only one filter type (updated, following, folder) is possible.\n\n :type nid: str\n :param nid: This is the ID of the network to get the feed\n from. This is optional and only to override the existing\n `network_id` entered when created the class\n ...
Please provide a description of the function:def search(self, query, nid=None): r = self.request( method="network.search", nid=nid, data=dict(query=query) ) return self._handle_error(r, "Search with query '{}' failed." ...
[ "Search for posts with ``query``\n\n :type nid: str\n :param nid: This is the ID of the network to get the feed\n from. This is optional and only to override the existing\n `network_id` entered when created the class\n :type query: str\n :param query: The search qu...
Please provide a description of the function:def get_stats(self, nid=None): r = self.request( api_type="main", method="network.get_stats", nid=nid, ) return self._handle_error(r, "Could not retrieve stats for class.")
[ "Get statistics for class\n\n :type nid: str\n :param nid: This is the ID of the network to get stats\n from. This is optional and only to override the existing\n `network_id` entered when created the class\n " ]
Please provide a description of the function:def request(self, method, data=None, nid=None, nid_key='nid', api_type="logic", return_response=False): self._check_authenticated() nid = nid if nid else self._nid if data is None: data = {} headers = {} ...
[ "Get data from arbitrary Piazza API endpoint `method` in network `nid`\n\n :type method: str\n :param method: An internal Piazza API method name like `content.get`\n or `network.get_users`\n :type data: dict\n :param data: Key-value data to pass to Piazza in the request\n ...
Please provide a description of the function:def _handle_error(self, result, err_msg): if result.get(u'error'): raise RequestError("{}\nResponse: {}".format( err_msg, json.dumps(result, indent=2) )) else: return result.get(u're...
[ "Check result for error\n\n :type result: dict\n :param result: response body\n :type err_msg: str\n :param err_msg: The message given to the :class:`RequestError` instance\n raised\n :returns: Actual result from result\n :raises RequestError: If result has error...
Please provide a description of the function:def user_login(self, email=None, password=None): self._rpc_api = PiazzaRPC() self._rpc_api.user_login(email=email, password=password)
[ "Login with email, password and get back a session cookie\n\n :type email: str\n :param email: The email used for authentication\n :type password: str\n :param password: The password used for authentication\n " ]
Please provide a description of the function:def demo_login(self, auth=None, url=None): self._rpc_api = PiazzaRPC() self._rpc_api.demo_login(auth=auth, url=url)
[ "Authenticate with a \"Share Your Class\" URL using a demo user.\n\n You may provide either the entire ``url`` or simply the ``auth``\n parameter.\n\n :param url: Example - \"https://piazza.com/demo_login?nid=hbj11a1gcvl1s6&auth=06c111b\"\n :param auth: Example - \"06c111b\"\n " ]
Please provide a description of the function:def network(self, network_id): self._ensure_authenticated() return Network(network_id, self._rpc_api.session)
[ "Returns :class:`Network` instance for ``network_id``\n\n :type network_id: str\n :param network_id: This is the ID of the network.\n This can be found by visiting your class page\n on Piazza's web UI and grabbing it from\n https://piazza.com/class/{network_id}\n ...
Please provide a description of the function:def get_user_classes(self): # Previously getting classes from profile (such a list is incomplete) # raw_classes = self.get_user_profile().get('all_classes').values() # Get classes from the user status (includes all classes) status = ...
[ "Get list of the current user's classes. This is a subset of the\n information returned by the call to ``get_user_status``.\n\n :returns: Classes of currently authenticated user\n :rtype: list\n " ]
Please provide a description of the function:def nonce(): nonce_part1 = _int2base(int(_time()*1000), 36) nonce_part2 = _int2base(round(_random()*1679616), 36) return "{}{}".format(nonce_part1, nonce_part2)
[ "\n Returns a new nonce to be used with the Piazza API.\n " ]
Please provide a description of the function:def _int2base(x, base): if base > len(_exradix_digits): raise ValueError( "Base is too large: The defined digit set only allows for " "bases smaller than " + len(_exradix_digits) + "." ) if x > 0: sign = 1 ...
[ "\n Converts an integer from base 10 to some arbitrary numerical base,\n and return a string representing the number in the new base (using\n letters to extend the numerical digits).\n\n :type x: int\n :param x: The integer to convert\n :type base: int\n :param base: The base to convert...
Please provide a description of the function:def iter_all_posts(self, limit=None): feed = self.get_feed(limit=999999, offset=0) cids = [post['id'] for post in feed["feed"]] if limit is not None: cids = cids[:limit] for cid in cids: yield self.get_post(cid...
[ "Get all posts visible to the current user\n\n This grabs you current feed and ids of all posts from it; each post\n is then individually fetched. This method does not go against\n a bulk endpoint; it retrieves each post individually, so a\n caution to the user when using this.\n\n ...
Please provide a description of the function:def create_post(self, post_type, post_folders, post_subject, post_content, is_announcement=0, bypass_email=0, anonymous=False): params = { "anonymous": "yes" if anonymous else "no", "subject": post_subject, "content": post...
[ "Create a post\n\n It seems like if the post has `<p>` tags, then it's treated as HTML,\n but is treated as text otherwise. You'll want to provide `content`\n accordingly.\n\n :type post_type: str\n :param post_type: 'note', 'question'\n :type post_folders: str\n :pa...
Please provide a description of the function:def create_followup(self, post, content, anonymous=False): try: cid = post["id"] except KeyError: cid = post params = { "cid": cid, "type": "followup", # For followups, the content...
[ "Create a follow-up on a post `post`.\n\n It seems like if the post has `<p>` tags, then it's treated as HTML,\n but is treated as text otherwise. You'll want to provide `content`\n accordingly.\n\n :type post: dict|str|int\n :param post: Either the post dict returned by another ...
Please provide a description of the function:def create_instructor_answer(self, post, content, revision, anonymous=False): try: cid = post["id"] except KeyError: cid = post params = { "cid": cid, "type": "i_answer", "content":...
[ "Create an instructor's answer to a post `post`.\n\n It seems like if the post has `<p>` tags, then it's treated as HTML,\n but is treated as text otherwise. You'll want to provide `content`\n accordingly.\n\n :type post: dict|str|int\n :param post: Either the post dict returned ...