_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q234800
ElasticSearch.all_properties
train
def all_properties(self): """Get all properties of a given index""" properties = {} r = self.requests.get(self.index_url + "/_mapping", headers=HEADER_JSON, verify=False) try: r.raise_for_status() r_json = r.json() if 'items' not in r_json[self.index...
python
{ "resource": "" }
q234801
get_kibiter_version
train
def get_kibiter_version(url): """ Return kibiter major number version The url must point to the Elasticsearch used by Kibiter """ config_url = '.kibana/config/_search' # Avoid having // in the URL because ES will fail if url[-1] != '/': url += "/" url += config_url ...
python
{ "resource": "" }
q234802
get_params
train
def get_params(): """ Get params definition from ElasticOcean and from all the backends """ parser = get_params_parser() args = parser.parse_args() if not args.enrich_only and not args.only_identities and not args.only_studies: if not args.index: # Check that the raw index name is ...
python
{ "resource": "" }
q234803
get_time_diff_days
train
def get_time_diff_days(start_txt, end_txt): ''' Number of days between two days ''' if start_txt is None or end_txt is None: return None start = parser.parse(start_txt) end = parser.parse(end_txt) seconds_day = float(60 * 60 * 24) diff_days = \ (end - start).total_seconds() /...
python
{ "resource": "" }
q234804
JiraEnrich.enrich_fields
train
def enrich_fields(cls, fields, eitem): """Enrich the fields property of an issue. Loops through al properties in issue['fields'], using those that are relevant to enrich eitem with new properties. Those properties are user defined, depending on options configured in Jira. For ex...
python
{ "resource": "" }
q234805
MediaWikiEnrich.get_review_sh
train
def get_review_sh(self, revision, item): """ Add sorting hat enrichment fields for the author of the revision """ identity = self.get_sh_identity(revision) update = parser.parse(item[self.get_field_date()]) erevision = self.get_item_sh_fields(identity, update) return erevision
python
{ "resource": "" }
q234806
GitHubEnrich.get_github_cache
train
def get_github_cache(self, kind, key_): """ Get cache data for items of _type using key_ as the cache dict key """ cache = {} res_size = 100 # best size? from_ = 0 index_github = "github/" + kind url = self.elastic.url + "/" + index_github url += "/_search" + ...
python
{ "resource": "" }
q234807
GitHubEnrich.get_time_to_first_attention
train
def get_time_to_first_attention(self, item): """Get the first date at which a comment or reaction was made to the issue by someone other than the user who created the issue """ comment_dates = [str_to_datetime(comment['created_at']) for comment in item['comments_data'] ...
python
{ "resource": "" }
q234808
GitHubEnrich.get_time_to_merge_request_response
train
def get_time_to_merge_request_response(self, item): """Get the first date at which a review was made on the PR by someone other than the user who created the PR """ review_dates = [str_to_datetime(review['created_at']) for review in item['review_comments_data'] if...
python
{ "resource": "" }
q234809
CratesEnrich.get_rich_events
train
def get_rich_events(self, item): """ In the events there are some common fields with the crate. The name of the field must be the same in the create and in the downloads event so we can filer using it in crate and event at the same time. * Fields that don't change: the field doe...
python
{ "resource": "" }
q234810
TwitterEnrich.get_item_project
train
def get_item_project(self, eitem): """ Get project mapping enrichment field. Twitter mappings is pretty special so it needs a special implementacion. """ project = None eitem_project = {} ds_name = self.get_connector_name() # data source name in projects map ...
python
{ "resource": "" }
q234811
JenkinsEnrich.get_fields_from_job_name
train
def get_fields_from_job_name(self, job_name): """Analyze a Jenkins job name, producing a dictionary The produced dictionary will include information about the category and subcategory of the job name, and any extra information which could be useful. For each deployment of a Jen...
python
{ "resource": "" }
q234812
JenkinsEnrich.extract_builton
train
def extract_builton(self, built_on, regex): """Extracts node name using a regular expression. Node name is expected to be group 1. """ pattern = re.compile(regex, re.M | re.I) match = pattern.search(built_on) if match and len(match.groups()) >= 1: node_name = ...
python
{ "resource": "" }
q234813
onion_study
train
def onion_study(in_conn, out_conn, data_source): """Build and index for onion from a given Git index. :param in_conn: ESPandasConnector to read from. :param out_conn: ESPandasConnector to write to. :param data_source: name of the date source to generate onion from. :return: number of documents writ...
python
{ "resource": "" }
q234814
ESOnionConnector.read_block
train
def read_block(self, size=None, from_date=None): """Read author commits by Quarter, Org and Project. :param from_date: not used here. Incremental mode not supported yet. :param size: not used here. :return: DataFrame with commit count per author, split by quarter, org and project. ...
python
{ "resource": "" }
q234815
ESOnionConnector.__quarters
train
def __quarters(self, from_date=None): """Get a set of quarters with available items from a given index date. :param from_date: :return: list of `pandas.Period` corresponding to quarters """ s = Search(using=self._es_conn, index=self._es_index) if from_date: #...
python
{ "resource": "" }
q234816
ESOnionConnector.__list_uniques
train
def __list_uniques(self, date_range, field_name): """Retrieve a list of unique values in a given field within a date range. :param date_range: :param field_name: :return: list of unique values. """ # Get project list s = Search(using=self._es_conn, index=self._e...
python
{ "resource": "" }
q234817
ESOnionConnector.__build_dataframe
train
def __build_dataframe(self, timing, project_name=None, org_name=None): """Build a DataFrame from a time bucket. :param timing: :param project_name: :param org_name: :return: """ date_list = [] uuid_list = [] name_list = [] contribs_list = ...
python
{ "resource": "" }
q234818
OnionStudy.process
train
def process(self, items_block): """Process a DataFrame to compute Onion. :param items_block: items to be processed. Expects to find a pandas DataFrame. """ logger.info(self.__log_prefix + " Authors to process: " + str(len(items_block))) onion_enrich = Onion(items_block) ...
python
{ "resource": "" }
q234819
GrimoireLibProjects.get_projects
train
def get_projects(self): """ Get the projects list from database """ repos_list = [] gerrit_projects_db = self.projects_db db = Database(user="root", passwd="", host="localhost", port=3306, scrdb=None, shdb=gerrit_projects_db, prjdb=None) sql = """ ...
python
{ "resource": "" }
q234820
metadata
train
def metadata(func): """Add metadata to an item. Decorator that adds metadata to a given item such as the gelk revision used. """ @functools.wraps(func) def decorator(self, *args, **kwargs): eitem = func(self, *args, **kwargs) metadata = { 'metadata__gelk_version': s...
python
{ "resource": "" }
q234821
Enrich.get_grimoire_fields
train
def get_grimoire_fields(self, creation_date, item_name): """ Return common grimoire fields for all data sources """ grimoire_date = None try: grimoire_date = str_to_datetime(creation_date).isoformat() except Exception as ex: pass name = "is_" + self.get_...
python
{ "resource": "" }
q234822
Enrich.add_project_levels
train
def add_project_levels(cls, project): """ Add project sub levels extra items """ eitem_path = '' eitem_project_levels = {} if project is not None: subprojects = project.split('.') for i in range(0, len(subprojects)): if i > 0: ...
python
{ "resource": "" }
q234823
Enrich.get_item_metadata
train
def get_item_metadata(self, eitem): """ In the projects.json file, inside each project, there is a field called "meta" which has a dictionary with fields to be added to the enriched items for this project. This fields must be added with the prefix cm_ (custom metadata). This me...
python
{ "resource": "" }
q234824
Enrich.get_domain
train
def get_domain(self, identity): """ Get the domain from a SH identity """ domain = None if identity['email']: try: domain = identity['email'].split("@")[1] except IndexError: # logger.warning("Bad email format: %s" % (identity['email'])) ...
python
{ "resource": "" }
q234825
Enrich.get_enrollment
train
def get_enrollment(self, uuid, item_date): """ Get the enrollment for the uuid when the item was done """ # item_date must be offset-naive (utc) if item_date and item_date.tzinfo: item_date = (item_date - item_date.utcoffset()).replace(tzinfo=None) enrollments = self.get_enr...
python
{ "resource": "" }
q234826
Enrich.__get_item_sh_fields_empty
train
def __get_item_sh_fields_empty(self, rol, undefined=False): """ Return a SH identity with all fields to empty_field """ # If empty_field is None, the fields do not appear in index patterns empty_field = '' if not undefined else '-- UNDEFINED --' return { rol + "_id": empty_fi...
python
{ "resource": "" }
q234827
Enrich.get_item_sh_fields
train
def get_item_sh_fields(self, identity=None, item_date=None, sh_id=None, rol='author'): """ Get standard SH fields from a SH identity """ eitem_sh = self.__get_item_sh_fields_empty(rol) if identity: # Use the identity to get the SortingHat identity ...
python
{ "resource": "" }
q234828
Enrich.get_item_sh
train
def get_item_sh(self, item, roles=None, date_field=None): """ Add sorting hat enrichment fields for different roles If there are no roles, just add the author fields. """ eitem_sh = {} # Item enriched author_field = self.get_field_author() if not roles: ...
python
{ "resource": "" }
q234829
Enrich.get_sh_ids
train
def get_sh_ids(self, identity, backend_name): """ Return the Sorting Hat id and uuid for an identity """ # Convert the dict to tuple so it is hashable identity_tuple = tuple(identity.items()) sh_ids = self.__get_sh_ids_cache(identity_tuple, backend_name) return sh_ids
python
{ "resource": "" }
q234830
ElasticItems.get_repository_filter_raw
train
def get_repository_filter_raw(self, term=False): """ Returns the filter to be used in queries in a repository items """ perceval_backend_name = self.get_connector_name() filter_ = get_repository_filter(self.perceval_backend, perceval_backend_name, term) return filter_
python
{ "resource": "" }
q234831
ElasticItems.set_filter_raw
train
def set_filter_raw(self, filter_raw): """Filter to be used when getting items from Ocean index""" self.filter_raw = filter_raw self.filter_raw_dict = [] splitted = re.compile(FILTER_SEPARATOR).split(filter_raw) for fltr_raw in splitted: fltr = self.__process_filter(...
python
{ "resource": "" }
q234832
ElasticItems.set_filter_raw_should
train
def set_filter_raw_should(self, filter_raw_should): """Bool filter should to be used when getting items from Ocean index""" self.filter_raw_should = filter_raw_should self.filter_raw_should_dict = [] splitted = re.compile(FILTER_SEPARATOR).split(filter_raw_should) for fltr_raw ...
python
{ "resource": "" }
q234833
ElasticItems.fetch
train
def fetch(self, _filter=None, ignore_incremental=False): """ Fetch the items from raw or enriched index. An optional _filter could be provided to filter the data collected """ logger.debug("Creating a elastic items generator.") scroll_id = None page = self.get_elastic_items(scr...
python
{ "resource": "" }
q234834
find_uuid
train
def find_uuid(es_url, index): """ Find the unique identifier field for a given index """ uid_field = None # Get the first item to detect the data source and raw/enriched type res = requests.get('%s/%s/_search?size=1' % (es_url, index)) first_item = res.json()['hits']['hits'][0]['_source'] fiel...
python
{ "resource": "" }
q234835
find_mapping
train
def find_mapping(es_url, index): """ Find the mapping given an index """ mapping = None backend = find_perceval_backend(es_url, index) if backend: mapping = backend.get_elastic_mappings() if mapping: logging.debug("MAPPING FOUND:\n%s", json.dumps(json.loads(mapping['items']), ind...
python
{ "resource": "" }
q234836
get_elastic_items
train
def get_elastic_items(elastic, elastic_scroll_id=None, limit=None): """ Get the items from the index """ scroll_size = limit if not limit: scroll_size = DEFAULT_LIMIT if not elastic: return None url = elastic.index_url max_process_items_pack_time = "5m" # 10 minutes url +...
python
{ "resource": "" }
q234837
fetch
train
def fetch(elastic, backend, limit=None, search_after_value=None, scroll=True): """ Fetch the items from raw or enriched index """ logging.debug("Creating a elastic items generator.") elastic_scroll_id = None search_after = search_after_value while True: if scroll: rjson = get_...
python
{ "resource": "" }
q234838
export_items
train
def export_items(elastic_url, in_index, out_index, elastic_url_out=None, search_after=False, search_after_value=None, limit=None, copy=False): """ Export items from in_index to out_index using the correct mapping """ if not limit: limit = DEFAULT_LIMIT if search_a...
python
{ "resource": "" }
q234839
GerritEnrich._fix_review_dates
train
def _fix_review_dates(self, item): """Convert dates so ES detect them""" for date_field in ['timestamp', 'createdOn', 'lastUpdated']: if date_field in item.keys(): date_ts = item[date_field] item[date_field] = unixtime_to_datetime(date_ts).isoformat() ...
python
{ "resource": "" }
q234840
BugzillaEnrich.get_sh_identity
train
def get_sh_identity(self, item, identity_field=None): """ Return a Sorting Hat identity using bugzilla user data """ def fill_list_identity(identity, user_list_data): """ Fill identity with user data in first item in list """ identity['username'] = user_list_data[0]['__text__'] ...
python
{ "resource": "" }
q234841
CeresBase.analyze
train
def analyze(self): """Populate an enriched index by processing input items in blocks. :return: total number of out_items written. """ from_date = self._out.latest_date() if from_date: logger.info("Reading items since " + from_date) else: logger.in...
python
{ "resource": "" }
q234842
ESConnector.read_item
train
def read_item(self, from_date=None): """Read items and return them one by one. :param from_date: start date for incremental reading. :return: next single item when any available. :raises ValueError: `metadata__timestamp` field not found in index :raises NotFoundError: index not ...
python
{ "resource": "" }
q234843
ESConnector.read_block
train
def read_block(self, size, from_date=None): """Read items and return them in blocks. :param from_date: start date for incremental reading. :param size: block size. :return: next block of items when any available. :raises ValueError: `metadata__timestamp` field not found in index...
python
{ "resource": "" }
q234844
ESConnector.write
train
def write(self, items): """Upload items to ElasticSearch. :param items: items to be uploaded. """ if self._read_only: raise IOError("Cannot write, Connector created as Read Only") # Uploading info to the new ES docs = [] for item in items: ...
python
{ "resource": "" }
q234845
ESConnector.create_alias
train
def create_alias(self, alias_name): """Creates an alias pointing to the index configured in this connection""" return self._es_conn.indices.put_alias(index=self._es_index, name=alias_name)
python
{ "resource": "" }
q234846
ESConnector.exists_alias
train
def exists_alias(self, alias_name, index_name=None): """Check whether or not the given alias exists :return: True if alias already exist""" return self._es_conn.indices.exists_alias(index=index_name, name=alias_name)
python
{ "resource": "" }
q234847
ESConnector._build_search_query
train
def _build_search_query(self, from_date): """Build an ElasticSearch search query to retrieve items for read methods. :param from_date: date to start retrieving items from. :return: JSON query in dict format """ sort = [{self._sort_on_field: {"order": "asc"}}] filters =...
python
{ "resource": "" }
q234848
ElasticOcean.add_params
train
def add_params(cls, cmdline_parser): """ Shared params in all backends """ 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.add_argume...
python
{ "resource": "" }
q234849
ElasticOcean.get_p2o_params_from_url
train
def get_p2o_params_from_url(cls, url): """ Get the p2o params given a URL for the data source """ # 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 = ...
python
{ "resource": "" }
q234850
ElasticOcean.feed
train
def feed(self, from_date=None, from_offset=None, category=None, latest_items=None, arthur_items=None, filter_classified=None): """ Feed data in Elastic from Perceval or Arthur """ if self.fetch_archive: items = self.perceval_backend.fetch_from_archive() self.feed_it...
python
{ "resource": "" }
q234851
GitEnrich.get_identities
train
def get_identities(self, item): """ Return the identities from an item. If the repo is in GitHub, get the usernames from GitHub. """ def add_sh_github_identity(user, user_field, rol): """ Add a new github identity to SH if it does not exists """ github_repo = None ...
python
{ "resource": "" }
q234852
GitEnrich.__fix_field_date
train
def __fix_field_date(self, item, attribute): """Fix possible errors in the field date""" 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", attribute,...
python
{ "resource": "" }
q234853
GitEnrich.update_items
train
def update_items(self, ocean_backend, enrich_backend): """Retrieve the commits not present in the original repository and delete the corresponding documents from the raw and enriched indexes""" fltr = { 'name': 'origin', 'value': [self.perceval_backend.origin] } ...
python
{ "resource": "" }
q234854
GitEnrich.add_commit_branches
train
def add_commit_branches(self, git_repo, enrich_backend): """Add the information about branches to the documents representing commits in the enriched index. Branches are obtained using the command `git ls-remote`, then for each branch, the list of commits is retrieved via the command `git rev-lis...
python
{ "resource": "" }
q234855
find_ds_mapping
train
def find_ds_mapping(data_source, es_major_version): """ Find the mapping given a perceval data source :param data_source: name of the perceval data source :param es_major_version: string with the major version for Elasticsearch :return: a dict with the mappings (raw and enriched) """ mappin...
python
{ "resource": "" }
q234856
areas_of_code
train
def areas_of_code(git_enrich, in_conn, out_conn, block_size=100): """Build and index for areas of code from a given Perceval RAW index. :param block_size: size of items block. :param git_enrich: GitEnrich object to deal with SortingHat affiliations. :param in_conn: ESPandasConnector to read from. :...
python
{ "resource": "" }
q234857
AreasOfCode.process
train
def process(self, items_block): """Process items to add file related information. Eventize items creating one new item per each file found in the commit (excluding files with no actions performed on them). For each event, file path, file name, path parts, file type and file extension ar...
python
{ "resource": "" }
q234858
get_time_diff_days
train
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) is not datetime.datetime: end = parser...
python
{ "resource": "" }
q234859
PhabricatorEnrich.__fill_phab_ids
train
def __fill_phab_ids(self, item): """ Get mappings between phab ids and names """ 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']: ...
python
{ "resource": "" }
q234860
Tab.starting_at
train
def starting_at(self, datetime_or_str): """ Set the starting time for the cron job. If not specified, the starting time will always be the beginning of the interval that is current when the cron is started. :param datetime_or_str: a datetime object or a string that dateutil.parser can ...
python
{ "resource": "" }
q234861
Tab.run
train
def run(self, func, *func_args, **func__kwargs): """ Specify the function to run at the scheduled times :param func: a callable :param func_args: the args to the callable :param func__kwargs: the kwargs to the callable :return: """ self._func = func ...
python
{ "resource": "" }
q234862
Tab._get_target
train
def _get_target(self): """ returns a callable with no arguments designed to be the target of a Subprocess """ 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 ta...
python
{ "resource": "" }
q234863
wrapped_target
train
def wrapped_target(target, q_stdout, q_stderr, q_error, robust, name, *args, **kwargs): # pragma: no cover """ Wraps a target with queues replacing stdout and stderr """ import sys sys.stdout = IOQueue(q_stdout) sys.stderr = IOQueue(q_stderr) try: target(*args, **kwargs) except...
python
{ "resource": "" }
q234864
ProcessMonitor.loop
train
def loop(self, max_seconds=None): """ Main loop for the process. This will run continuously until maxiter """ loop_started = datetime.datetime.now() self._is_running = True while self._is_running: self.process_error_queue(self.q_error) if max_se...
python
{ "resource": "" }
q234865
escape
train
def escape(string, escape_pattern): """Assistant function for string escaping""" try: return string.translate(escape_pattern) except AttributeError: warnings.warn("Non-string-like data passed. " "Attempting to convert to 'str'.") return str(string).translate(tag...
python
{ "resource": "" }
q234866
_make_serializer
train
def _make_serializer(meas, schema, rm_none, extra_tags, placeholder): # noqa: C901 """Factory of line protocol parsers""" _validate_schema(schema, placeholder) tags = [] fields = [] ts = None meas = meas for k, t in schema.items(): if t is MEASUREMENT: meas = f"{{i.{k}}}...
python
{ "resource": "" }
q234867
lineprotocol
train
def lineprotocol( cls=None, *, schema: Optional[Mapping[str, type]] = None, rm_none: bool = False, extra_tags: Optional[Mapping[str, str]] = None, placeholder: bool = False ): """Adds ``to_lineprotocol`` method to arbitrary user-defined classes :param cls: Class ...
python
{ "resource": "" }
q234868
_serialize_fields
train
def _serialize_fields(point): """Field values can be floats, integers, strings, or Booleans.""" 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(...
python
{ "resource": "" }
q234869
serialize
train
def serialize(data, measurement=None, tag_columns=None, **extra_tags): """Converts input data into line protocol format""" if isinstance(data, bytes): return data elif isinstance(data, str): return data.encode('utf-8') elif hasattr(data, 'to_lineprotocol'): return data.to_linepro...
python
{ "resource": "" }
q234870
iterpoints
train
def iterpoints(resp: dict, parser: Optional[Callable] = None) -> Iterator[Any]: """Iterates a response JSON yielding data point by point. Can be used with both regular and chunked responses. By default, returns just a plain list of values representing each point, without column names, or other metadata...
python
{ "resource": "" }
q234871
parse
train
def parse(resp) -> DataFrameType: """Makes a dictionary of DataFrames from a response object""" statements = [] for statement in resp['results']: series = {} for s in statement.get('series', []): series[_get_name(s)] = _drop_zero_index(_serializer(s)) statements.append(se...
python
{ "resource": "" }
q234872
_itertuples
train
def _itertuples(df): """Custom implementation of ``DataFrame.itertuples`` that returns plain tuples instead of namedtuples. About 50% faster. """ cols = [df.iloc[:, k] for k in range(len(df.columns))] return zip(df.index, *cols)
python
{ "resource": "" }
q234873
serialize
train
def serialize(df, measurement, tag_columns=None, **extra_tags) -> bytes: """Converts a Pandas DataFrame into line protocol format""" # Pre-processing if measurement is None: raise ValueError("Missing 'measurement'") if not isinstance(df.index, pd.DatetimeIndex): raise ValueError('DataFra...
python
{ "resource": "" }
q234874
runner
train
def runner(coro): """Function execution decorator.""" @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
python
{ "resource": "" }
q234875
InfluxDBClient._check_error
train
def _check_error(response): """Checks for JSON error messages and raises Python exception""" if 'error' in response: raise InfluxDBError(response['error']) elif 'results' in response: for statement in response['results']: if 'error' in statement: ...
python
{ "resource": "" }
q234876
create_magic_packet
train
def create_magic_packet(macaddress): """ Create a magic packet. A magic packet is a packet that can be used with the for wake on lan protocol to wake up a computer. The packet is constructed from the mac address given as a parameter. Args: macaddress (str): the mac address that should ...
python
{ "resource": "" }
q234877
send_magic_packet
train
def send_magic_packet(*macs, **kwargs): """ Wake up computers having any of the given mac addresses. Wake on lan must be enabled on the host device. Args: macs (str): One or more macaddresses of machines to wake. Keyword Args: ip_address (str): the ip address of the host to send t...
python
{ "resource": "" }
q234878
main
train
def main(argv=None): """ Run wake on lan as a CLI application. """ parser = argparse.ArgumentParser( description='Wake one or more computers using the wake on lan' ' protocol.') parser.add_argument( 'macs', metavar='mac address', nargs='+', ...
python
{ "resource": "" }
q234879
mjml
train
def mjml(parser, token): """ Compile MJML template after render django template. Usage: {% mjml %} .. MJML template code .. {% endmjml %} """ nodelist = parser.parse(('endmjml',)) parser.delete_first_token() tokens = token.split_contents() if len(tokens) != 1...
python
{ "resource": "" }
q234880
HeaderParser.parse_header_line
train
def parse_header_line(self, line): """docstring for parse_header_line""" self.header = line[1:].rstrip().split('\t') if len(self.header) < 9: self.header = line[1:].rstrip().split() self.individuals = self.header[9:]
python
{ "resource": "" }
q234881
HeaderParser.print_header
train
def print_header(self): """Returns a list with the header lines if proper format""" 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...
python
{ "resource": "" }
q234882
VCFParser.add_variant
train
def add_variant(self, chrom, pos, rs_id, ref, alt, qual, filt, info, form=None, genotypes=[]): """ Add a variant to the parser. This function is for building a vcf. It takes the relevant parameters and make a vcf variant in the proper format. """ variant_info = ...
python
{ "resource": "" }
q234883
PiazzaRPC.content_get
train
def content_get(self, cid, nid=None): """Get data from post `cid` in network `nid` :type nid: str :param nid: This is the ID of the network (or class) from which to query posts. This is optional and only to override the existing `network_id` entered when created the cla...
python
{ "resource": "" }
q234884
PiazzaRPC.content_create
train
def content_create(self, params): """Create a post or followup. :type params: dict :param params: A dict of options to pass to the endpoint. Depends on the specific type of content being created. :returns: Python object containing returned data """ r = self....
python
{ "resource": "" }
q234885
PiazzaRPC.add_students
train
def add_students(self, student_emails, nid=None): """Enroll students in a network `nid`. Piazza will email these students with instructions to activate their account. :type student_emails: list of str :param student_emails: A listing of email addresses to enroll in...
python
{ "resource": "" }
q234886
PiazzaRPC.get_all_users
train
def get_all_users(self, nid=None): """Get a listing of data for each user in a network `nid` :type nid: str :param nid: This is the ID of the network to get users from. This is optional and only to override the existing `network_id` entered when created the class ...
python
{ "resource": "" }
q234887
PiazzaRPC.get_users
train
def get_users(self, user_ids, nid=None): """Get a listing of data for specific users `user_ids` in a network `nid` :type user_ids: list of str :param user_ids: a list of user ids. These are the same ids that are returned by get_all_users. :type nid: str :pa...
python
{ "resource": "" }
q234888
PiazzaRPC.remove_users
train
def remove_users(self, user_ids, nid=None): """Remove users from a network `nid` :type user_ids: list of str :param user_ids: a list of user ids. These are the same ids that are returned by get_all_users. :type nid: str :param nid: This is the ID of the network to ...
python
{ "resource": "" }
q234889
PiazzaRPC.get_my_feed
train
def get_my_feed(self, limit=150, offset=20, sort="updated", nid=None): """Get my feed :type limit: int :param limit: Number of posts from feed to get, starting from ``offset`` :type offset: int :param offset: Offset starting from bottom of feed :type sort: str :p...
python
{ "resource": "" }
q234890
PiazzaRPC.filter_feed
train
def filter_feed(self, updated=False, following=False, folder=False, filter_folder="", sort="updated", nid=None): """Get filtered feed Only one filter type (updated, following, folder) is possible. :type nid: str :param nid: This is the ID of the network to get the ...
python
{ "resource": "" }
q234891
PiazzaRPC.search
train
def search(self, query, nid=None): """Search for posts with ``query`` :type nid: str :param nid: This is the ID of the network to get the feed from. This is optional and only to override the existing `network_id` entered when created the class :type query: str ...
python
{ "resource": "" }
q234892
PiazzaRPC.get_stats
train
def get_stats(self, nid=None): """Get statistics for class :type nid: str :param nid: This is the ID of the network to get stats from. This is optional and only to override the existing `network_id` entered when created the class """ r = self.request( ...
python
{ "resource": "" }
q234893
PiazzaRPC.request
train
def request(self, method, data=None, nid=None, nid_key='nid', api_type="logic", return_response=False): """Get data from arbitrary Piazza API endpoint `method` in network `nid` :type method: str :param method: An internal Piazza API method name like `content.get` or...
python
{ "resource": "" }
q234894
PiazzaRPC._handle_error
train
def _handle_error(self, result, err_msg): """Check result for error :type result: dict :param result: response body :type err_msg: str :param err_msg: The message given to the :class:`RequestError` instance raised :returns: Actual result from result :...
python
{ "resource": "" }
q234895
Piazza.get_user_classes
train
def get_user_classes(self): """Get list of the current user's classes. This is a subset of the information returned by the call to ``get_user_status``. :returns: Classes of currently authenticated user :rtype: list """ # Previously getting classes from profile (such a li...
python
{ "resource": "" }
q234896
nonce
train
def nonce(): """ Returns a new nonce to be used with the Piazza API. """ nonce_part1 = _int2base(int(_time()*1000), 36) nonce_part2 = _int2base(round(_random()*1679616), 36) return "{}{}".format(nonce_part1, nonce_part2)
python
{ "resource": "" }
q234897
Network.iter_all_posts
train
def iter_all_posts(self, limit=None): """Get all posts visible to the current user This grabs you current feed and ids of all posts from it; each post is then individually fetched. This method does not go against a bulk endpoint; it retrieves each post individually, so a caution...
python
{ "resource": "" }
q234898
Network.create_post
train
def create_post(self, post_type, post_folders, post_subject, post_content, is_announcement=0, bypass_email=0, anonymous=False): """Create a post It seems like if the post has `<p>` tags, then it's treated as HTML, but is treated as text otherwise. You'll want to provide `content` accord...
python
{ "resource": "" }
q234899
Network.create_followup
train
def create_followup(self, post, content, anonymous=False): """Create a follow-up on a post `post`. It seems like if the post has `<p>` tags, then it's treated as HTML, but is treated as text otherwise. You'll want to provide `content` accordingly. :type post: dict|str|int ...
python
{ "resource": "" }